答:
create a one extra project in which all common things are defined

That's exactly the way that .Net expects you to do it.

Abstract these objects into a third Assembly, and reference this from both projects.  I'd suggest doing so as Interfaces, which is cleaner, but ...

Watch out for Serialisation:

The only way I could directly serialise/ deserialise objects between the two programs (admittedly this was a while ago using Framework 2.0) was to install the "shared" assembly into the Global Assembly Cache on both client and server machines.  If the assembly was "local" to each project, then the Framework saw them as discrete Types and refused to [de]serialise the one into the other.

And [de]serialising objects Typed as Interfaces is a bit of a "challenge".  The original, non-Interface Type didn't seem to "make it" through the Serialisation "pipe" so the receiver didn't know what concrete Type to "build" from the incoming stream.

Title: Sharing classes or interfaces between different projects

Body:
I was looking for some answers in SO or here, but without any results, that's why I would ask you.

Let's assume I have a two different projects - for example server part and client part of an app. I'm developing my own part, while my friend is making the second one. But both of us should use some common interfaces like User or AccountInfo or ChangableAccount... whatever in order to ensure a compatibility. For example if a clients send a User data to server, then the server should operate on the same class. The same with interfaces etc. Moreover, if there are any changes in a common interface, both projects should adjust its code to the new situation.

The only solution I can see now is, to create a one extra project in which all common things are defined. We, me and my friend, should add this project as a dependency to a main project (client or server). Shared project can be managed by some version control system, so we have always the most up-to-date state.

What other solution would you suggest? How such problems are solved in professional apps?


问:
My architecture has a problem with views that required information from different objects. How can I solve this?
I am building an architecture like this:
These are my SW layers

```<code> ______________
|              |
|    Views     |
|______________|

 ______________
|              |
|Business Logic|
|______________|

 ______________
|              |
|  Repository  |
|______________|
</code>```

My views are going to generate my HTML to be sent to the user
Business logic is where all the business logics are
Repository is a layer to access the DB

My idea is that the repository uses entities (that are basically the representation of the tables, in order to perform DB queries.

The layers communicate between themselves using Business Objects, that are objects that represent the real-world-object itself. They can contain business rules and methods.

The views build/use DTOs, they are basically objects that have the information required to be shown on the screen. They expect also this kind of object on actions and, before calling the business logic, they create BO.

First question: what is your overall feeling about this architecture?

I've used similar architecture for some projects and I always got this problem:
If my view has this list to show :

```<code>Student1, age, course, Date Enrolled, Already paid?
</code>```

It has information from different BO.
How do you think one should build the structure?

These were the alternatives I could think of:

The view layer could call the methods to get the student, then the course it studies, then the payment information. This would cause a lot of DB accesses and my view would have the knowledge about how to act to generate this information. This just seems wrong for me.

I could have an "adapter object", that has the required information (a class that would have a properties Student, Course and Payment). But I would required one adapter object for each similar case, this may get very bad for big projects.

I still don't like them. Would you have ideas? How would you change the architecture to avoid this kind of problems?

@Rory:
I read the CQRS and I don't think this suits my needs. As taken from a link references in your link

Before describing the details of CQRS we need to understand the two main driving forces behind it: collaboration and staleness

That means: many different actors using the same object (collaboration) and once data has been shown to a user, that same data may have been changed by another actor – it is stale (staleness).

My problem is that I want to show to the user information from different BO, so I would need to receive them from the service layer. How can my service layer assemble and deliver this information?

Edit to @AndrewM:
Yes, you understood it correctly, the original idea was to have the view layer to build the BOs, but you have a very nice point about the creation of the BO inside the business layers.
Assuming I follow your advice and move the creation logic inside the business layer, my business layer interface would contain the DTOs, for instance

```<code>public void foo(MyDTO object)
</code>```

But as far as I understand, the DTO is tightly coupled to each view, so it would not be reusable by a second view. In order to use it, the second view would need to build a specific DTO from a specific view or I would have to duplicate the code in the business layer. Is this correct or am I missing something?

答:
I'm not sure I follow completely, let me see if I have this right.

The View Layer has components that generate DTOs for the UI, but generate BO's to call components in the business layer.  The components in the business layer then hand these to components in the repository layer for storage/retrieval.

If this is the case, then I'm not really sure the point of the business layer.  It is hard to tell its responsibilities from the description. If the components n the view layer are the ones creating BO's then it has fairly intricate knowledge of those.

You might want to put all BO constructions and management into components in the business layer.  It seems that the business layer should be the adapter. (This is usually what business logic is for.)  I would expect that components in the business layer would consume requests for data  from view components (e.g. get me info from student foo) and create complete objects (student, age, course, etc.) by assembling the data from the components in the repository layer.  I would expect the type (and qualities) of objects that flow between the different layers to be different in this case.

Can you explain a little more about what you are sending between the components?

ContentLicense: CC BY-SA 3.0


问:
Are there mainstream general-purpose non-Turing complete languages available today?
Non-Turing complete languages offer a great advantage over Turing-complete languages as they are much more analyzable and, thus, offer much broader optimization possibilities. Yet they are barely used and Turing-completeness is actually sold as a good feature.

Are there any mainstream non-Turing-complete languages available today that are made for general-purpose programming?

答:
The reason Turing incomplete languages are not mainstream is that it is easy to implement your own whenever you need it and however you need it. An interesting example is bitcoin-script:
https://github.com/bitcoin/bitcoin/blob/master/src/script.cpp</p>


问:
Why additional code and complexity when data model and interaction are simple is considered a disadvantage in MVC model
According to the slides given by my lecturer, one of the disadvantages of MVC model is

additional code and complexity when data model and interaction are simple

Why is this so, I would assume it would make no difference since data model and interaction are on two different components of the MVC model?

答:
Yes, model and interactions are different components of MVC but, they are related through the relationship of MVC.

If you have a very simple project with a few data and a little interaction, the MVC frameworks would generate a lot of code for something that no need this kind of complexity. But if your project starts to grow up you will have to change to MVC if you didn't before in order to maintain your code.

So yes there is an additional complexity when the data model and the interaction are simple, but if your project starts to grow this complexity would help you to maintain your code easily


答: That's the whole point.  When it is simple, you don't need two different components, and all that structure becomes overhead.  It's like turning on an industrial bakery to make one doughnut.  A certain amount of inherent complexity is required to make the overhead of the framework worth it.</p>

Title: Why additional code and complexity when data model and interaction are simple is considered a disadvantage in MVC model

Body:
According to the slides given by my lecturer, one of the disadvantages of MVC model is

additional code and complexity when data model and interaction are simple

Why is this so, I would assume it would make no difference since data model and interaction are on two different components of the MVC model?


问:
fast n-gram access data structure
TL;DR

Is there a data structure that'd quickly let me match words at any point (e.g., 'foo' matches 'foobar' and 'zoofoo'), and, ideally, returns a list of "characters that show up after the needle" (e.g., 'foo' should return ['b', $]).

I'm implementing an algorithm that generates random words from a training set of other words.

In simple terms, it's basically like this:

Choose an arbitrary starting point.

Choose the longest suffix of the current word that is contained in at least 2 other words

Choose one of those words at random, and append the next character to the current wor.

GOTO 2 until "next character" is EOW

e.g., if the current word is 'tat', some valid options would be 'potato' and 'tattoo'; if the current word is "ophtalmi", the only option is "ophtalmic", so we search if any words contain "phtalmi", "htalmi", "talmi", and so on.

I've tried a couple of implementations: in one, I've used a trie populated with every suffix of every word. This is very fast at generating words, but populating the trie is VERY slow (~4 million words have not finished in over 10 hours).

In another, I've generated a hash of:

```<code>for word in words:
    for suffix in tails(words):
        for prefix, suffix in prefixes(words): # prefixes("foo") = [("f","oo"),("fo","o"),("foo","")]
            ngrams[prefix].add(suffix) # this is a set
</code>```

and it's much faster at reading the training set, and very fast at generating, but it takes a lot of RAM.

And, finally, the dumb option, of simply searching

```<code>candidates = [word for word in words if string in words]
</code>```

which takes very little memory, but is much slower.

Is there a data structure with the behaviour I need?

答:
Either ternary search trees or marisa-tries seem data structures that perform well for common prefix search, which is what you are trying to do.

Since you seem to be using Python, here you have a package for the fomer, while the latter seems to have two Python bindings: the official one based on SWIG, but also an unofficial one based on Cython.

Title: fast n-gram access data structure


问:
How to mark unit/integration tests when they do not apply for the current test configuration - Inconclusive or Passed?
In my test environment we are running the same set of integration (and sometimes unit) tests against different systems that have different capabilities.

Some of the tests cannot be executed against some of the systems because a feature that enables this scenario is missing or we need completely different behavior.

Currently we are using MSTest and have tests with this pattern:

```<code>[TestMethod]
public void TestMethod1()
{
    if(targetSystem.SupportsFeatureX == false)
        Assert.Inconclusive("Not supported by underlying system");
    // the code for the actual test follows
}
</code>```

Should we mark the test as Inconclusive or just let it Pass if the feature check is not satisfied?

Please note that targetSystem is a third party system that we have no control over so we just live with features that are present.

答:
If your test framework supports it, you should mark tests that can't be executed due to missing (external) dependencies as skipped. That gives the clearest picture in the overview.

If the test framework does not support a 'skipped' status, then 'inconclusive' is a next-best option. At least, 'inconclusive' won't give as much of a misleading result.

Using 'pass' for tests that were not actually executed can give a misleading impression regarding the stability of a feature. Just imagine the questions you would get if the statistics show that the tests for Feature X consistently pass on systems A, B and C, but regularly fail on systems Y and Z. Is there a problem specific to systems Y and Z or do systems A, B and C not have feature X and is there a generic problem in the feature?


问:
Is it generally a good idea to work with JDK 6 instead of JDK 7?
As far as I know, there aren't a lot of differences between JDK 6 and JDK 7. At least, I haven't yet come across a difference (I coded with JDK 7 and with JDK 6).

A lot of computers run JRE 6 or JRE 7. Compiling my program using JDK 7 will narrow the number of potential computers that can run my application.

Is it generally a good idea to always program using JDK 6 and compile my program for JRE 6? Is this something common? Or is it generally a bad idea?

答:
It's generally good to use JDK 7 because its still being supported. As this question's answer states, Java 6 is at end of life. This means that security updates are less of a priority if at all and compatibility with newer systems is not an issue that is of particular importance to the maintainers of the JDK.

You may not use many features of Java 7 but that doesn't mean you shouldn't be targeting it for release. The only reason you'd want to target JDK 6 that I can think of is that the deployment environment that you are targeting can't support Java 7.

There's also the small matter of the very near future release of Java 8.


问:
Why does Rails do config in code?
According to the Pragmatic Programmers, code should be for abstractions, while configuration and details should live in metadata. Rails seems to diverge dramatically from this pattern. Much config is done in code files such as application.rb, routes.rb and the various environment.rb files, while other types of config is done in yaml files (e.g. database.yml). What is the thinking behind this design decision?

答:
In Rails those boundaries always have been a bit blurred. There are several reasons for this, the first one maybe the simple fact that the Ruby language allows it to write code that looks like configurations. For example you can use methods without putting the arguments in braces, which leads to the common usage of things like this:

```<code>has_many :orders
</code>```

in the model definitions. Looks like a configuration, actually is a method call with the param :orders.

Starting from this point it is often easier to chain method calls for complex configuration options. This especially in files like routes.rb. Also this allows for very dynamic configurations (say you want to use regular expressions in your routing). Also the routing can in general be a much more dynamic thing, so having code that's executed is often more viable.

Actually in many places those .rb files do not generate 'static' configurations, but move anonymous functions in place that later get called, eg when a route has to be evaluated.

In case of the very basic files like environment.rb and application.rb it is a bit misleading to call them configuration files. They are more a kind of anchor points where you can add require calls to be executed while the Rails system is bootstrapping its class hierarchy.

So there is a mix of reasons active here, some simply based on the 'Ruby culture', others for practical purposes. (Not every single one necessarily the best decision, but most of the time they make sense once you see the advanced possibilities you get from them).

Title: Why does Rails do config in code?

Body:
In Rails those boundaries always have been a bit blurred. There are several reasons for this, the first one maybe the simple fact that the Ruby language allows it to write code that looks like configurations. For example you can use methods without putting the arguments in braces, which leads to the common usage of things like this:

has_many :orders

in the model definitions. Looks like a configuration, actually is a method call with the param :orders.

Starting from this point it is often easier to chain method calls for complex configuration options. This especially in files like routes.rb. Also this allows for very dynamic configurations (say you want to use regular expressions in your routing). Also the routing can in general be a much more dynamic thing, so having code that's executed is often more viable.

Actually in many places those .rb files do not generate 'static' configurations, but move anonymous functions in place that later get called, eg when a route has to be evaluated.

In case of the very basic files like environment.rb and application.rb it is a bit misleading to call them configuration files. They are more a kind of anchor points where you can add require calls to be executed while the Rails system is bootstrapping its class hierarchy.

So there is a mix of reasons active here, some simply based on the 'Ruby culture', others for practical purposes. (Not every single one necessarily the best decision, but most of the time they make sense once you see the advanced possibilities you get from them).


问:
Should I use git for project files, other than the actual source?
I have a lot of small projects, and while their source code is backed up and tracked with git, I don't know what to do with the rest of the files associated with a project.

These consist of small text files, some images, maybe a prototype or proof of concept, etc. They're not necessary to build or deploy, but I need them while working on the project.

It's not really documentation, but rather todo lists, bugs to be fixed, a few screenshots, that sort of thing. As I said before, they're small projects so I don't think I should create a wiki/bugtracker for each one, especially since I'm the only developer :)

I backup these, but I feel they could benefit from git as well (in another repository). I've sorted these files in three main folders, "current", "abandoned", and "finished".

Should I use git and just git mv the files when the project is finished or abandoned ? I'm a bit new to git, and I don't know how well tools "like" whole folders that move.

If you have a better way of keeping track of those files, I'm interested. It's probably too broad for a SE question, though.

答:
If the build fails without them, add to master.
If the build passes but you need these files for whatever reason, add them in another branch like "resources".
If you don't need them any more, just remove them.</p>


答: Any project files which are needed for the production system (the application code + tests to ensure requirements compliance, configuration, cron jobs, and anything else which is part of your process) and which cannot be generated automatically (even using wget) should be in version control. Everything else can be ignored.

Title: Should I use git for project files, other than the actual source?

Body:
I have a lot of small projects, and while their source code is backed up and tracked with git, I don't know what to do with the rest of the files associated with a project.

These consist of small text files, some images, maybe a prototype or proof of concept, etc. They're not necessary to build or deploy, but I need them while working on the project.

It's not really documentation, but rather todo lists, bugs to be fixed, a few screenshots, that sort of thing. As I said before, they're small projects so I don't think I should create a wiki/bugtracker for each one, especially since I'm the only developer :)

I backup these, but I feel they could benefit from git as well (in another repository). I've sorted these files in three main folders, "current", "abandoned", and "finished".

Should I use git and just git mv the files when the project is finished or abandoned ? I'm a bit new to git, and I don't know how well tools "like" whole folders that move.

If you have a better way of keeping track of those files, I'm interested. It's probably too broad for a SE question, though.


问:
Are all race conditions worth fixing?
I just wrote the following piece of code (in delphi):

```<code>procedure Update(Value: Integer);
begin
  // If the last update was yesterday, replace yesterday value
  if CompareDate(FLastUpdate,Now) <> 0 then
  begin
    FYesterdayValue := FTodayValue;
  end;
  FTodayValue := Value;
  FLastUpdate := Now;
end;
</code>```

And I realized that it contains a small, but real race condition. Imagine that the first time the "Now" function is called it's one millisecond before midnight, the if-statement is skipped and the timestamp is updated with another call to "Now" which is now one millisecond AFTER midnight. Now the timestamp has the wrong value and the FYesterdayValue will not get the correct value.

In practise, I think the chances of this ever happening is almost non existent because a) the code is typically called ~1 / minute and b) the cpu time between the two call will be EXTREMELY small.

However it's a bug and I'm curious if you would fix it if you stumbled upon it in a project.

答:
As a general rule, problems are worth fixing when the expected benefit exceeds the expected cost. Thread safety is no exception from this rule, it's just that the way of calculating the risk that determines the expected cost is particularly complex and ill-understood by many.

To begin with, threading safety is not on many people's radar. They will simply assume "This is never called concurrently, nothing can go wrong". And often it isn't. Other times it is (e.g. the CPU stalled for an unexpectedly large time because the entire app now lives in an oversubscribed virtual machine...), and then nobody has any clue what could possibly have happened. In other words, the probability of a race actually occurring is often very hard to estimate.

The impact is often easier to understand: if you're logging some informative stuff to an internal audit log, it tends to be low; if the date that you're maintaining is related to business logic (perhaps it determines when the subscription licence of your customer expires?), then it might be catastrophically bad.

Without knowing the context of this code, I can't predict what should be done. But almost certainly it isn't a good idea to notice a possible race condition and do nothing about it by just convincing yourself that it won't be a problem. First, as I said, it is particularly hard to predict whether it will be a problem or not. Second, if the condition were probable, you would have to deal with it after all, so you have to be capable of securing your code. And if you understand how to do that (usually it isn't that hard), there is comparatively little reason not to do it all the time as a matter of principle - just to avoid convincing yourself "Ah, I don't need to worry in this instance, this will never happen", which is a classic example of "Famous last words".

Title: Are all race conditions worth fixing?


答:
We get a different picture when we read the whole page you linked to, and not just the headline.

program for the general case, and put the specifics somewhere else - outside the compiled code base.

We don't have a compiled code base, my Ruby is interpreted. There is no recompilation step, changing the configuration is as easy as changing the source file and restarting the program.

There are several benefits to this approach:

It forces you to decouple your design, which results in a more flexible and adaptable program.

The RoR framework is already sufficiently decoupled.

It forces you to create a more robust, abstract design by deferring details—deferring them all the way out of the program.

Parts of the implementation may also be details that should be deferred out of the main program. In dynamic languages, there simply isn't this great dichotomy between code and data – code is just another kind of data. This has been shown with great success by the Lisp languages, and Ruby stands firmly in this Lispish tradition via its Smalltalk heritage.

You can customize the application without recompiling it. You can also use this level of customization to provide easy work-arounds for critical bugs in live production systems.

Again, no recompiling is necessary with Ruby (or other dynamic languages like Python or Perl). In fact, we can monkey-patch new code into the system while it's still running.

Metadata can be expressed in a manner that's much closer to the problem domain than a general-purpose programming language might be (see Domain Languages).

Ruby's syntax is flexible enough that it's easy to whip up half a DSL with it. In fact, the Ruby implementation gives us a parser and compiler for free, all we have to do is to implement the semantics.

You may even be able to implement several different projects using the same application engine, but with different metadata.

Exactly. The RoR framework takes application-specific code from your configuration files. It's easy to swap out these files for another website.

Title: Why does Rails do config in code?

Body: According to the Pragmatic Programmers, code should be for abstractions, while configuration and details should live in metadata. Rails seems to diverge dramatically from this pattern. Much config is done in code files such as application.rb, routes.rb and the various environment.rb files, while other types of config is done in yaml files (e.g. database.yml). What is the thinking behind this design decision?


问:
Sharing classes or interfaces between different projects
I was looking for some answers in SO or here, but without any results, that's why I would ask you.

Let's assume I have a two different projects - for example server part and client part of an app. I'm developing my own part, while my friend is making the second one. But both of us should use some common interfaces like User or AccountInfo or ChangableAccount... whatever in order to ensure a compatibility. For example if a clients send a User data to server, then the server should operate on the same class. The same with interfaces etc. Moreover, if there are any changes in a common interface, both projects should adjust its code to the new situation.

The only solution I can see now is, to create a one extra project in which all common things are defined. We, me and my friend, should add this project as a dependency to a main project (client or server). Shared project can be managed by some version control system, so we have always the most up-to-date state.

What other solution would you suggest? How such problems are solved in professional apps?

答: As others have suggested, your thought process is accurate.  Professionally, most would use something like Maven or Gradle to manage these dependencies efficiently.</p>


问:
Using π, φ, λ etc. as variable names while programming?
This is a function in the d3.v3.js file (the graph library D3.js):

```<code>  function d3_geo_areaRingStart() {
    var λ00, φ00, λ0, cosφ0, sinφ0;
    d3_geo_area.point = function(λ, φ) {
      d3_geo_area.point = nextPoint;
      λ0 = (λ00 = λ) * d3_radians, cosφ0 = Math.cos(φ = (φ00 = φ) * d3_radians / 2 + π / 4),
      sinφ0 = Math.sin(φ);
    };
    function nextPoint(λ, φ) {
      λ *= d3_radians;
      φ = φ * d3_radians / 2 + π / 4;
      var dλ = λ - λ0, cosφ = Math.cos(φ), sinφ = Math.sin(φ), k = sinφ0 * sinφ, u = cosφ0 * cosφ + k * Math.cos(dλ), v = k * Math.sin(dλ);
      d3_geo_areaRingSum.add(Math.atan2(v, u));
      λ0 = λ, cosφ0 = cosφ, sinφ0 = sinφ;
    }
    d3_geo_area.lineEnd = function() {
      nextPoint(λ00, φ00);
    };
  }
</code>```

I was completely taken aback that the programmers used π, φ and λ as variable names. Surprisingly, these variables were accepted even by Notepad (ie: it didn't turn into junk/unrecognized characters).

Is it good practice to use such variables? I can see that they're very intuitive and searchable too, but a bit unnerving.

答:
It's a good idea for someone else to use full unicode variable names.

Eventually, after someone else has found all the problems in all sorts of tools and environments and all of those problems have been fixed; it might even be a good idea for you or me to use them. Of course when that time comes, I still won't know how to type them quickly and would have to refuse.


答:
I would fix this bug, not just because of the race condition, but also because the version where you call Now once at the start and save it is much easier to reason about in general.

Basically, the more predictable a function is, the easier it is to understand. Now is, in a way, very unpredictable (it might return different values every time you call it), and thus every time you call it you make your own function less predictable and harder to understand.

As such, I really like Rory's suggestion that you refactor the call to Now out of the function completely. Now it's even more predictable, and as he points out, unit-testable.

Title: Are all race conditions worth fixing?

Body:
I just wrote the following piece of code (in delphi):

```<code>procedure Update(Value: Integer);
begin
  // If the last update was yesterday, replace yesterday value
  if CompareDate(FLastUpdate,Now) <> 0 then
  begin
    FYesterdayValue := FTodayValue;
  end;
  FTodayValue := Value;
  FLastUpdate := Now;
end;
</code>```

And I realized that it contains a small, but real race condition. Imagine that the first time the "Now" function is called it's one millisecond before midnight, the if-statement is skipped and the timestamp is updated with another call to "Now" which is now one millisecond AFTER midnight. Now the timestamp has the wrong value and the FYesterdayValue will not get the correct value.

In practise, I think the chances of this ever happening is almost non existent because a) the code is typically called ~1 / minute and b) the cpu time between the two call will be EXTREMELY small.

However it's a bug and I'm curious if you would fix it if you stumbled upon it in a project.


答:
Is it good practice to use such variables? I think that it is especially in this case where you can write formulae in their native-looking form.  Though i think it's better to say that it's good practice to declare that your HTML documents are unicode (providing, of course, that they are unicode) using at least:

<meta charset="utf-8">

Title: Using π, φ, λ etc. as variable names while programming?

Body:
This is a function in the d3.v3.js file (the graph library D3.js):

```<code>  function d3_geo_areaRingStart() {
    var λ00, φ00, λ0, cosφ0, sinφ0;
    d3_geo_area.point = function(λ, φ) {
      d3_geo_area.point = nextPoint;
      λ0 = (λ00 = λ) * d3_radians, cosφ0 = Math.cos(φ = (φ00 = φ) * d3_radians / 2 + π / 4),
      sinφ0 = Math.sin(φ);
    };
    function nextPoint(λ, φ) {
      λ *= d3_radians;
      φ = φ * d3_radians / 2 + π / 4;
      var dλ = λ - λ0, cosφ = Math.cos(φ), sinφ = Math.sin(φ), k = sinφ0 * sinφ, u = cosφ0 * cosφ + k * Math.cos(dλ), v = k * Math.sin(dλ);
      d3_geo_areaRingSum.add(Math.atan2(v, u));
      λ0 = λ, cosφ0 = cosφ, sinφ0 = sinφ;
    }
    d3_geo_area.lineEnd = function() {
      nextPoint(λ00, φ00);
    };
  }
</code>```

I was completely taken aback that the programmers used π, φ and λ as variable names. Surprisingly, these variables were accepted even by Notepad (ie: it didn't turn into junk/unrecognized characters).

Is it good practice to use such variables? I can see that they're very intuitive and searchable too, but a bit unnerving.


答:
If I saw one of my coworkers writing code with such variable names, I would ask them their rationale for such a decision, but ultimately I think it would have to be changed. Variable names should be descriptive, but also easy to read/write/modify. I don't even know how to type π, λ, or φ on my keyboard. I shouldn't have to go about copy/pasting symbols in my editor when I write my code.

In general, unless the symbol is universally understood, is easily produceable, and is ultimately descriptive to its purpose, I would not use it. I would shy away from foreign words, overly large/advanced words as well. The better solution in this case would be to write out the symbols as their names: "pi", "lambda", and "phi".


答: When the code is written in an environment where greek keyboards are standard (like in greece), this maybe acceptable (assumed the letters have some mathematical meaning for the people who have to read and maintain the code).  Otherwise editing greek letters will IMHO become very cumbersome, so I would not recommend it in general, even when the symbols have some certain meaning to the reader.</p>


问:
Difference between networking programming and socket programming
Are there any major differences when we talk about "socket programming" compared to "network programming"?

Are there some topics that cover "network programming" but not "socket programming"?

答: Yeah, it's true that network programming requires networking technology while on the other hand socket programming is a subset of network programming. Most current network programming is done either using sockets directly, or using various other layers on top of sockets.</p>


答:
It's entirely dependent on the environment you find yourself in. These symbols are unicode, so you need a development environment that supports unicode. Also, they are dependent on special keystrokes or copy-pasting. This means that they are easier to do on a Mac since Macs have built in support for generating such things via the option key. Windows can do it but you've got to remember all of the various unicode numbers for each symbol.

I suspect the reasoning here is one of minification since φ takes up slightly less space than phi. It also ensures that the browser using D3.js is fairly modern.


问:
How to get around the Circular Reference issue with JSON and Entity
I have been experimenting with creating a website that leverages MVC with JSON for my presentation layer and Entity framework for data model/database. My Issue comes into play with serializing my Model objects into JSON.

I am using the code first method to create my database.  When doing the code first method a one to many relationship (parent/child) requires the child to have a reference back to the parent. (Example code my be a typo but you get the picture)

```<code>class parent
{
   public List<child> Children{get;set;}
   public int Id{get;set;}

}
class child
{
    public int ParentId{get;set;}
    [ForeignKey("ParentId")]
    public parent MyParent{get;set;}
    public string name{get;set;}
 }
</code>```

When returning a "parent" object via a JsonResult a circular reference error is thrown because "child" has a property of class parent.

I have tried the ScriptIgnore attribute but I lose the ability to look at the child objects. I will need to display information in a parent child view at some point.

I have tried to make base classes for both parent and child that do not have a circular reference. Unfortunately when I attempt to send the baseParent and baseChild these are read by the JSON Parser as their derived classes (I am pretty sure this concept is escaping me).

```<code>Base.baseParent basep = (Base.baseParent)parent;
return Json(basep, JsonRequestBehavior.AllowGet);
</code>```

The one solution I have come up with is to create "View" Models. I create simple versions of the database models that do not include the reference to the parent class. These view models each have method to return the Database Version and a constructor that takes the database model as a parameter (viewmodel.name = databasemodel.name).  This method seems forced although it works.

NOTE:I am posting here because I think this is more discussion worthy. I could leverage a different design pattern to over come this issue or it could be as simple as using a different attribute on my model.  In my searching I have not seen a good method to overcome this problem.

My end goal would be to have a nice MVC application that heavily leverages JSON for communicating with the server and displaying data.  While maintaining a consistant model across layers (or as best as I can come up with).

答:
I see two distinct subjects in your question:

How to manage circular references when serializing to JSON?

How safe is it to use EF entities as model entities in you views?

Concerning circular references I'm sorry to say that there is no simple solution. First because JSON cannot be used to represent circular references, the following code:

```<code>var aParent = {Children : []}, aChild  = {Parent : aParent};
aParent.Children.push(aChild);
JSON.stringify(aParent);
</code>```

Results in: TypeError: Converting circular structure to JSON

The only choice you have is to keep only the composite --> component part of the composition and discard the "back navigation" component --> composite, thus in you example:

```<code>class parent
{
    public List<child> Children{get;set;}
    public int Id{get;set;}
}
class child
{
    public int ParentId{get;set;}
    [ForeignKey("ParentId"), ScriptIgnore]
    public parent MyParent{get;set;}
    public string name{get;set;}
}
</code>```

Nothing prevents you from recomposing this navigation property on your client side, here using jQuery:

```<code>$.each(parent.Children, function(i, child) {
  child.Parent = parent;
})
</code>```

But then you will need to discard it again before sending it back to the server, for JSON.stringify won't be able to serialize the circular reference:

```<code>$.each(parent.Children, function(i, child) {
  delete child.Parent;
})
</code>```

Now there is the issue of using EF entities as your view model entities.

First EF is likely to using Dynamic Proxies of your class to implement behaviors such as change detection or lazy loading, you have to disable those if you want to serialize the EF entities.

Moreover using EF entities in the UI can be at risk since all the default binder will mapping every field from the request to entities fields including those you did not want the user to set.

Thus, if you want you MVC app to be properly designed I would recommended to use a dedicated view model to prevent the "guts" of your internal business model from being exposed to the client, thus I would recommend you a specific view model.

Body:
I see two distinct subjects in your question:

How to manage circular references when serializing to JSON?

How safe is it to use EF entities as model entities in you views?

Concerning circular references I'm sorry to say that there is no simple solution. First because JSON cannot be used to represent circular references, the following code:

var aParent = {Children : []}, aChild  = {Parent : aParent};
aParent.Children.push(aChild);
JSON.stringify(aParent);

Results in: TypeError: Converting circular structure to JSON

The only choice you have is to keep only the composite --> component part of the composition and discard the "back navigation" component --> composite, thus in you example:

class parent
{
    public List<child> Children{get;set;}
    public int Id{get;set;}
}
class child
{
    public int ParentId{get;set;}
    [ForeignKey("ParentId"), ScriptIgnore]
    public parent MyParent{get;set;}
    public string name{get;set;}
}

Nothing prevents you from recomposing this navigation property on your client side, here using jQuery:

$.each(parent.Children, function(i, child) {
  child.Parent = parent;
})

But then you will need to discard it again before sending it back to the server, for JSON.stringify won't be able to serialize the circular reference:

$.each(parent.Children, function(i, child) {
  delete child.Parent;
})

Now there is the issue of using EF entities as your view model entities.

First EF is likely to using Dynamic Proxies of your class to implement behaviors such as change detection or lazy loading, you have to disable those if you want to serialize the EF entities.

Moreover using EF entities in the UI can be at risk since all the default binder will mapping every field from the request to entities fields including those you did not want the user to set.

Thus, if you want you MVC app to be properly designed I would recommended to use a dedicated view model to prevent the "guts" of your internal business model from being exposed to the client, thus I would recommend you a specific view model.


答:
create a one extra project in which all common things are defined

This is the exactly first step to share reusable parts - and its the easy part. The more challenging part is to decide if the two projects which are using the shared library shall have independent release cycles (or not), and if it should be possible that "project A" uses version 1.0 of your shared lib, whilst project B uses version 2.0 at the same time.

If you want the latter to be possible, you need to have a strict versioning scheme and release management for your library (and version numbers as part of the library file name, like suggested by @RoryHunter). You should also take care about backward compatibility in your lib in this situation. Your library should be managed as a separate product, adding unit tests to it to make sure the different versions in production will be a good idea, and a tool like Maven can make sense, too.

If, however, you want prevent that situation, you should manage "project A", "project B" and your lib as a common project, with a combined development, build and release process. This will allow to change the common interface of the shared library much more and often than in the first scenario. And you won't need something like Maven or version numbers in the library file name. But the tradeoff is that A and B cannot be developed independently any more.


答:
Kudos to @WorldEngineer. I do want to add that the decision of whether to support JDK 6 or other backwards compatibility requirements is not usually your decision to make unless you are the CTO or other decision maker at your organization, or this is just a hobby project--so why worry about it? Tell the people that have a stake in the issue what the costs, risks/rewards are and then go with what they tell you.

Backwards compatibility is almost always a business decision: not a dev decision. IMHO, when you have a choice, go with the latest stable standard for whatever technology you are using unless the business tells you otherwise.

I would strongly advise against making this decision on your own and not letting the business owners make it for you. CYA.

Of course, if this is in regards to a hobby project, or you are the CTO etc... I think you should always go with the latest standard.

Title: Is it generally a good idea to work with JDK 6 instead of JDK 7?

Body:
As far as I know, there aren't a lot of differences between JDK 6 and JDK 7. At least, I haven't yet come across a difference (I coded with JDK 7 and with JDK 6).

A lot of computers run JRE 6 or JRE 7. Compiling my program using JDK 7 will narrow the number of potential computers that can run my application.

Is it generally a good idea to always program using JDK 6 and compile my program for JRE 6? Is this something common? Or is it generally a bad idea?


问:
How do you version your files (Version Numbers)
I wonder how do you decide on the version number of your apps, do you really record down all changes made (for a change log)? Then how will you decide how to increment the version number. eg. +0.0.1 for each bug fix or something, +0.1 for each new feature release? or maybe you bundle many changes into +0.1 of your version number?</p>

答:
Although this has changed through the years (I've worked on several projects which each used different versioning schemes), it has always been something like this:

the major version, the minor version, and the update version

X.Y.Z.WWWW

X: major release with identifiable new features

Y: minor release with existing feature improvements

Z: update release (distributed) containing bug fixes but no new functionality

W: code build - internal to programmers

These program version numbers did not necessarily correspond to the numbers used by marketing. What I mean? For example, Word 2000 (communicated to the public) is really Word 9.0.1.3821 (internal to the product team). Product marketing owns the name that's distributed; Development owns versioning and the project code name.

Numbering schemes are largely irrelevant to customers; versioning is only for keeping track of what is shipping to the customer. There are many software developers who think that numbering schemes are a not-important marketing aspect of the product. Marketing people and customers generally do not (or should not) care about version numbers.

ContentLicense: CC BY-SA 2.5


问:
Is it a good idea to develop website that only has little access to DB? CRUD will be done by calling API provided by separate internal backend system
I'm going to start developing an application in near future. This application consists of :

Back-end system. This system provides API to be used by client. This
system connects to data store and 3rd party API.

Data Store : Can be relational or nosql data store.

Client : Client will be a website and mobile applications.

My reasons are below :

I want to prevent duplicated SQL query and 3rd party API call in
website application side. The application and website will be
developed by different developers. Only back end system
developers that can make query or call 3rd party API. All website
developers should only use API provided by back-end system

In my opinion, the website is also a client just like the mobile
application. If the mobile apps get their data from back-end system
API, why the website shouldn't be the same.

I heard twitter is using similar idea (I can be wrong though). Its
website is using twitter API just like their mobile application.

My primary concern to this architecture is that the website performance will be lower compared than If the website can make query or 3rd party API call directly.

Is there any other pros and cons that I should think about ?

答:
You're basically describing a service layer.

Your performance concerns seem unfounded.  In practice, your service layer will merely translate your API into the necessary 3rd party API or SQL calls; the overhead should be minimal.


问:
Should an object update itself?
I'm working on Ruby on Rails. There is a feature in our app where doctors can "claim" cases for themselves.

I can either have the doctor perform the action and update the plate, or I can have the doctor send itself to the plate and have the plate update itself.

Should objects update itself? It just seems cleaner to me, but I'm not sure. Or maybe I'm overthinking?

First case, doctor only:

```<code>def claim(plate)
  plate.claimed = true
  plate.doctor_id = id
  plate.save
end
</code>```

This is the second case (doctor sends itself to the plate):

```<code>  #doctor
  def claim(plate)
    plate.claimed_by(self)
  end

  #plate
  def claimed_by(doctor)
    self.claimed = true
    self.doctor_id = doctor.id
    self.save
  end
</code>```

答:
The second case allows additional business logic (such as validation) to occur in the method body, unless plate.claimed and plate.doctor_id are first-class properties, and already have validation in their own right.

The second case is more "atomic," in the sense that the plate object has more control over its own state within the claimed_by method.  If something goes wrong, you're still in the method body, and have an opportunity to do some clean up.

The second case is a better example of "Tell, don't ask.".  Rather than manipulating the plate object's data from the outside, you're telling the plate object what you want, and letting the plate object manipulate its own state.

Title: Should an object update itself?


问:
Simple dependency handling for objects (perl)
I am a bit stuck with a design of a project, where many objects has to have access to the same piece of information. It could be some data, to construct a global-like object for themselves or the object itself (essentially a config object).

Essentialy these object are in a tree: On a top is a 'Router' object, which has 'Interface's, which has 'Host's. Router creates interfaces and interface creates hosts. Also, the router object gets that config object as parameter in constructor.

I would like to keep the code clean and easy to test, keeping the neccessary mocking at minimum and allowing easy test setups.

Which methods is recommended for providing access to this config object accross the project?

use a singleton instance of the config object

use a superglobal config object

Each object (router, interface, host) should get the config object via the constructor -> in every new object calls there should be this config object. It would be like: Host->new({config => $self->config})

Each object should have a reference to the parent router. Interface and Host will have access to the Router (which will be passed to them in the constructor -> weak_ref to the main Router object), and they will access the router's config object

Interface will have a delegate method to retrieve the config object from the router and Host will have access to this config object through this method -> this implies, that everyone should be aware of it's parents (host should have a reference to the parent interface, interface should have a reference to the router etc.)

Or maybe have a singleton global object-storage, from which everyone could retreive what they want (config object, database handle etc)?

Or use some existing dependency injection system, which seems like an overkill (a lot)

答:
My vote is for managing the dependencies through the constructors of your classes (#3).  You can use whatever mechanism you feel is appropriate to generate the config object.

Handing your objects their dependencies through the constructor is essentially a poor man's form of Dependency Injection.  The only thing you will miss by not having a DI framework is the ability to have centralized configuration of your dependencies.  You will not need this unless your system is large and you have to manage many dependencies.


问:
Are value converters more trouble than they're worth?
I'm working on a WPF application with views that require numerous value conversions. Initially, my philosophy (inspired in part by this lively debate on XAML Disciples) was that I should make the view model strictly about supporting the data requirements of the view. This meant that any value conversions required to turn data into things like visibilities, brushes, sizes, etc. would be handled with value converters and multi-value converters. Conceptually, this seemed quite elegant. The view model and view would both have a distinct purpose and be nicely decoupled. A clear line would be drawn between "data" and "look".

Well, after giving this strategy "the old college try", I'm having some doubts whether I want to continue developing this way. I'm actually strongly considering dumping the value converters and placing the responsibility for (almost) all value conversion squarely in the hands of the view model.

The reality of using value converters just doesn't seem to be measuring up to the apparent value of cleanly separated concerns. My biggest issue with value converters is that they are tedious to use. You have to create a new class, implement IValueConverter or IMultiValueConverter, cast the value or values from object to the correct type, test for DependencyProperty.Unset (at least for multi-value converters), write the conversion logic, register the converter in a resource dictionary [see update below], and finally, hook up the converter using rather verbose XAML (which requires use of magic strings for both the binding(s) and the name of the converter [see update below]). The debugging process is no picnic either, as error messages are often cryptic, especially in Visual Studio's design mode/Expression Blend.

This isn't to say that the alternative--making the view model responsible for all value conversion--is an improvement. This could very well be a matter of the grass being greener on the other side. Besides losing the elegant separation of concerns, you have to write a bunch of derived properties and make sure you conscientiously call RaisePropertyChanged(() => DerivedProperty) when setting base properties, which could prove to be an unpleasant maintenance issue.

The following is an initial list I put together of the pros and cons of allowing view models to handle conversion logic and doing away with value converters:

Pros:

Fewer total bindings since multi-converters are eliminated

Fewer magic strings (binding paths + converter resource names)

No more registering each converter (plus maintaining this list)

Less work to write each converter (no implementing interfaces or casting required)

Can easily inject dependencies to help with conversions (e.g., color tables)

XAML markup is less verbose and easier to read

Converter reuse still possible (although some planning is required)

No mysterious issues with DependencyProperty.Unset (a problem I noticed with multi-value converters)

*Strikethroughs indicate benefits that disappear if you use markup extensions (see update below)

Cons:

Stronger coupling between view model and view (e.g., properties must deal with concepts like visibility and brushes)

More total properties to allow direct mapping for every binding in view

RaisePropertyChanged must be called for each derived property (see Update 2 below)

Must still rely on converters if the conversion is based on a property of a UI element

So, as you can probably tell, I have some heartburn about this issue. I'm very hesitant to go down the road of refactoring only to realize that the coding process is just as inefficient and tedious whether I use value converters or expose numerous value conversion properties in my view model.

Am I missing any pros/cons? For those who have tried both means of value conversion, which did you find worked better for you and why? Are there any other alternatives? (The disciples mentioned something about type descriptor providers, but I couldn't get a handle on what they were talking about. Any insight on this would be appreciated.)

Update

I found out today that it's possible to use something called a "markup extension" to eliminate the need to register value converters. In fact, it not only eliminates the need to register them, but it actually provides intellisense for selecting a converter when you type Converter=. Here is the article that got me started: http://www.wpftutorial.net/ValueConverters.html.

The ability to use a markup extension changes the balance somewhat in my pros and cons listing and discussion above (see strikethroughs).

As a result of this revelation, I'm experimenting with a hybrid system where I use converters for BoolToVisibility and what I call MatchToVisibility and the view model for all other conversions. MatchToVisibility is basically a converter that lets me check if the bound value (usually an enum) matches one or more values specified in XAML.

Example:

```<code>Visibility="{Binding Status, Converter={vc:MatchToVisibility
            IfTrue=Visible, IfFalse=Hidden, Value1=Finished, Value2=Canceled}}"
</code>```

Basically what this does is check if the status is either Finished or Canceled. If it is, then the visibility gets sets to "Visible". Otherwise, it gets sets to "Hidden". This turned out to be a very common scenario, and having this converter saved me about 15 properties on my view model (plus associated RaisePropertyChanged statements). Note that when you type Converter={vc:, "MatchToVisibility" shows up in an intellisense menu. This noticeably reduces the chance of errors and makes using value converters less tedious (you don't have to remember or look up the name of the value converter you want).

In case you're curious, I'll paste the code below. One important feature of this implementation of MatchToVisibility is that it checks to see if the bound value is an enum, and if it is, it checks to make sure Value1, Value2, etc. are also enums of the same type. This provides a design-time and run-time check of whether any of the enum values are mistyped. To improve this to a compile-time check, you can use the following instead (I typed this by hand so please forgive me if I made any mistakes):

```<code>Visibility="{Binding Status, Converter={vc:MatchToVisibility
            IfTrue={x:Type {win:Visibility.Visible}},
            IfFalse={x:Type {win:Visibility.Hidden}},
            Value1={x:Type {enum:Status.Finished}},
            Value2={x:Type {enum:Status.Canceled}}"
</code>```

While this is safer, it's just too verbose to be worth it for me. I might as well just use a property on the view model if I'm going to do this. Anyway, I'm finding that the design-time check is perfectly adequate for the scenarios I've tried so far.

Here's the code for MatchToVisibility

```<code>[ValueConversion(typeof(object), typeof(Visibility))]
public class MatchToVisibility : BaseValueConverter
{
    [ConstructorArgument("ifTrue")]
    public object IfTrue { get; set; }

    [ConstructorArgument("ifFalse")]
    public object IfFalse { get; set; }

    [ConstructorArgument("value1")]
    public object Value1 { get; set; }

    [ConstructorArgument("value2")]
    public object Value2 { get; set; }

    [ConstructorArgument("value3")]
    public object Value3 { get; set; }

    [ConstructorArgument("value4")]
    public object Value4 { get; set; }

    [ConstructorArgument("value5")]
    public object Value5 { get; set; }

    public MatchToVisibility() { }

    public MatchToVisibility(
        object ifTrue, object ifFalse,
        object value1, object value2 = null, object value3 = null,
        object value4 = null, object value5 = null)
    {
        IfTrue = ifTrue;
        IfFalse = ifFalse;
        Value1 = value1;
        Value2 = value2;
        Value3 = value3;
        Value4 = value4;
        Value5 = value5;
    }

    public override object Convert(
        object value, Type targetType, object parameter, CultureInfo culture)
    {
        var ifTrue = IfTrue.ToString().ToEnum<Visibility>();
        var ifFalse = IfFalse.ToString().ToEnum<Visibility>();
        var values = new[] { Value1, Value2, Value3, Value4, Value5 };
        var valueStrings = values.Cast<string>();
        bool isMatch;
        if (Enum.IsDefined(value.GetType(), value))
        {
            var valueEnums = valueStrings.Select(vs => vs == null ? null : Enum.Parse(value.GetType(), vs));
            isMatch = valueEnums.ToList().Contains(value);
        }
        else
            isMatch = valueStrings.Contains(value.ToString());
        return isMatch ? ifTrue : ifFalse;
    }
}
</code>```

Here's the code for BaseValueConverter

```<code>// this is how the markup extension capability gets wired up
public abstract class BaseValueConverter : MarkupExtension, IValueConverter
{
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return this;
    }

    public abstract object Convert(
        object value, Type targetType, object parameter, CultureInfo culture);

    public virtual object ConvertBack(
        object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
</code>```

Here's the ToEnum extension method

```<code>public static TEnum ToEnum<TEnum>(this string text)
{
    return (TEnum)Enum.Parse(typeof(TEnum), text);
}
</code>```

Update 2

Since I posted this question, I've come across an open-source project that uses "IL weaving" to inject NotifyPropertyChanged code for properties and dependent properties. This makes implementing Josh Smith's vision of the view model as a "value converter on steroids" an absolute breeze. You can just use "Auto-Implemented Properties", and the weaver will do the rest.

Example:

If I enter this code:

```<code>public string GivenName { get; set; }
public string FamilyName { get; set; }

public string FullName
{
    get
    {
        return string.Format("{0} {1}", GivenName, FamilyName);
    }
}
</code>```

...this is what gets compiled:

```<code>string givenNames;
public string GivenNames
{
    get { return givenName; }
    set
    {
        if (value != givenName)
        {
            givenNames = value;
            OnPropertyChanged("GivenName");
            OnPropertyChanged("FullName");
        }
    }
}

string familyName;
public string FamilyName
{
    get { return familyName; }
    set
    {
        if (value != familyName)
        {
            familyName = value;
            OnPropertyChanged("FamilyName");
            OnPropertyChanged("FullName");
        }
    }
}

public string FullName
{
    get
    {
        return string.Format("{0} {1}", GivenName, FamilyName);
    }
}
</code>```

That's a huge savings in the amount of code you have to type, read, scroll past, etc. More importantly, though, it saves you from having to figure out what your dependencies are. You can add new "property gets" like FullName without having to painstakingly go up the chain of dependencies to add in RaisePropertyChanged() calls.

What is this open-source project called? The original version is called "NotifyPropertyWeaver", but the owner (Simon Potter) has since created a platform called "Fody" for hosting a whole series of IL weavers. The equivalent of NotifyPropertyWeaver under this new platform is called PropertyChanged.Fody.

Fody setup instructions: http://code.google.com/p/fody/wiki/SampleUsage (replace "Virtuosity" with "PropertyChanged")

PropertyChanged.Fody project site: http://code.google.com/p/propertychanged/

If you'd prefer to go with NotifyPropertyWeaver (which a little simpler to install, but won't necessarily be updated in the future beyond bug fixes), here is the project site:
http://code.google.com/p/notifypropertyweaver/

Either way, these IL weaver solutions completely change the calculus in the debate between view model on steroids vs. value converters.

答:
Sometimes it is good to use a value converter to take advantage of virtualization.

An example of this what in a project where we had to display bitmasked data for hundreds of thousands of cells in a grid. When we decoded the bitmasks in the view model for every single cell the program took way too long to load.

But when we created a value converter that decoded a single cell the program loaded in a fraction of the time and was just as responsive because the converter is only called when the user is looking at a particular cell (and it would only need to be called a max of thirty times any time the user shifted their view on the grid).

I don't know how MVVM complaint that solution was, but it cut the load time by 95%.


答:
As they say in Computer Science, "A level of indirection solves every problem".

You can view what you are developing as a Service Oriented Architecture. The front end application consumes the data retrieved from the back end application. Together, they form a service. (The front end application might run on your user's machine, if it is a thin client, e.g. made in JavaScript, or it might run on your machines, if it is a fat client that needs to perform complex computations or needs access to other resources that are not on your user's machine).

The main upside of this specific "building a level of indirection" is that you are abstracting away your core data model. Many different clients may retrieve it using the same API: a mobile app client, an administration site that is not accessible from the Internet, or an embedded client in a satellite circling the Moon. Also, you are free to exchange the way those core data are stored: to you, they are retrieved from a DB, but those clients do not care if next week the backend retrieves the data from a flat file or a NoSQL key-value store.

The main downside is that this may be overkill if you are building a simple web site that is used within an intranet.

As @RobertHarvey notes, your concern about performance is unfounded. Indeed, being able to exchange backends might allow you to scale to much more performant hardware or software without the clients noticing.

Other pros and cons: remember to have a very clear protocol between frontend and backend -- what was before an interface between packages has now become a remote API. Having an API call that returns the version, or the API capabilities, is useful. If the client calls go over the internet, remember to take into account they could be forged -- try to encrypt and sign them, as if they were mails coming to your central office from local branches.

Title: Is it a good idea to develop website that only has little access to DB? CRUD will be done by calling API provided by separate internal backend system

Body:
I'm going to start developing an application in near future. This application consists of :

Back-end system. This system provides API to be used by client. This
system connects to data store and 3rd party API.

Data Store : Can be relational or nosql data store.

Client : Client will be a website and mobile applications.

My reasons are below :

I want to prevent duplicated SQL query and 3rd party API call in
website application side. The application and website will be
developed by different developers. Only back end system
developers that can make query or call 3rd party API. All website
developers should only use API provided by back-end system

In my opinion, the website is also a client just like the mobile
application. If the mobile apps get their data from back-end system
API, why the website shouldn't be the same.

I heard twitter is using similar idea (I can be wrong though). Its
website is using twitter API just like their mobile application.

My primary concern to this architecture is that the website performance will be lower compared than If the website can make query or 3rd party API call directly.

Is there any other pros and cons that I should think about ?


问:
in multi-tenant systems what is the correct practice for segregating each tenants data from each other?
I am a first-time azure developer and I am taking over a single-tenant cloud system and have been tasked with converting the system to multi-tenant. What is the correct practice to separate each tenant's sql server data?

Its a data collection & reporting system. Each tenant will want to build and run their own custom reports on the data. So in multi-tenant, how are tenants prevented from seeing each others data?

答:
There is no one "correct" way to do anything in programming, even with a cloud-computing specific architecture such as Windows Azure.

A cursory search of the MSDN documentation reveals that Azure does in fact have some useful functionality to help you separate your client's data.  It appears as if you could decide to give each client their own SQL server instance, or you could instead use a common instance that you either partition directly or leverage some built-in functionality to partition for you.

Each of those solutions have their own pros and cons, which you will need to evaluation on your own.  Some conceptual guidance as to the selection:

If you use a separate instance for each client you will have built-in separation for your clients' data, but some reduced ability to examine data from multiple clients.  Microsoft may also charge more for the additional overhead.

If you use the same instance but partition the data manually in a single database, you'll have to manage and adjust the various keys and indexes yourself.  You obviously don't want to have a large client's 50,000,000 records slow down the query a smaller client's 500 records.

If you give each client a distinct schema or database in your single server instance, query management becomes easier, but you may need to worry about server-locks.  (On the plus side, a seperate-db-per-client may let you make the transition easier.)

If you use Microsoft's bulit-in partition tools, they may very well wind up doing exactly what you want them to do.  Or you may get 70% of the way throuh implementation and discover a need their tools do not cover, requiring you to abandon much of your work.  (Research and proper models are important when using anyone else's toolchain.)

As for the question of "how do you move data from single-instance to multi-instance", I imagine it would largely be a matter of constructing your new architecture and then importing the old data.  You'll want to know how to do that for future clients, anyway.


问:
Is it bad to have classes as properties of all other classes?
I've been making MVC programs for work (I'm an intern) and I feel like I'm doing a pretty good job at abstraction, single responsibility, etc. But I have this feeling about how I keep making objects properties of other objects and I'm not sure if it's a bad thing.

Example:

```<code>User
{
     String Username;
     Int32 UserID;
          .
          .
          .
     BusinessLogicClass Variable;
}

BusinessLogicClass
{
    AnotherClass Variable;
    AndAnother Variable2;
}

AnotherClass
{
     IThinkYoureGetting ThePoint;
}
</code>```

All my Classes are properties of the others in one massive hierarchy, It's kind of what the business logic calls for but I can't help but wonder if I should be trying to prevent something like this. So I end up effectively with one variable that I control the children of, but the classes are separate.

Is this something common? Is it bad? If it is bad, what should I do about it?

答:
No, that is not necessarily bad. That is object-oriented programming: objects contain other objects. Each one is responsible for its own piece of the program, which often means encapsulating other objects.

For example, a car contains a transmission. That could be a complex class containing a bunch of other objects such as gears, clutch plates, etc. which could be abstracted as classes.

In an MVC framework, you should be careful to keep different concerns separate. For example, a view should not generally contain model objects: normally, the view communicates requested model updates through events, decoupling the two layers. But a view object could definitely contain other view objects, for example a panel containing buttons, text boxes, etc.

Business logic that pertains to program flow is strictly a concern for the Controller layer. Business logic that pertains to updating the model is a little more open to debate. In your example, it may be appropriate to put limited business logic in the User model, but only if that logic pertains to tasks such as validation, updating dependent fields, etc. in other words, tasks that are tightly coupled to the data contained in the User. It would not be appropriate for the User to contain logic that interacts with the UI or program flow.


答:
Many people will immediately jump to the idea of having one database per customer.  In most cases thats unnecessary and creates additional problems of keeping the database structures in sync.  Of course, if you specifically want them to have different database structures (different table & column definitions) or you want to give them direct access to the database, then this is what you want to do.

The most typical method for multi-tenant systems is to logically separate the data in the database via an organization or customer ID.  If your data is more or less normalized, your database queries shouldn't become that much more complex, if you even have to change them.

Title: in multi-tenant systems what is the correct practice for segregating each tenants data from each other?

Body:
I am a first-time azure developer and I am taking over a single-tenant cloud system and have been tasked with converting the system to multi-tenant. What is the correct practice to separate each tenant's sql server data?

Its a data collection & reporting system. Each tenant will want to build and run their own custom reports on the data. So in multi-tenant, how are tenants prevented from seeing each others data?


答:
JSON serializer that deals with Circular References

Here is an example custom Jackson JSONSerializer that deals with circular references by serializing the first occurrence and storing a *reference to the first occurrence on all subsequent occurrences.

Dealing with Circular References when Serializing objects with Jackson

Relevant partial snippet from the above article:

```<code>private final Set<ObjectName> seen;

/**
 * Serialize an ObjectName with all its attributes or only its String representation if it is a circular reference.
 * @param on ObjectName to serialize
 * @param jgen JsonGenerator to build the output
 * @param provider SerializerProvider
 * @throws IOException
 * @throws JsonProcessingException
 */
@Override
public void serialize(@Nonnull final ObjectName on, @Nonnull final JsonGenerator jgen, @Nonnull final SerializerProvider provider) throws IOException, JsonProcessingException
{
    if (this.seen.contains(on))
    {
        jgen.writeString(on.toString());
    }
    else
    {
        this.seen.add(on);
        jgen.writeStartObject();
        final List<MBeanAttributeInfo> ais = this.getAttributeInfos(on);
        for (final MBeanAttributeInfo ai : ais)
        {
            final Object attribute = this.getAttribute(on, ai.getName());
            jgen.writeObjectField(ai.getName(), attribute);
        }
        jgen.writeEndObject();
    }
}
</code>```

Title: How to get around the Circular Reference issue with JSON and Entity

Body:
I have been experimenting with creating a website that leverages MVC with JSON for my presentation layer and Entity framework for data model/database. My Issue comes into play with serializing my Model objects into JSON.

I am using the code first method to create my database.  When doing the code first method a one to many relationship (parent/child) requires the child to have a reference back to the parent. (Example code my be a typo but you get the picture)

```<code>class parent
{
   public List<child> Children{get;set;}
   public int Id{get;set;}

}
class child
{
    public int ParentId{get;set;}
    [ForeignKey("ParentId")]
    public parent MyParent{get;set;}
    public string name{get;set;}
 }
</code>```

When returning a "parent" object via a JsonResult a circular reference error is thrown because "child" has a property of class parent.

I have tried the ScriptIgnore attribute but I lose the ability to look at the child objects. I will need to display information in a parent child view at some point.

I have tried to make base classes for both parent and child that do not have a circular reference. Unfortunately when I attempt to send the baseParent and baseChild these are read by the JSON Parser as their derived classes (I am pretty sure this concept is escaping me).

```<code>Base.baseParent basep = (Base.baseParent)parent;
return Json(basep, JsonRequestBehavior.AllowGet);
</code>```

The one solution I have come up with is to create "View" Models. I create simple versions of the database models that do not include the reference to the parent class. These view models each have method to return the Database Version and a constructor that takes the database model as a parameter (viewmodel.name = databasemodel.name).  This method seems forced although it works.

NOTE:I am posting here because I think this is more discussion worthy. I could leverage a different design pattern to over come this issue or it could be as simple as using a different attribute on my model.  In my searching I have not seen a good method to overcome this problem.

My end goal would be to have a nice MVC application that heavily leverages JSON for communicating with the server and displaying data.  While maintaining a consistant model across layers (or as best as I can come up with).

Body:
JSON serializer that deals with Circular References

Here is an example custom Jackson JSONSerializer that deals with circular references by serializing the first occurrence and storing a *reference to the first occurrence on all subsequent occurrences.

Dealing with Circular References when Serializing objects with Jackson

Relevant partial snippet from the above article:

private final Set<ObjectName> seen;

/**
 * Serialize an ObjectName with all its attributes or only its String representation if it is a circular reference.
 * @param on ObjectName to serialize
 * @param jgen JsonGenerator to build the output
 * @param provider SerializerProvider
 * @throws IOException
 * @throws JsonProcessingException
 */
@Override
public void serialize(@Nonnull final ObjectName on, @Nonnull final JsonGenerator jgen, @Nonnull final SerializerProvider provider) throws IOException, JsonProcessingException
{
    if (this.seen.contains(on))
    {
        jgen.writeString(on.toString());
    }
    else
    {
        this.seen.add(on);
        jgen.writeStartObject();
        final List<MBeanAttributeInfo> ais = this.getAttributeInfos(on);
        for (final MBeanAttributeInfo ai : ais)
        {
            final Object attribute = this.getAttribute(on, ai.getName());
            jgen.writeObjectField(ai.getName(), attribute);
        }
        jgen.writeEndObject();
    }
}


问:
Select custom output formats from database with SQL
I am planning to make a simple rest service application, and I am currently deciding the architecture. I have decided that I want to write the middle layer in multiple languages, so that it is easy to deploy/integrate with as wide a range of systems as possible.

Due to the necessity of porting the code to multiple languages, I want to keep the middle layer logic as simple as possible, to alleviate the coding effort involved.

I am planning to put as much code into SQL as possible. For example, traditionally, I might select some data from the database, then loop through the array of results, and process them further before sending back as a well formed response, like perhaps some HTML derived from the data.

However, given I want the middle layer to be as simple as possible, I would prefer to do all the processing as SQL. I have prepared sql statements that select from my results by concatenating and using group aggregates for repeating elements. It all seems to work fine, but I have a niggling doubt that I have left the reservation.

I am concerned that I have not seen this kind of thing done, so perhaps there is a good reason I have not thought of.

My question is...

Is it a bad idea to write complex formatting logic in SQL instead of application code?

In terms of...

performance

maintenance of code

limitations of language

anything else

n.b. I don't want to use PL_SQL or anything like that, I am only interested in using very basic SQL commands to achieve my formatting, as I want the database code to be portable between different databases too

答:
What you are describing is fairly common.  I wouldn't use SQL to generate actual HTML formatting presented to the user.  But there's nothing wrong with putting some of the heavy lifting onto the database server.  In fact, there's a school of thought that encourages that.  Examples might be date and number formatting, or even using stored procedures for geographic calculations.  You just have to be aware of any performance issues if your queries start to get too complex, and be ready to profile them if they show up.  A lot of programmers, especially those fairly new to databases, will greatly underestimate what kind of workload a well-tuned DBMS can handle.

Addendum: Personally, I prefer most logic to be in code because I'm a programmer and that's what I work with.  But there are cases when you want to rely on the SQL server more.  Yours might be one of them.


答:
```
In terms of...

1. performance
2. maintenance of code
3. limitations of language
4. anything else
```

I don't see any major problems unless your formatting functions get very complex. I suppose it could happen. I've done similar things and never had a problem with performance, but it could still happen.

Your formatting logic is in one central place. Not a bad thing.

You're limited to the functions your database provides. This may or may not be a problem.

This is not such a bad idea. It gives you the ability to have different clients get the same sort of results and it doesn't require you to write a separate formatting component.

I would recommend that if you do this, have one base view that presents the data, unformatted. That way, you can write different views on top of that view with different formatting logic, as you start to need differently formatted outputs (text, HTML, HTML for mobile, XML, etc...)

If you decide that all formatting in the database is not so great, you could change your database to format the output as XML, and then use an XSLT in your many clients to transform to your target format. In that case, all you need to do is run the XSLT in your client (provided that the many different languages can all handle XML and XSL).

Title: Select custom output formats from database with SQL

Body:
I am planning to make a simple rest service application, and I am currently deciding the architecture. I have decided that I want to write the middle layer in multiple languages, so that it is easy to deploy/integrate with as wide a range of systems as possible.

Due to the necessity of porting the code to multiple languages, I want to keep the middle layer logic as simple as possible, to alleviate the coding effort involved.

I am planning to put as much code into SQL as possible. For example, traditionally, I might select some data from the database, then loop through the array of results, and process them further before sending back as a well formed response, like perhaps some HTML derived from the data.

However, given I want the middle layer to be as simple as possible, I would prefer to do all the processing as SQL. I have prepared sql statements that select from my results by concatenating and using group aggregates for repeating elements. It all seems to work fine, but I have a niggling doubt that I have left the reservation.

I am concerned that I have not seen this kind of thing done, so perhaps there is a good reason I have not thought of.

My question is...

Is it a bad idea to write complex formatting logic in SQL instead of application code?

In terms of...

performance

maintenance of code

limitations of language

anything else

n.b. I don't want to use PL_SQL or anything like that, I am only interested in using very basic SQL commands to achieve my formatting, as I want the database code to be portable between different databases too

Body:
In terms of...

1. performance
2. maintenance of code
3. limitations of language
4. anything else

I don't see any major problems unless your formatting functions get very complex. I suppose it could happen. I've done similar things and never had a problem with performance, but it could still happen.

Your formatting logic is in one central place. Not a bad thing.

You're limited to the functions your database provides. This may or may not be a problem.

This is not such a bad idea. It gives you the ability to have different clients get the same sort of results and it doesn't require you to write a separate formatting component.

I would recommend that if you do this, have one base view that presents the data, unformatted. That way, you can write different views on top of that view with different formatting logic, as you start to need differently formatted outputs (text, HTML, HTML for mobile, XML, etc...)

If you decide that all formatting in the database is not so great, you could change your database to format the output as XML, and then use an XSLT in your many clients to transform to your target format. In that case, all you need to do is run the XSLT in your client (provided that the many different languages can all handle XML and XSL).


问:
Why are good programmers referred to as Ninjas?
How is a Ninja programmer defined? If it is just an experienced developer, then is there really no better way to describe that? Ninja sounds like a childish marketing ploy designed to attract developers with delusions of self-grandeur. Or am I missing something? In particular I want to know what qualities of a Ninja are desired in programmers that makes the comparison valid (besides the coolness factor)?

I did find this article which makes some good comparisons between Ninja characteristics and Agile development. However, I would like to hear from people who have used the word Ninja for hiring purposes and what their motivation was behind it.

Update: There were several good points raised on both sides of the argument. I've tried to summarize these in my blog post. I've chosen JB's answer as the accepted one because it summarizes all the valid reasons for making the comparison.

答:
One concept that martial arts experts and good programmers have in common is that economy of effort. Martial arts experts avoid wasted motion; good programmers avoid unnecessary code.

The concept of invisibility translates to transparency in library writing. A good library has an intuitive interface, and you can plug it in and not worry about it.

EDIT: I forgot the most important thing: both ninjas and good programmers are highly skilled as a result of training and practice.


问:
Is there a canonical book on x86 assembly?
There are lots of books on assembly. However, they usually deal with ISAs about which I don't care, such as MIPS or ARM. I don't deal with these architectures; there's no reason for me to try to learn them.

But x86 assembly books seem... nonexistent.

Let's say for example I'm trying to build a toy compiler generating Windows Portable Executable files.

Is there a book out there that's the de-facto standard for describing best practices, design methodologies, and other helpful information on x86 assembly? What about that book makes it special?

答:
Why not try the wikibook - http://en.wikibooks.org/wiki/X86_Assembly.  It gives a good introductory start to assembly language.

The hard bit about assembly is realising how simple it is, and that you need to stay with that simplicity.


答:
You wrote you want to

write complex formatting logic in SQL

but then

I don't want to use PL_SQL or anything like that, I am only interested in using very basic SQL commands to achieve my formatting as I want the database code to be portable between different databases too

Well, to my experience, you cannot have both - either you decide to do complex formatting logic in SQL, or you decide to use portable SQL - which means no complex formatting will be possible. The reason for this is that ANSI SQL supports only a small set of string formatting functions, far from beeing enough for implementing any real-world formatting requirements. However, the big database vendors like Oracle, MS, IBM or Sybase have added enough proprietary extensions, especially into the stored procedure dialects, to allow things like custom number or date formatting, HTML or XML generation etc.


答:
It's pretty much as you say - an attempt to imply coolness and eliteness (frequently among those who are neither) by making highly tenuous comparisons.

Personally I hate the phrase (along with "Rockstar Programmer" which makes we want to batter people to death - you can be a rockstar programmer when you've got a drug habit an alcohol problem and have trashed at least one car and one hotel room).

You're a programmer, if you have issues with being a programmer because you want to do something you think is cooler then deal with them (or quit to do something you think is cooler).  If you don't like the way others view programmers then understand that's their issue not yours.

You're certainly not going to change their minds with phrases that would make the average 12 year old think you were trying a bit hard to be impressive.

/rant

Edit:  To be clear, the rant is not aimed at the questioner...

Title: Why are good programmers referred to as Ninjas?

Body:
How is a Ninja programmer defined? If it is just an experienced developer, then is there really no better way to describe that? Ninja sounds like a childish marketing ploy designed to attract developers with delusions of self-grandeur. Or am I missing something? In particular I want to know what qualities of a Ninja are desired in programmers that makes the comparison valid (besides the coolness factor)?

I did find this article which makes some good comparisons between Ninja characteristics and Agile development. However, I would like to hear from people who have used the word Ninja for hiring purposes and what their motivation was behind it.

Update: There were several good points raised on both sides of the argument. I've tried to summarize these in my blog post. I've chosen JB's answer as the accepted one because it summarizes all the valid reasons for making the comparison.


问:
Suggest a best practice to create Constants class
There is a debate between my team members about the declaration of a Constants class. We are moving the constant variables into a separate class like below.

```<code>public class Constants
{
      public const string StateId = "ST";
      public const string CountryId = "CI";
}
</code>```

A few of my team members suggested that we declare the class as sealed to avoid overriding option, and a few are suggesting that we mark it as static to avoid instance creation of the Constant class.

However, I prefer to have it as Sealed with a static constructor, since it will help us to initialize the read-only variables in future need.
Please give us some advice on this.

答:
It's not totally clear what your question is, but if the values are truly constant, I don't see a problem with the simple option of:

```<code>    public static class LocationConstants
    {
        public const string StateId = "ST";
        public const string CountryId = "CI";
    }
</code>```

Using static in the class declaration signals your intention for the purpose of this class.

Marc Gravell describes some of the potential issues with constants in this Stack Overflow answer. Only you will know if these are a problem in your codebase, but if the values could ever change, use public static readonly instead of const, else any code referring to the constants will need to be rebuilt if the values change.

ContentLicense: CC BY-SA 4.0

Body:
It's not totally clear what your question is, but if the values are truly constant, I don't see a problem with the simple option of:

    public static class LocationConstants
    {
        public const string StateId = "ST";
        public const string CountryId = "CI";
    }

Using static in the class declaration signals your intention for the purpose of this class.

Marc Gravell describes some of the potential issues with constants in this Stack Overflow answer. Only you will know if these are a problem in your codebase, but if the values could ever change, use public static readonly instead of const, else any code referring to the constants will need to be rebuilt if the values change.


问:
Java - Use polymorphism or bounded type parameters
Suppose I have this class hierarchy...

```<code>public abstract class Animal {
    public abstract void eat();
    public abstract void talk();
}
class Dog extends Animal {
    @Override
    public void eat() {
    }

    @Override
    public void talk() {
    }
}

class Cat extends Animal {
    @Override
    public void eat() {
    }

    @Override
    public void talk() {
    }
}
</code>```

And then I have....

```<code>public static <T extends Animal> void addAnimal(T animal) {
    animal.eat();
    animal.talk();
}

public static void addAnimalPoly(Animal animal) {
    animal.eat();
    animal.talk();
}
</code>```

What's the difference when using bounded type parameters or polymorphism?

And when to use one or the other?

答:
These two examples are equivalent, and in fact will compile to the same bytecode.

There are two ways that adding a bounded generic type to a method as in your first example will do anything.

Passing the type parameter to another type

These two method signatures end up being the same in the byte code, but the compiler enforces type safety:

public static <T extends Animal> void addAnimals(Collection<T> animals)

public static void addAnimals(Collection<Animal> animals)

In the first case, only a Collection (or subtype) of Animal is allowed. In the second case, a Collection (or subtype) with a generic type of Animal or a subtype is allowed.

For example, the following is allowed in the first method but not the second:

```<code>List<Cat> cats = new ArrayList<Cat>();
cats.add(new Cat());
addAnimals(cats);
</code>```

The reason is that the second one only allows collections of animals, while the first allows collections of any object that is assignable to animal (i.e. subtypes). Note that if this list were a list of animals that happened to contain a cat, either method would accept it: the issue is the collection's generic specification, not what it actually contains.

Returning objects

The other time it matters is with returning objects. Let us assume the following method existed:

```<code>public static <T extends Animal> T feed(T animal) {
  animal.eat();
  return animal;
}
</code>```

You would be able to do the following with it:

```<code>Cat c1 = new Cat();
Cat c2 = feed(c1);
</code>```

While this is a contrived example, there are cases where it makes sense. Without generics, the method would have to return Animal and you would need to add type casting to make it work (which is what the compiler adds to the byte code anyway behind the scenes).

Body:
These two examples are equivalent, and in fact will compile to the same bytecode.

There are two ways that adding a bounded generic type to a method as in your first example will do anything.

Passing the type parameter to another type

These two method signatures end up being the same in the byte code, but the compiler enforces type safety:

public static <T extends Animal> void addAnimals(Collection<T> animals)

public static void addAnimals(Collection<Animal> animals)

In the first case, only a Collection (or subtype) of Animal is allowed. In the second case, a Collection (or subtype) with a generic type of Animal or a subtype is allowed.

For example, the following is allowed in the first method but not the second:

List<Cat> cats = new ArrayList<Cat>();
cats.add(new Cat());
addAnimals(cats);

The reason is that the second one only allows collections of animals, while the first allows collections of any object that is assignable to animal (i.e. subtypes). Note that if this list were a list of animals that happened to contain a cat, either method would accept it: the issue is the collection's generic specification, not what it actually contains.

Returning objects

The other time it matters is with returning objects. Let us assume the following method existed:

public static <T extends Animal> T feed(T animal) {
  animal.eat();
  return animal;
}

You would be able to do the following with it:

Cat c1 = new Cat();
Cat c2 = feed(c1);

While this is a contrived example, there are cases where it makes sense. Without generics, the method would have to return Animal and you would need to add type casting to make it work (which is what the compiler adds to the byte code anyway behind the scenes).


问:
Are "Stocks" a TDD/Unit testing anti pattern?
From Martin Fowler's Mocks Aren't Stubs he states that Stubs provide canned answers to calls made during the test while Mocks objects pre-programmed with expectations which form a specification of the calls they are expected to receive.

In addition several sources state that Stubs shouldn't fail tests, but Mock could.

So what about this:

```<code>$validator= $this->getMock('ValidatorService');

        // Set up the expectation for the isValid() method
        // to be called only once and with the string 'textToBeValidated'
        // as its parameter and returns true or false.
        $validator->expects($this->once())
                 ->method('isValid')
                 ->with($this->equalTo('textToBeValidated'))
                 ->will($this->returnValue(true));
</code>```

This came up in a code review in a project I'm working on and we called it a Stock (St ub - M ock). Why you ask?!

It set an expectation for isValid() to be called only once and with certain input like a Mock.

It returns a canned answer like a Stub.

I get a feeling that this is wrong, but what if we used a pure Stub only:

```<code> $validator->expects($this->any())  //<-- can't fail the test now
                     ->method('isValid')
                     ->will($this->returnValue(true));   //<-- canned answer
</code>```

I can't verify that the method isValid was called only once with the right parameters.

If the test passed I'm not sure that it passed for the right reason. Maybe isValid() was called twice and that caused it to pass.

So let's use a pure Mock instead:

```<code>$validator->expects($this->once())
                     ->method('isValid')
                     ->with($this->equalTo('textToBeValidated'))
</code>```

I can't verify that my function works correctly, because I only verified that call to isValid() was successful. Maybe there is a bug in the rest of my code using the ValidatorService.

I know some people will talk about state vs behavior verification, but the way I see it the only way to be sure that the test passes for the correct reason is to to use a Stock (i.e. verify the behavior and final state).

Of course the other option is to write 2 test for every test criteria. One using a Mock and an identical test using a Stub. However, that will result in a TestOverflow (a huge number of nearly identical tests).

What is the correct way to have a concrete test of a function using a dependency?

答:
Well, what you are describing as "Stock" is actually the definition of a Mock, at least in the book xUnit Patterns, which describes all the main types of test doubles.

The logic for the types of test doubles is that each inherits from the previous.

Consider a Dummy as the baseline, a NullObject implementation for any given interface.
The next type is the Stub, which returns some values.
Then there is the Spy, which returns values just as a Stub, but also records the details of its interactions.
Then comes the Mock, which by inheriting from the Spy, can decide whether to fail a test if the interaction is not valid for the given expectations.

By this logic, a Mock is a Spy, which is a Stub, which is a Dummy, which is a Test Double (the completely abstract concept).
There is also the concept of fakes, but they follow a different hierarchy.

You can see the details on the definition of each type here.