问:
Can/should the Single Responsibility Principle be applied to new code?
The principle is defined as modules having one reason to change. My question is, surely these reasons to change are not known until the code actually starts to change?? Pretty much every piece of code has numerous reasons why it could possibly change but surely attempting to anticipate all of these and design your code with this in mind would end up with very poor code. Isn't it a better idea to only really start to apply SRP when requests to change the code start coming in? More specifically, when a piece of code has changed more than once for more than one reason, thus proving it has more than one reason to change. It sounds very anti-Agile to attempt to guess reasons for change.

An example would be a piece of code which prints a document. A request comes in to change it to print to PDF and then a second request is made to change it to apply some different formatting to the document. At this point you have proof of more than a single reason to change (and violation of SRP) and should make the appropriate refactoring.

答:
Flup is headed in the right direction. The "single responsibility principle" originally applied to procedures. For example, Dennis Ritchie would say that a function should do one thing and do it well. Then, in C++, Bjarne Stroustrup would say that a class should do one thing and do it well.

Notice that, except as rules of thumb, these two formally have little or nothing to do with each other. They cater only to what is convenient to express in the programming language. Well, that's something. But it's quite a different story than what flup is driving at.

Modern (i.e., agile and DDD) implementations focus more on what's important to the business than on what the programming language can express. The surprising part is that programming languages haven't caught up yet. Old FORTRAN-like languages capture responsibilities that fit the major conceptual models of the time: the processes one applied to each card as it went through the card reader, or (as in C) the processing that accompanied each interrupt. Then came ADT languages, which had matured to the point of capturing what the DDD people would later re-invent as being important (though Jim Neighbors had most of this figured out, published, and in use by 1968): what today we call classes. (They're NOT modules.)

This step was less an evolution than a pendulum swing. As the pendulum swung to data we lost the use case modeling inherent in FORTRAN. That's fine when your primary focus involves the data or the shapes on a screen. It's a great model for programs like PowerPoint, or at least for its simple operations.

What got lost is system responsibilities. We don't sell the elements of DDD. And we don't well class methods. We sell system responsibilities. At some level, you need to design your system around the single responsibility principle.

So if you look at people like Rebecca Wirfs-Brock, or me, who used to talk about class methods, we're now talking in terms of use cases. That's what we sell. Those are the system operations. A use case should have a single responsibility. A use case is rarely an architectural unit. But everyone was trying to pretend it was. Witness the SOA people, for example.

This is why I'm excited about Trygve Reenskaug's DCI architecture — which is what's described in the Lean Architecture book above. It finally gives some real stature to what used to be an arbitrary and mystical obeissance to "single responsibility" — as one finds in most of the argumentation above. That stature relates to human mental models: end users first AND programmers second. It relates to business concerns. And, almost by happenstance, it encapsulates change as flup challenges us.

The single-responsibility principle as we know it is either a dinosaur left over from its days of origin or a hobby horse that we use as a substitute for understanding. You need to leave a few of these hobby horses behind to do great software. And that requires thinking out of the box. Keeping things simple and easy to understand works only when the problem is simple and easy to understand. I'm not terribly interested in those solutions: they're not typical, and it's not where the challenge lies.


答:
"Print" is very much like "view" in MVC. Anyone who understands the basics of objects would understand that.

It is a system responsibility. It is implemented as a mechanism — MVC — that involves a printer (the View), the thing being printed (the Module) and the printer request and options (from the Controller).

Trying to localize this as a class or module responsibility is asinine and reflects 30-year-old thinking. We've learned a lot since then, and it's amply evidenced in the literature and in the code of mature programmers.

ContentLicense: CC BY-SA 3.0

Title: Can/should the Single Responsibility Principle be applied to new code?

Body:
The principle is defined as modules having one reason to change. My question is, surely these reasons to change are not known until the code actually starts to change?? Pretty much every piece of code has numerous reasons why it could possibly change but surely attempting to anticipate all of these and design your code with this in mind would end up with very poor code. Isn't it a better idea to only really start to apply SRP when requests to change the code start coming in? More specifically, when a piece of code has changed more than once for more than one reason, thus proving it has more than one reason to change. It sounds very anti-Agile to attempt to guess reasons for change.

An example would be a piece of code which prints a document. A request comes in to change it to print to PDF and then a second request is made to change it to apply some different formatting to the document. At this point you have proof of more than a single reason to change (and violation of SRP) and should make the appropriate refactoring.


问:
Is there a common mathematical symbology for collections?
I am being asked to define several of my algorithms in mathematical terms to describe my work to a customer.  I am trying to determine if anybody knows whether common operators for collections like sequences, lists, tuples, etc have been defined. If so, is there a good reference that I could be pointed to. Thanks. I am interested in the actual symbols used.  I am wondering if the following would make sense or be appropiate to anybody.

Given two sequences (or strings):

S = (A, B, C) and T = (A, D, H)

In my mind, the intersection of these sequences would look like S ∩ T = (A) and the union of these sequences would be S ∪ T = (A, B, C, A, D, H)

答:
Sequences or lists in which there is an implied ordering of the elements are commonly delimited between ⟨ and ⟩. For example:

S = ⟨A, B, C⟩         (They look like , but taller. HTML entities are ⟨ and ⟩ )

If there is no order implied, use set notation.

S = {A, B, C}

Tuples, such as rows from a table or ordered pairs/triples, use parentheses:

car = (Toyota, Camry, 2010)

coordinates = (10, 45)

The union and intersection of sets are represented with the ∪ and ∩ symbols, as usual.

For lists, the operations are different. You concatenate lists rather than finding their union. This can be represented as S+T or simply ST (depending on who's watching).

As tuples are indivisible, the union or intersection of two of them is nonsensical.

You might want to ask this on https://cstheory.stackexchange.com/

ContentLicense: CC BY-SA 2.5

Body:
Sequences or lists in which there is an implied ordering of the elements are commonly delimited between ⟨ and ⟩. For example:

S = ⟨A, B, C⟩         (They look like <A, B, C>, but taller. HTML entities are &lang; and &rang; )

If there is no order implied, use set notation.

S = {A, B, C}

Tuples, such as rows from a table or ordered pairs/triples, use parentheses:

car = (Toyota, Camry, 2010)

coordinates = (10, 45)

The union and intersection of sets are represented with the ∪ and ∩ symbols, as usual.

For lists, the operations are different. You concatenate lists rather than finding their union. This can be represented as S+T or simply ST (depending on who's watching).

As tuples are indivisible, the union or intersection of two of them is nonsensical.

You might want to ask this on https://cstheory.stackexchange.com/


问:
Is there a reason that tests aren't written inline with the code that they test?
I've been reading a bit about Literate Programming recently, and it got me thinking... Well-written tests, especially BDD-style specs can do a better job at explaining what code does than prose does, and have the big advantage of verifying their own accuracy.

I've never seen tests written inline with the code that they test. Is this just because languages don't tend to make it simple to separate application and test code when written in the same source file (and nobody's made it easy), or is there a more principled reason that people separate test code from application code?

答:
This idea simply amounts to a "Self_Test" method within the context of an object-based or object-oriented design.  If using a compiled object-based language like Ada, all the self-test code will be marked by the compiler as unused (never invoked) during the production compilation, and therefore it will all be optimized away - none of it will appear in the resulting executable.

Using a "Self_Test" method is an extremely good idea, and if programmers were really concerned with quality they would all be be doing it.  One important issue, though, is that the "Self_Test" method needs to have intense discipline, in that it cannot access any of the implementation details and must instead rely only on all the other published methods within the object's specification.  Obviously, if the self test fails, the implementation will need to change.  The self test should be rigorously testing all the published properties of the object's methods, but never ever relying in any way upon any details of any specific implementation.

Object-based and object-oriented languages frequently do provide exactly that type of discipline with respect to methods external to the tested object (they enforce the object's specification, preventing any access to its implementation details and raising a compilation error if any such attempt is detected).  But the object's own internal methods are all given complete access to every implementation detail.  So the self test method is in a unique situation: it needs to be an internal method because of its nature (self test is obviously a method of the object being tested), yet it needs to receive all the compiler discipline of an external method (it has to be independent of the object's implementation details).  Few if any programming languages provide the capability to discipline an object's internal method as if it were an external method.  So this is an important programming language design issue.

In the absence of proper programming language support, the best way to do it is to create a companion object.  In other words, for every object you code (let's call it "Big_Object"), you also create a second, companion object whose name consists of a standard suffix concatenated with the name of the "real" object (in this case, "Big_Object_Self_Test"), and whose specification consists of a single method ("Big_Object_Self_Test.Self_Test (This_Big_Object : Big_Object) return Boolean;").  The companion object will then depend upon the specification of the main object, and the compiler will fully enforce all of the discipline of that specification against the companion object's implementation.


问:
Should code and data be treated seperately?
Is it really necessary to differentiate between code and data ?
Is there any language where such differentiation is not there ? </p>

答:
Yes.  Properly segregating code and data is very important.

Code is written beforehand and executed, generally at a fairly high level of trust.  Data comes from external sources, and not necessarily from a source that ought to be trusted.  And the most destructive of hacks (such as buffer overflows and SQL injections) come from an untrustworthy user finding a way to cause the computer to treat data as code.

Some programming languages, mostly those influenced by Lisp, as World Engineer noted, like to conflate the two.  This is almost like the language designer saying "here, you don't need to write your own security holes; we've given you a free arbitrary code execution vulnerability as a fundamental language feature!"


答:
In Lisp dialects, the code and data are both represented as lists, and this facilitates manipulation of code as data, because it is data.  But it is also useful to keep in mind the distinction: if you try to run some list that isn't code, you will get an error, rather than useful output.  Sometimes it is more useful to think of them as the same thing, sometimes it is more useful to think of them as different.

For example, a list of the integers from 1 to 5 would look like this in Lisp: (1 2 3 4 5).  If you try to run it, you'll get an error that complains that the number 1 is not a function.  You could think of that list as a piece of broken code, but it would be more useful to think of it as data, not code.  If you wrote (+ 2 3 4 5), then that is a function call of the '+' function on the arguments 2, 3, 4, and 5.  If you wrote it like this '(+ 2 3 4 5) (note the single quote at the front), then it would be a piece of code that's treated like data, and it would not be run just yet (although you could run it later).

Title: Should code and data be treated seperately?

Body:
Is it really necessary to differentiate between code and data ?
Is there any language where such differentiation is not there ? </p>


问:
Retrieving maximum value from a range in unsorted array
I have an unsorted array. I have queries in which I give a range and then the maximum value from that range has to returned.
For example:

```<code>array[]={23,17,9,45,78,2,4,6,90,1};
query(both inclusive): 2 6
answer: 78
</code>```

Which algorithm or data structure do I construct to quickly retrieve maximum value from any range. (There are a lot of queries)

EDIT:
This is indeed a simple version of the actual problem. I can have the array size as large as 100000 and the number of queries upto 100000. So I definitely require some preprocessing which'll facilitate a fast query response.

答:
The best algorithm would be in O(n) time as below
let start, end be the index of the bounds of range</p>

```<code>int findMax(int[] a, start, end) {
   max = Integer.MIN; // initialize to minimum Integer

   for(int i=start; i <= end; i++)
      if ( a[i] > max )
         max = a[i];

   return max;
}
</code>```

Body:
The best algorithm would be in O(n) time as below
let start, end be the index of the bounds of range

int findMax(int[] a, start, end) {
   max = Integer.MIN; // initialize to minimum Integer

   for(int i=start; i <= end; i++)
      if ( a[i] > max )
         max = a[i];

   return max;
}


问:
Given a situation, and some conditions, verify is that situation is possible
Well it's a problem me and my friend had thought of, and well, haven't come up with anything to solve the following problem(I'll try to phrase it in the best way I can):

Given that there are n number of teams, and the number of matches each team has played, and that no team can play more than 2 matches with any other team, predict if the distribution of matches played by each team is possible.

P.S. : I am a Python Programmer, so (if possible) post only python code for explaining..

答:
This is a nice exercise in constraint propagation and combinatorics. Here are some ideas:

Clearly there are result distributions which are impossible. For instance, the total number of of wins must equals the total number of losses, and the total number of draws must be an even number.

If you draw up some example distributions by adding up actual results, you will start noticing more regularities. Each of those is another criterion for proving that a given distribution is impossible.

Showing that a distribution is possible is a little harder. The most direct proof is to give a concrete example of results which would result in the distribution you are given..

If you can't manage to construct one, the most straightforward algorithm to decide if there is one is to enumerate all possible pairings and see whether they fit. For instance, starting with the top-ranked team, you can conduct a complete search: have they won, lost, tied, or not yet played against the second-ranked team? (You said that there are return games, so this decision has to be made twice, but that doesn't change the basic idea of a complete search.) Either you find a matching configuration of results, or you have proved that there isn't one.

A complete search is expensive, but there are various constraints that you can use to prune the search space. For instance, you cannot assume more wins for a team than the input said they have, and the assumption of how A played against B must confirm to what you assume about B vs. A.


问:
Why do some programmers categorize C, Python, C++ differently? - regarding level
I am taking an introductory course on python and the instructor says that python is a high level language and C and C++ are low level languages. It's just confusing. I thought that C, C++, Python, Java, etc were all high level languages. </p>

<p>I was reading questions at stackoverflow on C, C++, etc and they all seem to refer to those languages as high level. It seems to me that some programmers use those terms interchangeably. </p>

答:
The line between the "low-level" and the "high-level" languages shifts from time to time.

For example:

Back in the days of UNIX, C was a high level language.

Today C doesn't have the structures like the mapping types(dictionaries), iterators etc. which today's high-level languages like Python have. So the line has shifted, and C has now fallen into the low-level group.

Low-Level Languages:

These languages are "close" to what the machine can execute (the lowest level being : Assembly Code!).

When working with these languages, the programmer has to think about the lowest level stuff like memory management.. You are close in that sense to the hardware, that you have to directly work with it.

High-level Languages:

These languages take you away from the hardware, as they manage things like memory themselves. When you work with these languages, memory is a factor(obviously), but you don't work with the hardware directly. Instead the language manages that, keeping you away (maybe higher) from the lower, hardware interface.


答:
The real issue that needs to be considered is "integrity of data".  Segregating code & data still leaves one open to corrupted data via buffer overruns.

Segregating code & data is a solution at one end of a spectrum, and very appropriate for languages (such as C) that enable indiscriminate changes to data (and, by extension, code if not segregated from the data).  It's an extreme and necessary solution to a fundamental problem in such languages.  Please note that I'm in no way suggesting that C is flawed - it was designed with such a feature for the "low level" work for which it was intended.  It was originally designed to be somewhere between assembly language and "high level languages".


问:
Payments and open source core developers
I'm not sure if there's an established protocol for this (even if it's not an official one), but thought those most experienced with open source might want to share with us.

I'm aware that random patches submitted to open source projects are never paid. They may be indirectly funded by a client but they're never paid for by the open source project itself.

But how about core developers? I heard for example that drupal has some 800 core developers behind it. Core developers means that they work on drupal core itself and together they push the main releases, so they're very important to the project. Of course drupal is just an example, but in general, is there any established protocol in the open source world that defines whether the company behind the project is expected to pay them and do these core developers expect such payment?

Any facts or first hand experiences?

答:
I covered this topic in detail in a blog post about donations to open-source projects.

The gist of it is this - once an open-source project reaches a certain size, one of several things can happen to allow it to continue existing (otherwise support and scope issues bring it down). There are 3 main ways to support an OS project at that stage:

A big company (Google, Microsoft, etc) "sponsors" the project and has paid developers from its staff working on it full-time. Some projects come out directly from those companies and naturally have this option baked in.

The project can transform into a real business, in the MySQL / Redhat mold. This means commercial licenses, paid support and customization / integration services. Otherwise some kind of bizdev opportunity that brings in a stream income (such as what Mozilla has with google by placing their search engine as the default one in Firefox).

A community of maintainers forms around the project with the original maintainer ceding control to allow others to contribute.

1 is unlikely and not something you can plan for while 2 is very difficult for most developers and most projects fail at that point. This a problem very dear to my heart, which is why I started Binpress (the company whose blog I linked to at the beginning), to provide a platform for developers to build those sustainable businesses on top of their open-source projects. From our experience this is a very viable model, and we've seen a lot of success recently in that space.


答:
No, it's definitely not necessary. The Van Neumann architecture, which practically all computers today are based upon, pioneered the idea of a stored program, which is nothing more than code stored as data.

That's at the hardware level though; at the software level, paradigms differ as to how closely data and code are intermingled (or, conversely, how sharply they need to be divided).

On one end of the spectrum, there's imperative programming, especially the procedural flavors - think Pascal, C, FORTRAN, BASIC (actual BASIC, not VB.NET or anything like that). In these languages, data and code are conceptually separate; you can take pointers to function addresses and pass them around, but other than that, code is code, and data is data. If you want to treat data as code, you have to pull quite some tricks, e.g. injecting some assembler code to jump to an address that contains your data.

On the other end, you'll find functional programming, where functions are data (in a super-hardcore FP idiom, functions are even the only kind of data you can have); but also logic programming (think Prolog), where the entire program is mostly just a data structure describing facts about the problem domain. And of course there's the dynamic camp, which gives you techniques like monkey-patching, duck typing, introspection / reflection, etc., to have your code inspect and modify itself at run time. Lisp (any Lisp, really) is a particularly interesting candidate here, because it combines functional programming and dynamic features.

In between, there's object-oriented programming; this idiom mainly inherits the imperative mindset of separate data and code, but at its core, it departs from it a bit by bundling related behavior (code) and state (data) into units (objects). Fast-forward to the point where the idiom has fully unraveled, and you see "design patterns" emerge, many of which pretty much replicate code-as-data features found in other idioms.

All that doesn't really answer your question though: should code and data be separated? Well, the fact that even the most hardcore code-data-separators occasionally use code generators, lookup tables, and similar techniques that mix them up should tell you that being religious about such a separation is ridiculous. There are quite some advantages to treating them as separate realms, and often, it is the most straightforward approach. Often, but not always. In many cases, letting go of the separation can lead to cleaner code, less cruft, and more elegant solutions.

Take this example:

```<code>interface Fooable {
    function  run();
}

function foo(Fooable f) {
    f.run();
}

// ...

myF = new Fooable() { function run() { print "Hello, world!"; } }
foo(myF);
</code>```

vs.:

```<code>function foo(f) {
    f();
}

myF = function () { print "Hello, world!"; }
foo(myF);
</code>```

In any case, I consider it important to keep in mind that a separation of code and data is just one way to approach a problem, and that at the machine level, the distinction is questionable at best.

Body:
No, it's definitely not necessary. The Van Neumann architecture, which practically all computers today are based upon, pioneered the idea of a stored program, which is nothing more than code stored as data.

That's at the hardware level though; at the software level, paradigms differ as to how closely data and code are intermingled (or, conversely, how sharply they need to be divided).

On one end of the spectrum, there's imperative programming, especially the procedural flavors - think Pascal, C, FORTRAN, BASIC (actual BASIC, not VB.NET or anything like that). In these languages, data and code are conceptually separate; you can take pointers to function addresses and pass them around, but other than that, code is code, and data is data. If you want to treat data as code, you have to pull quite some tricks, e.g. injecting some assembler code to jump to an address that contains your data.

On the other end, you'll find functional programming, where functions are data (in a super-hardcore FP idiom, functions are even the only kind of data you can have); but also logic programming (think Prolog), where the entire program is mostly just a data structure describing facts about the problem domain. And of course there's the dynamic camp, which gives you techniques like monkey-patching, duck typing, introspection / reflection, etc., to have your code inspect and modify itself at run time. Lisp (any Lisp, really) is a particularly interesting candidate here, because it combines functional programming and dynamic features.

In between, there's object-oriented programming; this idiom mainly inherits the imperative mindset of separate data and code, but at its core, it departs from it a bit by bundling related behavior (code) and state (data) into units (objects). Fast-forward to the point where the idiom has fully unraveled, and you see "design patterns" emerge, many of which pretty much replicate code-as-data features found in other idioms.

All that doesn't really answer your question though: should code and data be separated? Well, the fact that even the most hardcore code-data-separators occasionally use code generators, lookup tables, and similar techniques that mix them up should tell you that being religious about such a separation is ridiculous. There are quite some advantages to treating them as separate realms, and often, it is the most straightforward approach. Often, but not always. In many cases, letting go of the separation can lead to cleaner code, less cruft, and more elegant solutions.

Take this example:

interface Fooable {
    function  run();
}

function foo(Fooable f) {
    f.run();
}

// ...

myF = new Fooable() { function run() { print "Hello, world!"; } }
foo(myF);

vs.:

function foo(f) {
    f();
}

myF = function () { print "Hello, world!"; }
foo(myF);

In any case, I consider it important to keep in mind that a separation of code and data is just one way to approach a problem, and that at the machine level, the distinction is questionable at best.


问:
How to design a website with search capabilities?
Suppose you want to create a web page with some search capabilities over a database. Search has to be restricted both on some categorization of data and open text given by the users. Functional and non-functional requirements pose this constraints:

Search has to be fast

Data representation paradigm (i.e. Relational, Object-Relational, Semistructured...) should support big modifications on every stage of software lifetime.

Database's paradigm should permit easy refactoring for existing client code

Having this into account

Would you recommend a relational database? How would you tackle the constraints in this scenario?

Would you recommend a XML database? How would you tackle the constraints in this scenario?

If you think above solutions to be not useful in the light of this problem... what could be a useful approach?

Please give some bibliography (or some websites) supporting your answers.

thanks!

答:
Whether or not to use SQL or Lucene for searching depends on how sophisticated you need for your searching to be.

If you don't need keyword based search, then stick with SQL.

If you are interested in a more intelligent ordering of the results, then use Lucene.

If you need keyword based search across a large amount of data, then use Lucene.

If you do decide to go with Lucene, then Embedding Lucene in Your Service gives advice to developers on how to start. You will still keep your data in SQL but you will also keep another copy of the searchable parts in Lucene. There is more here on SQL vs Lucene. It also addresses how to use Lucene in multi-threaded environments.


答: Erlang 2 does actually support inline tests. Any boolean expression in the code which is not used (e.g. assigned to a variable or passed) is automatically treated as a test and evaluated by the compiler; if the expression is false, the code doesn't compile.</p>

Title: Is there a reason that tests aren't written inline with the code that they test?

Body:
I've been reading a bit about Literate Programming recently, and it got me thinking... Well-written tests, especially BDD-style specs can do a better job at explaining what code does than prose does, and have the big advantage of verifying their own accuracy.

I've never seen tests written inline with the code that they test. Is this just because languages don't tend to make it simple to separate application and test code when written in the same source file (and nobody's made it easy), or is there a more principled reason that people separate test code from application code?


问:
Is Oberon really "a better Pascal"?
Reading Niklaus Wirth, one can notice that despite some popularity of Pascal, he is not glad that Oberon (as a "polished" successor of Pascal and Modula) didn't get much popularity. I never did anything in Oberon, but reading the page Oberon For Pascal Developers I really did not like many of the changes as a Delphi/pascal developer, for example

forcing the reserved words to be always uppercase

making the language case-sensitive

getting rid of enumeration types

What do you think about Oberon, is it really "a better Pascal" from your point of view?

答:
It is better, and worse, in various ways:

It is nice to have garbage collection, and facilities for modular and Object Oriented programming.
It is a relatively small language; easy to parse, and implement.

The lack of enumerations is a pain (indeed, in the extended Oberon dialect we use, we added them back).

Relative to more modern languages, its minimalism is a bit brutal, and treating strings as arrays of characters in any language is ghastly.

Of course, Pascal has evolved quite a bit too, e.g. see Component Pascal.

Title: Is Oberon really "a better Pascal"?


问:
C++ or C#: Which language is Microsoft going to use in development of future Windows versions?
I heard almost all parts of Windows are written in C and C++ with some assembly. Why did Microsoft skip C#? Is there any scope for C# in the development of future Windows versions?  </p>

答: At the time, there were no serious competitors to C/C++ in systems programming and now it's a legacy codebase that would probably cost a lot to port. C# also did not exist back then. For the record, there are attempts to turn .NET into an OS platform but these are not Microsoft projects.</p>


问:
The need for adding an interface to every class
My coworker and I are arguing very hard about this topic. He's thinking that every single class should have an Interface that the class implements (also Single-Implementations). He uses this design for documentation principles. In my mind that is obsolete because in Java you can comment on implementations, too.

I think that Interfaces are only needed there, where you have to publish some kind of open API, for yourself as the programmer, or for other people who later will connect their projects at this docking point.

Also I am in knowledge about Mocking Objects, whose library (e.g. EasyMock) also requires some Interface to create a Mock.

In my view, interfaces for every class are not necessary for every single class in JAVA. In other languages including some Frameworks it might be helpful.

Maybe you could show me some aspects that I don't see where Interfaces for every class might be helpful, or am I on the right way to deny this design principle?

答:
A unique interface for every class? By the great noodly appendages, that smells like an antipattern! Let's debunk a few things here…

Firstly, the only somewhat-valid reason for giving everything an interface is if you are very heavily using the built-in JRE proxy system (which can only construct proxies for interfaces). However, if you're doing that then you can also think in terms of using runtime class generation systems like the asm library to generate relevant proxies. (If you're getting deeply into that, look at how Spring and AspectJ work.)

Secondly, you should actually be thinking much more about grouping code into clearly defined APIs. Those APIs should be defined by interfaces (and relevant POJOs and exceptions as necessary) so that you think purely in terms of what that API actually promises and guarantees. Using the discipline of an OSGi bundle might well be a good idea here. That's also the level at which you really do your testing; that's the level at which you have black-box unit testing. Going within the implementation of the API — white-box testing — should be kept more to a minimum, because you're checking things in that case that should be unobservable to the outside world. (Creating lots of unobservable stuff is against the YAGNI principle.)

Of course, if you then keep the implementations thin so there is as little extra code other than the actual direct API implementation classes, that's probably a good thing under normal circumstances. Adding excessive amounts of abstraction does nothing except make you more confused!


答:
Oh dear, I don't know where to start...

You don't add an interface to a class. You implement an interface by coding a class.

Let's just say that I have come to appreciate coding against interfaces instead of classes for a multitude of reasons. High cohesion, low coupling design and testability being the most important.

Testability is greatly improved by using interfaces. Testability is also greatly improved by dependency inversion. And dependency inversion just happens to be so much simpler when using interfaces. (I am talking the principle here, not about frameworks, containers or libraries.)

Interfaces and dependency inversion allow you to create tailor made test stub classes for interfaces that the interface/class under test depends on, without having to worry about the parts of a "used" class that you do not rely on in the interface/class under test. (Please note that I do not use mocking. In Martin Fowler's words I am a classicist tester, using stub classes to isolate the class under test from external dependencies.)

So even when an interface will only ever have a single "real" implementation, it will soon have a couple of test stub implementations when it is used by at least one other class implementing another interface.

In fact, I nowadays code unit tests against interfaces and test an/every implementing class by registering a descendant class of the test class and setting it up to use the implementing class and any test stubs it may need. Thus ensuring that any and all implementations are tested against the same "contract".

Coding the tests against the interfaces also helps in focusing on the desired behavior and avoids being distracted by the implementation details of the class under test.

Title: The need for adding an interface to every class

Body:
My coworker and I are arguing very hard about this topic. He's thinking that every single class should have an Interface that the class implements (also Single-Implementations). He uses this design for documentation principles. In my mind that is obsolete because in Java you can comment on implementations, too.

I think that Interfaces are only needed there, where you have to publish some kind of open API, for yourself as the programmer, or for other people who later will connect their projects at this docking point.

Also I am in knowledge about Mocking Objects, whose library (e.g. EasyMock) also requires some Interface to create a Mock.

In my view, interfaces for every class are not necessary for every single class in JAVA. In other languages including some Frameworks it might be helpful.

Maybe you could show me some aspects that I don't see where Interfaces for every class might be helpful, or am I on the right way to deny this design principle?


答:
In direct answer to your question, I bet you'd find that most of Windows pre-dates C# in any case.

Who's to say what will happen in the future? I've seen so many revolutionary ideas from MS over the last 25 years that I've lost count.

But I read somewhere that VS2012 (the gui at least) was entirely rewritten in C# and WPF, so maybe you could take that as a sign of future direction? But I wouldn't put money on it.

Title: C++ or C#: Which language is Microsoft going to use in development of future Windows versions?

Body: I heard almost all parts of Windows are written in C and C++ with some assembly. Why did Microsoft skip C#? Is there any scope for C# in the development of future Windows versions?  </p>


答:
As you allude to in your question, the big win of exposing classes only via interfaces is when you come to unit test, in particular automated testing.

If you test a particular class, and construct a particular interface through which the class is accessed, then not only will the class itself implement the interface, but any "mocking" component will also implement that interface.

Now having said all this, I've thought about this a fair bit myself, and I'm not sure it is something I'd buy into either!


答:
C++ gives you access to the underlying hardware, something C# can't provide. So for the foreseeable future, Windows will be built in C++ (as parts as still built in assembly where raw performance and interrupt handling are necessary).

As a proof-of-concept, Microsoft Research built Singularity, a C#-based operating system. It uses a superset of C# called Spec# and some other extensions to minimize the need for C++ and other lower-level languages.


答:
I think the first question to ask shall be what are interfaces about. Interfaces are contracts you expose to whoever uses your module, including yourself (in another module). They mark boundaries where implementation details can be not so important and can be exchanged without breaking contract. While classes are concrete details, and they implement the contract interface promised.

So if you follow this road, defining an interface for every class is definitely over moduled. Of course interfaces can also be used as a kind of tag, like "Serializable". But this kind of use is replaced by annotations after java 5.


答:
This is in response to a large number of comments suggesting that inline tests are not done because it's difficult to impossible to remove the test code from release builds. This is untrue. Almost all compilers and assemblers support this already, with compiled languages, such as C, C++, C#, this is done with what are called compiler directives.

In the case of c# ( I believe c++ as well, the syntax might've slightly different depending on what compiler you are using) this is how you can do it.

```<code>#define DEBUG //  = true if c++ code
#define TEST /* can also be defined in the make file for c++ or project file for c# and applies to all associated .cs/.cpp files */

//somewhere in your code
#if DEBUG
// debug only code
#elif TEST
// test only code
#endif
</code>```

Because this uses compiler directives, the code will not exist in the executable files that are built if the flags are not set. This is also how you make "write once , compile twice" programs for multiple platforms/hardware.

Body:
This is in response to a large number of comments suggesting that inline tests are not done because it's difficult to impossible to remove the test code from release builds. This is untrue. Almost all compilers and assemblers support this already, with compiled languages, such as C, C++, C#, this is done with what are called compiler directives.

In the case of c# ( I believe c++ as well, the syntax might've slightly different depending on what compiler you are using) this is how you can do it.

#define DEBUG //  = true if c++ code
#define TEST /* can also be defined in the make file for c++ or project file for c# and applies to all associated .cs/.cpp files */

//somewhere in your code
#if DEBUG
// debug only code
#elif TEST
// test only code
#endif

Because this uses compiler directives, the code will not exist in the executable files that are built if the flags are not set. This is also how you make "write once , compile twice" programs for multiple platforms/hardware.


问:
What's the web framework to use on a front-end web application?
What do you consider a good client web framework to use on interface business application? jQuery? YUI!? Another? Some plugins useful?

The application will be use mostly internally replacing a desktop application for data entry and lots of queries/views.

答: To make a clientside replacement of an old "Winform style" driven backoffice applications Sencha (EXTJS) has been proven to be a really good option.</p>


答:
We use inline tests with our Perl code. There's a module, Test::Inline, that generates test files from the inline code.

I'm not particularly good at organizing my tests, and have found them easier and more likely to be maintained when inlined.

Responding to a couple of the concerns raised:

The inlined tests are written in POD sections, so they're not part of the actual code. They are ignored by the interpreter, so there's no code bloat.

We use Vim folding to hide the test sections. The only thing you see is a single line above each method being tested like +-- 33 lines: #test----. When you want to work with the test, you just expand it.

The Test::Inline module "compiles" the tests to normal TAP-compatible files, so they can co-exist with traditional tests.

For reference:

POD

TAP


问:
Does change the license under which Linux is released need the permission of all the copyright holders?
As far as I know Linus holds the copyright to Linux.

While looking around in the kernel sources, I see that almost every file has it's own copyright holders. For example the file module.c in the Linux kernel contains:

```<code>Copyright (C) 2002 Richard Henderson Copyright (C) 2001 Rusty Russell, 2002, 2010 Rusty
</code>```

And the COPYING file in the root directory contains:

```<code>   NOTE! This copyright does *not* cover user programs that use kernel
 services by normal system calls - this is merely considered normal use
 of the kernel, and does *not* fall under the heading of "derived work".
 Also note that the GPL below is copyrighted by the Free Software
 Foundation, but the instance of code that it refers to (the Linux
 kernel) is copyrighted by me and others who actually wrote it.

 Also note that the only valid version of the GPL as far as the kernel
 is concerned is _this_ particular version of the license (ie v2, not
 v2.2 or v3.x or whatever), unless explicitly otherwise stated.

            Linus Torvalds
</code>```

So if Linus would want to change the license under which Linux is released, wouldn't he need the permission of all the copyright holders, which are probably 1000's of people?

答:
Yes, he would need permission from every person who has contributed code to the project. This is because those people have only given permission to redistribute their code under the GPL.

Some other projects circumvent this by requiring that contributors assign their rights to the project.


答:
On the floor of the truck I think you should make a more abstract question, for example, what should I expose in my API?.

After defining who really want to conquer the path gets easier.

About interfaces and classes, there is no rule that say 100% effective. Will depend somewhat the needs of your project.


答: Not working in product development but clearly microsoft windows for good years will still be developed in C and C + +. This is because the languages allow / provide access to hardware to a safe level instruction. C # runs on MSIL and has no goal of being language OS.</p>


问:
is it wrong for my parent object to make assumption about child objects?
I have a simple domain with about 6 objects in the model.  For the most part they have a clear child/parent relationship with parent having multuple children.  I'm going to have all of them be immutable.  However, at some point I'll need to both fetch a set of all objects of a given type, and be able to fetch a specific object of a certain type by it's label.

I was going to have a model with some generic maps, and an abstract class for objects in the model.  Adding to the model sticks the object in my map, and asks for the parent objects and sticks those in the map etc.  Likewise a delete can delete all classes that called themselves children.  This way I can query for specific classes in a generic method without writing logic to hunt down each class.

Once I thought of this my next thought was rather I can use a similar framework to save CPU by looking up children in the same manner.  If I already have to store "these objects claimed x was a parent" to do the delete I can then say "give me children of X".  However, this assumes that X knows something about the other objects (what classes are effectively children of it).  I can put in type safty via reflection mostly; but is it brittle for one object to presume that certain other class is going to claim it as a parent and persumably be in the model as such?

TO clarify,  lets say I have a node and edge class.  My edge would report a node as it's parent.  My Node can then say "give me all Objects that claimed me as parent and are edges" and do logic on them; even though it never did anything to ensure that there were edges out there using it as a node.  Is this wrong?

Note, this is a small system.  I know that there are great abstraction patterns for huge systems, that I mostly don't think are worth the implementation cost or less explicit code for such a simple system.

答:
If its not a framework (with new children being added by users) and you put a smaller version of question in the parent as code comments then its fine.

Even if it was a framework it would be okay as long you have warned users, though would be more useful if there was some validation/ checking -> explicit and/or via language features.


问:
OOP principles and method names
```<code>class Boxer:

    def punch(self, punching_bag, strength):
        punching_bag.punch(strength)

class PunchingBag:

    def punch(self, strength):
        print "Punching bag punched with strength", strength

boxer = Boxer()
punching_bag = PunchingBag()

boxer.punch(punching_bag, 2)
</code>```

No doubts that punch is a good method name in case of a boxer.
But is name punch also good for the method of punching bag?
In both cases I mean punch as a command (i.e. do punch).

答:
I think it is a conceptual issue (how we think about the world). It's alright to say:

Look, the door is closing. door.close()

Wow, the paper is folding on its own. paper.fold()

What the hell?! That file on the desk has just closed, nobody being around. file.close()

It is weird to say:

That punching bag in the gym has just punched itself. bag.punch()

It would need to have something to punch itself with in the first place (e.g. arms). You would probably say:

The punching bag has started moving on its own like somebody would have punched it. punching_bag.move()

It's alright for programmatic objects to do things that normally others do to/with them (in the "real world"). But I guess it should always make at least some sense that the thing is doing it to/with itself. You should be able to imagine it easily without getting obscure (as in case of the punching_bag).

Title: OOP principles and method names


问:
github tools - is there a way not to copyright your app and stay its author
I am wondering...

Recently I have observed github; I saw many Java projects' codes which don't have copyright at their headers... I mean, as I may guess, in this case the only thing which can prove the code author is - it is author's github account;
So my question is... is it safe to protect open source code with github account only or there is a more optimal way to do so? Please share your experience;

Thanks

答:
In principle, you don't need to put in a copyright statement to own the copyright on something you have written. There are a few exceptions, such as stuff you write as part of your employment or when you explicitly transfer your copyright, but that is the general principle that copyright law is based upon.

The point of putting in the copyright statement is mostly to make it abundantly clear to the reader who own the copyright.

Another thing is that, unless there is a licence granting others those rights, the copyright holder is the only one that is permitted to copy, distribute or modify the work. And most open-source licences require that you explicitly state who owns the copyright.

So, in the end, if you happen upon something that does not have a clear copyright statement and appropriate licence, it is best to assume you can't use it. But I would not rely on others to presume the same thing.
The best way to protect your code is not to put it out in a publicly accessible place. The second best is to clearly state the copyright and licence.


问:
Is there any environments like Visual Studio for embedded systems?
I thought it would be very useful if there is an embedded application development tool like Visual Studio for web development. I mean when we develop web applications we have a toolbox and we drag and drop components and generally use events. In embedded systems events are interrupts. So why don't we have a toolbox which has electronic circuit components and we drag and drop them, also by clicking on them writing the behind code. Is there any extension like that for visual studio? or Is there any other environment like that?</p>

答: For Atmel AVR embedded microcontroller there is the Atmel Studio which makes writing c/c++/assembly and their debugging quite comfortable.</p>


问:
What is the meaning of "inversion" in Dependency Inversion design principle?
I'm reading about design patterns. I know what this principle does.

High-level and low-level classes depend on abstractions. But why we say this is inversion?

答: The problem is that so-called "Dependency Inversion Principle" is poorly named and defined. While the definition was clarified by its author afterwards, the name is a total misnomer. There are no dependencies which are inverted when this principle is applied.</p>

OwnerDisplayName: Khajavi


问:
Using only UI testing. Is that Ok?
I am a sole developer working with an offshore employer. I do realize the importance of unit testing (although haven't practiced before) but currently, the code hasn't ever been tested. The problem with the code is that it isn't what I call "been moduled well", some parts are really messy, extensive use of globals and the code doesn't really show loose coupling. If I am not wrong, the code might require heavy refactoring before being able to be unit tested. Also, it seems the employer, isn't quite interested in testing. He rather suggests to spend this time in building features.

So what I suggested to him is UI testing. Because UI testing is something we do every time, testing features, clicking, checking if something is  not broke, it made sense to both of us to use it to automate the process of checking features and save us time.

Since I have never done UI testing before, I don't know what possible disadvantages might be associated with using just UI testing alone or will it be much beneficial at all?

答:
The biggest problem IMHO of UI Testing exclusively is that the permutations of things to be tested, even in a relatively simple app, are too great and the level too high to catch many potential defects. Code coverage is not going to be very high.

You will probably find and locate some major items that will inhibit the users in a few scenarios (best case, worst case run through), validation issues and what not. However, you won't find the things that say a Breaker would use to disadvantage your application and get into your data, for example.

Unit test, TDD, Functional Testing and other testing methodologies are designed around testing the code internally and at a more granular level. This makes the testing more complete and likely to catch the more insidious bugs that simple UI testing alone will miss. A combination of the above is your best bet. Sadly it doesn't sound like you will have to much choice unless you just do it. It sounds like there are severe time constraints as it is, but note that with only UI testing your time may run over regardless.

Title: Using only UI testing. Is that Ok?


问:
Worst coding standard you've ever had to follow?
Have you ever had to work to coding standards that:

Greatly decreased your productivity?

Were originally included for good reasons but were kept long after the original concern became irrelevant?

Were in a list so long that it was impossible to remember them all?

Made you think the author was just trying to leave their mark rather than encouraging good coding practice?

You had no idea why they were included?

If so, what is your least favorite rule and why?

Some examples here

答:
The worst was a project (C++) where classes were prefixed with module abbreviations.

For example, if something was in the MessagePassing module, and part of the Response mechanism, it might be called MESPAS_RESSomeobject.

Working on that code made me want to gouge out my eyes.

Not the worst, but my current job requires a c_ prefixes on classes and e_ prefixes for enums.  Nothing for structs.  but _t postfix on typedefs.  It's pretty ugly too.

Oh, and function header comments in BOTH .h and .cpp (declaration and definition) which of course almost never match.


问:
What are the most popular IDEs per language?
This has nothing to do with having a favourite editor or anything like that. I was just wondering, per language, what are the most popular Integrated Development Environments? Maybe a top 2-3 if there is some contention. (Perceived popularity is enough)

Thus Far:

C# - Visual Studio, SharpDevelop

Java - Eclipse, NetBeans, IDEA

Objective-C - Xcode

Delphi - RAD Studio

Object Pascal - Delphi, Lazarus

C, C++ - Visual Studio, Vim

PL/SQL - RapidSQL, Oracle SQLDeveloper

PHP - Eclipse, NetBeans, Nusphere PHPed

Actionscript (AS2, AS3) - FlashDevelop

Flex - Flash Builder 4

Python - Eclipse, IDLE

Perl - Padre

Common Lisp - Lispworks, Emacs

Ruby - TextMate

Haskell - Vim

Fortran - Vim

Visual Basic - Visual Studio

答:
JetBrains has IDE's for several languages that have a similar look & feel:

IntelliJ IDEA for Java

RubyMine for Ruby and Ruby on Rails

PHPStorm for PHP, HTML and JavaScript

PyCharm for Python and Django

(I have the last three.)


问:
Why are there non-decidable languages? Can anyone explain me my book's solution?
Well in my book it is says that "there are non-decidable languages" And the proof is:

Every algorithm is a word. Then there are only countable algorithms. But there are uncountable languages and therefore more than algorithms

Why is it said that every algorithm is a word? A word is a concatenation of symbols, elements of an alphabet, then what's the relation between a word and an algorithm? Can anyone explain me that?

答:
Here's a solid example.

Some languages have metaprogramming/preprocessing systems that contain code that needs to be evaluated at compile time.  This can be simple substitution, like C's macros, or more complex.

There are some cases in which the compile-time code evaluation system is complex enough that it can be shown to be Turing-complete.  C++'s Template system is the most infamous example of this, though Perl and Lisp have also been shown to have this property.

One famous property of Turing-complete languages is the Halting Problem: it is possible to construct a valid program in any Turing-complete language which will end up in an infinite loop and not terminate.  It is also possible, in any Turing-complete language, to construct a valid program for which it is not possible to determine whether or not it will end up in an infinite loop.

Since preprocessing code has to be evaluated to completion by the compiler, this means that in a programming language with Turing-complete compiler-time preprocessing, it is possible to construct a syntactically-correct program for which it is not possible for the compiler to decide what it means.  Thus, C++, Perl and Lisp are non-decidable languages in the general case.  (Which, of course, does not mean that it's not possible to write programs in them. Just that not every syntactically correct program written in them can be understood by a parser.)


问:
Javascript Architectural Model
Are there any obvious flaws to this OO architectural model which I intend to implement using javascript? It is similar to the MVP model but instead the role of the model is broken down into three modules:

the cache (stores data instead of rerequesting from server)

the model (manages requests for raw data, retrieving it from the cache if available or the server)

the modifier (handles requests which require data which makes changes to the data on the server)

For a diagram showing how data flows through this model:

view

sets up & manages the UI possibly requiring the requesting of data from the presenter

sets up controls to alter what is displayed, possibly requiring the requesting of data from the presenter

cache

contains a record of some fetched data in data objects

has a .store() method for storing data in the cache

has a .retrieve() method for retrieving data from the cache

access for storage and retrieval is available to the model and the modifier (acting as a faster intermediate location for the sharing of information than the server)

presenter

handles requests for formatted data from view

requests data from Model (passing a callback for completion) formats data for presentation and calls view callbacks

model

handles requests for data from presenter

requests data from cache (cache.retrieve())

if data not in cache, requests it from server and then stores it in cache (cache.store())

data passed back to presenter via callbacks

modifier

handles requests from view for modifications to data

specify post, put and delete request types

only support specific types of request which may be handled separately (eg settings)

stores new data in cache (cache.store())

pushes data to the server

calls callback about the success of data storage

This is quite big project and there will be a number of others working on it so it would be good to get it right from the off.

edit 1

The cache.store() and cache.retrieve() methods both only receive the information required to refer to the data in the cache, but do not specify how it is stored. The cache methods use this information to respond with or store the correct data, but the internal structure in which the data is stored is kept secret.

答:
There are a few flaws in the design, in my opinion.

Both the model and the modifier need to know how the data is structured internally. This will likely result in a duplication of code and/or responsibilities.

<update>

For example, you have a Customer object who can hold an Account. Now the model needs to know how Customer and Account are related so the correct information can be retrieved from the database. But the modifier needs to have the same knowledge to be able to perform updates of the data. If there is now a change to allow multiple Accounts per Customer, there are two places where this change has to be applied. This is the kind of duplication I refer to.

</update>

I would have made the interactions with the cache more transparent.

All in all, I would make these changes to the architecture:

The modifier makes the modifications to the model instead of the cache and the database. This gives the modifier the same responsibilities as the Controller in the MVC pattern. You might consider renaming the modifier accordingly.

Replace the cache with a cachedDatabase, which handles the database connection and caches the results for fast access the second time the data is requested. For the model it should be transparent where the data came from (cache or database).

Title: Javascript Architectural Model


问:
Plugin Architecture: How to Handle Databases and Logging?
I am in the process of designing an architecture for a plugin based application and I have some questions about how to handle database access and logging. The goal of my application is to allow a device my company is manufacturing to send messages over any number of third-party protocols and to any number of third party devices. Because of the nature of my application, I need to log every message that is sent via my system in reasonable detail.

Here's what I am thinking on the Database side: There will be a global message table which stores all of the implementation agnostic data we have, and then there will be a table (or set of tables) for each messaging plugin as defined by the plugin writer which references the Global Message table via a foreign key.

It is handling these other tables that I am having a hard time figuring out how to design safely. On the one hand, I don't particularly want to give the plugins full access to the database (I want them to have the fewest possible privileges), on the other hand I want the plugin developers to have full reign to log any data they need to tables that they define similarly to how plugins work in Wordpress. Additionally, I don't want logging to the Database to be optional at all: Good logging is crucial to my application.

Things I have considered:

Designing a logging infrastructure which allows a plugin to define (maybe in an XML file) the tables it needs in the DB and a mapping between those tables and objects that they will return, and using those mappings and table definitions to write to the DB the results from method calls.

Making a naming convention for Stored Procedures in the DB that each plugin must define when defining their tables and automatically calling those stored procedures after sending a message.

Allowing each plugin to implement a logging method which returns a String holding the proper SQL query.

Each of the above solutions makes me a little uncomfortable, but I'm not sure what other approaches might exist. Any Suggestions?

Implementation Details:
I am writing my application in Java, and I am using a hand-rolled plugin solution, so I have a pretty decent amount of flexibility. Since none of the actual code has been written (other than some proof-of concept code which is really just for reference), I can make fairly major changes to my plan without great cost.

答:
What you are describing is a situation in which you are designing APIs - between your application and the plug-ins. At this level you should focus on designing the interfaces and the data that needs to be exchanged without worrying about any specific persistence strategy. Once you nail that part, then part of the implementation in your application can handle the data any way it wants.

Since you are using Java, take a look at any high-level API you already use for the design cues - like Spring Data, Collections (e.g. Map, List) etc. They all hide the details behind Interfaces, Abstract classes and Concrete classes that implement the desired functionality.

At a very high level, I can think of the following (very simplistic approach, not knowing the exact details):

An Interface that allows a plugin to register itself to your
application. Say you call it PluginRegistry. Then the method in it
should be relevant for any plugin to register itself to the
application and establish the communication links (like message
listeners, callbacks etc). Your interface can dictate what method(s)
the plugin needs to implement.

Say another interface defines the message exchange. It could be a high-level Interface coupled with an Abstract class (for default implementation) and one or more Concrete classes for specific implementations. You can leave the implementation of concrete classes to the plugins.

Your abstract classes can hide the details of logging in the database. Since you have the flexibility to design how the message should look like (plug-in will inherit from and/or implement the necessary interface), the abstract class with the default implementation can write the necessary data to the database (I'd prefer a log file) without the plugin knowing too much about it. This way you do not need to expose this functionality to plugins and can later change your implementations as needed.

The reason I mentioned that a log file is preferred over a relational-db is that you will have flexibility in logging any way you want in a file. A NoSQL db would also be a good choice here as it wont force you into hard relationships between your data early on. Then write some scripts (e.g. in Python, Perl etc) to analyze the log files and gather the necessary data and put in the relational-db as needed for reporting. But your main raw data store will be log files. As your application matures, you will get a good idea of the data's structure, important elements and automate the analysis scripts. As you log more type of data, you will need to update the scripts as needed, but hey you wont be changing the db tables where and breaking your application.


问:
Can/should the Single Responsibility Principle be applied to new code?
The principle is defined as modules having one reason to change. My question is, surely these reasons to change are not known until the code actually starts to change?? Pretty much every piece of code has numerous reasons why it could possibly change but surely attempting to anticipate all of these and design your code with this in mind would end up with very poor code. Isn't it a better idea to only really start to apply SRP when requests to change the code start coming in? More specifically, when a piece of code has changed more than once for more than one reason, thus proving it has more than one reason to change. It sounds very anti-Agile to attempt to guess reasons for change.

An example would be a piece of code which prints a document. A request comes in to change it to print to PDF and then a second request is made to change it to apply some different formatting to the document. At this point you have proof of more than a single reason to change (and violation of SRP) and should make the appropriate refactoring.

答:
Isn't it a better idea to only really start to apply SRP when requests to change the code start coming in?

Ideally, you'll already have a good idea what the responsibilities of the various parts of the code are. Split into responsibilities according to your first instincts, possibly taking into account what the libraries that you are using want to do (delegating a task, a responsibility, to a library is usually a great thing to do, provided that library can actually do the task). Then, refine your understanding of the responsibilities according to the changing requirements. The better you understand the system initially, the less you need to fundamentally change responsibility assignments (though sometimes you discover that a responsibility is best split into sub-responsibilities).

Not that you should spend a long time worrying about it. A key feature of code is that it can be changed later, you don't have to get it completely right the first time. Just try to get better over time at learning what sort of shape responsibilities have so that you can make fewer mistakes in the future.

An example would be a piece of code which prints a document. A request comes in to change it to print to PDF and then a second request is made to change it to apply some different formatting to the document. At this point you have proof of more than a single reason to change (and violation of SRP) and should make the appropriate refactoring.

This is strictly an indication that the overall responsibility — “printing” the code — has sub-responsibilities, and should be split into pieces. That's not a violation of SRP per se but rather an indication that partitioning (perhaps into “formatting” and “rendering” sub-tasks) is probably required. Can you describe those responsibilities clearly so that you can understand what is going on within the sub-tasks without looking at their implementation? If you can, they are likely to be reasonable splits.

It might also be clearer if we look at a simple real example. Let us consider the sort() utility method in java.util.Arrays. What does it do? It sorts an array, and that's all it does. It doesn't print the elements out, it doesn't find the most morally-fit member, it doesn't whistle Dixie. It just sorts an array. You don't have to know how either. Sorting is that method's only responsibility. (In fact, there are many sorting methods in Java for somewhat ugly technical reasons to do with primitive types; you don't have to pay any attention to that though, since they all have equivalent responsibilities.)

Make your methods, your classes, your modules, make them have such a clearly designated rôle in life. It keeps the amount that you have to understand at once down, and that in turn is what allows you to handle designing and maintaining a large system.


问:
Is a grid or p2p architecture a subset of a broker architecture?
Is a grid or p2p architecture a subset of a broker architecture?

what are the key features that make these similar or distinct?

答:
In a peer-to-peer architecture, all peers are supposed to be on the same level. There is no distinction between clients, servers, or other special roles.

Broker as integration function is a more central role in hub-and-spoke architectures. The broker typically maps and routes messages. The broker may be part of the central middleware or it can be attached as a separate component to a messaging system.

A grid architecture is a distributed set of nodes or systems which collaborate to serve a common goal. Typically, there is some central system which distributes sub-tasks and collects the results. The nodes may be computers or they may be parts of microchips. Look for "Systolic Arrays".


问:
Divide and Conquer algorithms – Why not split in more parts than two?
In divide and conquer algorithms such as quicksort and mergesort, the input is usually (at least in introductory texts) split in two, and the two smaller data sets are then dealt with recursively. It does make sense to me that this makes it faster to solve a problem if the two halves takes less than half the work of dealing with the whole data set. But why not split the data set in three parts? Four? n?

I guess the work of splitting the data in many, many sub sets makes it not worth it, but I am lacking the intuition to see that one should stop at two sub sets.

I have also seen many references to 3-way quicksort. When is this faster? What is used in practice?

答:
Asymptotically speaking, it doesn't matter. For example, binary search makes approximately log2 n comparisons, and ternary search makes approximately log3 n comparisons. If you know your logarithms, you know that loga x = logb x/logb a, so binary search only makes about 1/log3 2 ≈ 1.5 times as many comparisons as ternary search. This is also the reason nobody ever specifies the base of the logarithm in big Oh notation: It's always a constant factor away from the logarithm in a given base, no matter what the base actual is. So splitting the problem into more subsets doesn't improve time complexity and practically isn't enough to outweigh the more complex logic. In fact, that complexity may affect practical performance negatively, increasing cache pressure or making micro-optimizations less infeasible.

On the other hand, some tree-ish data structure do use a high branching factor (much bigger than 3, often 32 or more), though usually for other reasons. It improves utilization of the memory hierarchy: data structures stored in RAM make better use of the cache, data structures stored on disk require fewer reads HDD->RAM.


答:
It does make sense to me that this makes it faster to solve a problem if the two halves takes less than half the work of dealing with the whole data set.

That is not the essence of divide-and-conquer algorithms. Usually the point is that the algorithms cannot "deal with the whole data set" at all. Instead, it is divided into pieces that are trivial to solve (like sorting two numbers), then those are solved trivially and the results recombined in a way that yields a solution for the full data set.

But why not split the data set in three parts? Four? n?

Mainly because splitting it into more than two parts and recombining more than two results
results in a more complex implementation but doesn't change the fundamental (Big O) characteristic of the algorithm - the difference is a constant factor, and may result in a slowdown if the division and recombination of more than 2 subsets creates additional overhead.

For example, if you do a 3-way merge sort, then in the recombination phase you now have to find the biggest of 3 elements for every element, which requires 2 comparisons instead of 1, so you'll do twice as many comparisons overall. In exchange, you reduce the recursion depth by a factor of ln(2)/ln(3) == 0.63, so you have 37% fewer swaps, but 2*0.63 == 26% more comparisons (and memory accesses). Whether that is good or bad depends on which is more expensive in your hardware.

I have also seen many references to 3-way quicksort. When is this faster?

Apparently a dual pivot variant of quicksort can be proven to require the same number of comparisons but on average 20% fewer swaps, so it's a net gain.

What is used in practice?

These days hardly anyone programs their own sorting algorithms anymore; they use one provided by a library. For example, the Java 7 API actually uses the dual-pivot quicksort.

People who actually do program their own sorting algorithm for some reason will tend to stick to the simple 2-way variant because less potential for errors beats 20% better performance most of the time. Remember: by far the most important performance improvement is when the code goes from "not working" to "working".

Title: Divide and Conquer algorithms – Why not split in more parts than two?

Body:
In divide and conquer algorithms such as quicksort and mergesort, the input is usually (at least in introductory texts) split in two, and the two smaller data sets are then dealt with recursively. It does make sense to me that this makes it faster to solve a problem if the two halves takes less than half the work of dealing with the whole data set. But why not split the data set in three parts? Four? n?

I guess the work of splitting the data in many, many sub sets makes it not worth it, but I am lacking the intuition to see that one should stop at two sub sets.

I have also seen many references to 3-way quicksort. When is this faster? What is used in practice?


答:
There are search/sort algorithms that subdivide not by two, but by N.

A simple example is search by hash coding, which takes O(1) time.

If the hash function is order-preserving, it can be used to make an O(N) sort algorithm.
(You can think of any sort algorithm as just doing N searches for where a number should go in the result.)

The fundamental issue is, when a program examines some data and then enters some following states, how many following states are there, and how close to equal are their probabilities?

When a computer does a comparison of two numbers, say, and then either jumps or not, if both paths are equally likely, the program counter "knows" one more bit of information on each path, so on average it has "learned" one bit.
If a problem requires that M bits be learned, then using binary decisions it can't get the answer in fewer than M decisions.
So, for example, looking up a number in a sorted table of size 1024 can't be done in fewer that 10 binary decisions, if only because any fewer would not have enough outcomes, but it can certainly be done in more than that.

When a computer takes one number and transforms it into an index into an array, it "learns" up to log base 2 of the number of elements in the array, and it does it in constant time. For example, if there is a jump table of 1024 entries, all more or less equally likely, then jumping through that table "learns" 10 bits. That's the fundamental trick behind hash coding. A sorting example of this is how you can sort a deck of cards. Have 52 bins, one for each card. Fling each card into its bin, and then scoop them all up. No subdividing required.


问:
Are square brackets and curly braces in Clojure still S-expressions?
I am trying to learn Lisp and looking at all the Lisps out there and their differences.

I see that in some implementations of Scheme, you can use square brackets interchangeably with round brackets for readability, so because they are treated the same, I assume they are still just S-expressions like everything else.

However, in Clojure I see that square brackets and curly braces are used to represent different data types like vectors and so on. Are these also still valid S-expressions, or must they be considered atoms? Doesn't this "break" the whole concept of S-expressions, thereby making Clojure an "impure" Lisp?

答:
S-expressions are a textual representation for data. Numbers, symbols, cons cells, lists, strings, ... Common Lisp also has textual representations for arrays, vectors, more number types, characters, ... Common Lisp also provides a user-extensible reader, so that the user can add more textual representations for data types. Sometimes this mechanism is also used to alter the syntax of the Lisp programming language (for example to support infix expressions or statements from other programming languages).

Thus, if a Lisp dialect offers textual representations for additional data-types, this fits well to the idea of s-expressions.


问:
Spoiled by Python convenience- and productivity-wise, spoiled by C++ speed-wise. Now unhappy with both
I'm currenetly struggling with choosing how to proceed as a programmer. I mainly programmed games and would like to continue. And for about 5 years or so I just used C++ and OpenGL, so I spent a lot of time on infrastructure, strange bugs, and mostly getting basic things to work.

A friend of mine then recommended python and after initially being aversed by it being not as explicit and formal as I was used to I was shocked by how much more productive I could be and how much progress I could actually make in a very small amount of time.

So currently I'm working on a multiplayer-shooter and repeatedly I find myself struggling with python being not as fast I might want it to be. I know that that I have to approach writing efficient code in python very differently now, but even with a little help from friends that are more experienced with python there is just too much going on sometimes (and extrapolating this, I know that I will end up stuck).

There are a lot of things I really like about my "home-language" C++, but after knowing how many hours I could be wasting I don't really want to go back.

What language can you recommend which offers high-productivy, is memory-safe (I really hated this) and as high-performance as I can get, but is still mature enough to be used for kind of serious projects (games-related) and maybe even mature enough to have people already having spent some time on OpenGL-Bindings or various libraries for Sound and similar (alternatively easy access to shared libraries written in C). Easy cross-plattform is a big plus! So no .NET please. Is this even possible?

答:
Delphi.

High productivity.  It's in the Pascal family, which was designed to be easy to read and write, with some very well-thought-out standard libraries available.

Memory safe.  Not completely (it's hard to get that without managed code) but far better than C++, with a stricter type system, bounds checking at the language level and a debugging memory manager available on SourceForge that makes tracking down whatever gets past the first two safeguards simple.

As high-performance as I can get.  It compiles to native code, and has been used to build games before, including some rather high-profile titles like Age of Wonders and the Space Rangers series.

Still mature enough to be used for kind of serious projects (games-related).  Delphi was first released in 1995 (the same year as Java) as an upgrade from the already-mature Turbo Pascal product, and has had a strong community behind it ever since.

Mature enough to have people already having spent some time on OpenGL-Bindings.  A basic OpenGL header implementation comes with the standard library.  A more extensive GL header unit can be found as part of Asphyre, an open-source multimedia library for Delphi tailored towards game development.

Alternatively easy access to shared libraries written in C.  Delphi actually makes it easier to talk to C-based DLLs than C does, as it has no need for .lib files; all you need is a translation of the headers.  Also, Delphi header translations for various multimedia libraries exist, including the popular game-development framework SDL, which I have contributed to personally.

Easy cross-plattform is a big plus! Delphi is still primarily a Windows development platform, but they recently released compilers for OSX and iOS, and they're currently working on an Android compiler as well.

Is this even possible? Yes.  It's not perfect, but it's possible, and it works pretty darn well.


问:
What are the 'must know' Emacs commands?
I'm a fairly new convert to Emacs and I really love it as an editor, primarily because I keep finding new and super-useful commands. Are there any other programmer 'must known' commands missing from my list?</p>

```<code>M-x replace-string     - Find and replace a given string.
M-x goto-line          - Goto a specific line
M-x column-number-mode - Show the current column number in text bar
</code>```

答:
```<code>M-:
</code>```

this allows you to evaluate arbitrary elisp in the minibuffer

```<code>C-x C-q
</code>```

readonly viewing of a file

```<code>C-c C-c
</code>```

comment region

among others!

Body:
M-:

this allows you to evaluate arbitrary elisp in the minibuffer

C-x C-q

readonly viewing of a file

C-c C-c

comment region

among others!


答:
There are lots of options to be considered once you find that scripting languages are not just toys.

Personally, I'd suggest:

Lua: very fast for a bytecode interpreter, much faster with LuaJIT (seriously, it challenges good C compilers), easy to mix with C code (either embedded in an application, or extended with C modules), minimalistic core/libraries, very portable (pure ANSI C), widely used in game industry.

Go: static typed, compiled, no bytecode.  Garbage collection, type inference, modern threading.  Designed by C++ programmers that wanted something more productive but loved by Python programmers that don't hate static typing.

Title: Spoiled by Python convenience- and productivity-wise, spoiled by C++ speed-wise. Now unhappy with both

Body:
I'm currenetly struggling with choosing how to proceed as a programmer. I mainly programmed games and would like to continue. And for about 5 years or so I just used C++ and OpenGL, so I spent a lot of time on infrastructure, strange bugs, and mostly getting basic things to work.

A friend of mine then recommended python and after initially being aversed by it being not as explicit and formal as I was used to I was shocked by how much more productive I could be and how much progress I could actually make in a very small amount of time.

So currently I'm working on a multiplayer-shooter and repeatedly I find myself struggling with python being not as fast I might want it to be. I know that that I have to approach writing efficient code in python very differently now, but even with a little help from friends that are more experienced with python there is just too much going on sometimes (and extrapolating this, I know that I will end up stuck).

There are a lot of things I really like about my "home-language" C++, but after knowing how many hours I could be wasting I don't really want to go back.

What language can you recommend which offers high-productivy, is memory-safe (I really hated this) and as high-performance as I can get, but is still mature enough to be used for kind of serious projects (games-related) and maybe even mature enough to have people already having spent some time on OpenGL-Bindings or various libraries for Sound and similar (alternatively easy access to shared libraries written in C). Easy cross-plattform is a big plus! So no .NET please. Is this even possible?


答:
You should be happy with both. Use python where you want to be highly productive (your words) and use C++ where you need high performance. If you need even higher performance, use more specific language (e.g. fortran), wrap it and call it from your python code. Need even speedier code, hand code some assembly. Maybe you don't even need to do that, maybe using language that supports concurrency pays more dividend.

It's about using the right tool for the job. You don't need to optimise everything, just where it really counts.

If you really want to only know one language, probably ruby is the answer. Just because you get 'rake' for 'make' replacement. You can have client, server and deployment scripts all in one language. Otherwise use a few languages.


答:
At my work, we started using UI tests in addition to our unit and integration tests. Of the three types, the UI tests take the longest to write and to run and catch the fewest amount of bugs. They are also extremely brittle, failing sporadically for no good reason.

Because they take so long to run and do not pass consistently, we found that it was not worth the effort to maintain them. Of course, this could be due to writing the UI tests poorly, or using a bad framework (we used visual studio Coded UI tests).

We have had much better success with unit and integration tests. In your situation, given that the code is not very modular, unit testing will be difficult as you mentioned. I think you would have much better success with integration and acceptance-level tests (test entire features at a level just below the UI).

Title: Using only UI testing. Is that Ok?

Body:
I am a sole developer working with an offshore employer. I do realize the importance of unit testing (although haven't practiced before) but currently, the code hasn't ever been tested. The problem with the code is that it isn't what I call "been moduled well", some parts are really messy, extensive use of globals and the code doesn't really show loose coupling. If I am not wrong, the code might require heavy refactoring before being able to be unit tested. Also, it seems the employer, isn't quite interested in testing. He rather suggests to spend this time in building features.

So what I suggested to him is UI testing. Because UI testing is something we do every time, testing features, clicking, checking if something is  not broke, it made sense to both of us to use it to automate the process of checking features and save us time.

Since I have never done UI testing before, I don't know what possible disadvantages might be associated with using just UI testing alone or will it be much beneficial at all?


答:
If you're working as part of a team; ask your team members. Nothing is worse than some rogue programmer deciding to write a piece of code in some language that nobody else knows. It's best for the entire team to agree on a small number of "right tool for the job" languages that everyone (or almost everyone) has experience with, and stick to them. Note: Having experience with a language is very different to merely knowing a language.

If it's just you (no team, and nobody maintaining the code for however many years after you're done); then I'd recommend using whatever you're most productive with (e.g. Python) then, after pieces work and after you've found the bottlenecks, rewrite the "not fast enough" pieces in a faster language (e.g. C++). Finally, after everything is done and everything is fast enough, think about minimising your software's dependencies (e.g. consider replacing any/all code that's still in Python so that your poor end users who are unlikely to have Python installed won't end up with unnecessary hassles).


答:
I would say stick with Python and use some of the advanced features it provides.  Specifically I am talking about the extensions.  If you look at how things work today there are some very fast things in Python and those things are all done in C/C++ as extensions.

You can create C/C++ extensions to speed up the slow parts of Python.  Additionally a good intermediary position would be to use Cython to get some decent speedups.

Cython
This provides a way to tweak Python code to make it run faster.  The basic idea here is to realize that one of the very slowest things in Python is typing as well as one of the most powerful.  Cython gives you the ability to specify the typing of variables in order to speed things up.  Here is a great example: Cython Example

Extensions
The next step if Cython doesn't speed things up enough is to create a straight C/C++ extension.  What this means is that you can create a custom function that will greatly speed things up.  Look for the most CPU intensive parts and implement them in C++ while keeping the other abilities of Python.

My Personal Experience
I created this IO tool to test asynchronous IO in Python that was very powerful.  It could do all sorts of things including data integrity checks.  This meant that I could write data out and then later verify it.  My problem was that Python allowed me to very quickly create this program but because of Python the data integrity section was very slow.  It was so slow that it would consume all of the CPU and bring the system to a crawl.  In order to solve this and make the program usable I thought about recreating the program in C++.  My problem was that every time I looked at what I would need to do the problem looked staggering and not worth the effort.  After some time I looked around and found Cython.  It was a good  intermediary solution.  I implemented the slow Python code in Cython and found that I got some large performance improvements.  After a while I still ran into the problem where things were slow so I created a C extension.  This extension then allowed me to realize my dream.

PyPy
I have heard, although never tried, that PyPy is a much faster implementation of Python which might give you the performance you desire while still using Python.


问:
Web Programming Cross Browser Frustrations Normal?
So I'm a relatively junior programmer, been doing it for a couple years now and have been recently working on a redo of the company's website, and have ran into some frustrations and was just wondering if that's the way it goes or if I'm missing something. I am by no means a designer, I focus on the code and don't pay much attention to how pretty it looks, that's someone else's job as far as I'm concerned.

That being said, I have been working on getting some things to work and the cross Browser problems have made me hate Web Development. I try to get html5 videos and no go, put in a flash backup and only works on half. Throw a Google api in and it looks like crap in ie and opera. The actual code behind doesn't work in ie7. It just seems like one thing after another. As I said I'm new to Web Development. Is this just the way it is? Throw some basic code in, then take all day/week to make it work everywhere?  I've cooled off since my initial frustration but I'm just wondering if this is normal practice or how typical web programming goes, because it seems pretty lousy to be right about now. Thanks!

答:
In the beginning, there were standards. Then, every browser decided to interpret them differently, add new features, and just plain forget the standard. Unfortunately, coding against all these browsers is a headache. Most of the normal layout will "just work," but fancy things (HTML5, CSS3, etc.) will not work in older versions of IE and probably doesn't work quite the same across all browsers (we have the standard border-shading CSS property, the -webkit and -mozilla prefixes for older versions of those browsers, and ActiveX filters to make IE do the same thing).

There is some hope, though. Browsers are getting better every release. IE 10 is far more compliant than IE 7, which is something you specifically called out. There are also HTML 5 shims that you can use to add some support for older browsers. JavaScript frameworks like jQuery iron out peculiar DOM bugs and other inconsistencies in implementations (although you'll want to use the 1.9 branch rather than the new 2.0 branch to keep support for legacy browsers). The web is slowly getting better, but until we can all agree on everything, you have ease of programming, browser support, and functionality to consider. You can only pick two.


问:
Source Code Only Allowed With One Open Source Project
I have an open source project that is licensed under the GNU General Public License v3 and it's done in Windows Presentation Foundation. I came across someone that sells themes/skins for WPF projects and he is willing to donate one of the skins for use with open source project. However, he only wants the skin to be allowed to be used with my project. I was wondering what the best way would be to prevent other people from stealing the skin and using it with their projects? Is there a license that would fit this requirement? Or is there a better way to accomplish this?</p>

答:
Either it's open, or it's not. If the skin is restricted to "just your project", then it is, by definition, not open. If, then, your project were to include this skin, by extension it wouldn't be open either.

You have two options:

a) Go with a proprietary but free-as-in-beer license. One that allows people to use the software, but not redistribute in modified form.
b) Don't include the skin. You can still prepare your code for it, and provide the skin as a separate download. That way, you can license your own code any way you like, and still distribute the skin under a different license.

As far as preventing the "stealing" (or, more correctly, unauthorized copying, modification or redistribution - nothing is really stolen, but let's not have that discussion here): technical means for this are futile - the content has to be displayed eventually, so you have to give the user complete read access to it at some point. In short; if the user can see it, the user can copy it.