答:
Use dependency inversion where it makes sense.

One extreme counterexample is the "string" class included in many languages. It represents a primitive concept, essentially an array of characters. Assuming you could change this core class, it makes no sense to use DI here because you will never need to swap out the internal state with something else.

If you have a group of objects used internally in a module that are not exposed to other modules or reused anywhere, it is probably not worth the effort to use DI.

There are two places where DI should automatically be used in my opinion:

In modules designed for extension. If the entire purpose of a module is to extend it and change behavior, it makes perfect sense to bake DI in from the start.

In modules that you are refactoring for the purpose of code reuse. Perhaps you coded a class to do something, then realize later that with a refactor you can leverage that code elsewhere and there is a need to do so. That is a great candidate for DI and other extensibility changes.

The keys here are use it where it is needed because it will introduce extra complexity, and make sure you measure that need either through technical requirements (point one) or quantitative code review (point two).

DI is a great tool, but just like any* tool, it can be overused or misused.

* Exception to the above rule: a reciprocating saw is the perfect tool for any job. If it does not fix your problem, it will remove it. Permanently.

Title: When NOT to apply the Dependency Inversion Principle?

Body:
I am currently trying to figure out SOLID. So the Dependency Inversion Principle means that any two classes should communicate via interfaces, not directly. Example: If class A has a method, that expects a pointer to an object of type class B, then this method should actually expect an object of type abstract base class of B. This is helps for Open/Close as well.

Provided that I understood that correctly, my question would be is it a good practice to apply this to all class interactions or should I try to think in terms of layers?

The reason I am skeptical is because we are paying some price for following this principle. Say, I need to implement feature Z. After analysis, I conclude that feature Z consists of functionality A, B and C. I create a facade class Z, that, through interfaces, uses classes A, B and C. I begin coding the implementation and at some point I realize that task Z actually consists of functionality A, B and D. Now I need to scrap the C interface, the C class prototype and write separate D interface and class. Without interfaces, only the class would've needed to be replaced.

In other words, to change something, I need to change 1. the caller 2. the interface 3. the declaration 4. the implementation. In a python directly coupled implementation, I would need to change only the implementation.


问:
When NOT to apply the Dependency Inversion Principle?
I am currently trying to figure out SOLID. So the Dependency Inversion Principle means that any two classes should communicate via interfaces, not directly. Example: If class A has a method, that expects a pointer to an object of type class B, then this method should actually expect an object of type abstract base class of B. This is helps for Open/Close as well.

Provided that I understood that correctly, my question would be is it a good practice to apply this to all class interactions or should I try to think in terms of layers?

The reason I am skeptical is because we are paying some price for following this principle. Say, I need to implement feature Z. After analysis, I conclude that feature Z consists of functionality A, B and C. I create a facade class Z, that, through interfaces, uses classes A, B and C. I begin coding the implementation and at some point I realize that task Z actually consists of functionality A, B and D. Now I need to scrap the C interface, the C class prototype and write separate D interface and class. Without interfaces, only the class would've needed to be replaced.

In other words, to change something, I need to change 1. the caller 2. the interface 3. the declaration 4. the implementation. In a python directly coupled implementation, I would need to change only the implementation.

答:
In many cartoons or other media, the forces of good and evil are often illustrated by an angel and a demon sitting on the character's shoulders. In our story here, instead of good and evil, we have SOLID on one shoulder, and YAGNI (You ain't gonna need it!) sitting on the other.

SOLID principles taken to the max are best suited for huge, complex, ultra-configurable enterprisey systems.  For smaller, or more specific systems, it is not appropriate to make everything ridiculously flexible, as the time you spend abstracting things will not prove to be a benefit.

Passing interfaces instead of concrete classes sometimes means for example that you can easily swap reading from a file for a a network stream. However, for a great amount of software projects, that kind of flexibility is just not ever going to be needed, and you might as well just pass concrete file classes and call it a day and spare your brain cells.

Part of the art of software development is having a good sense of what is likely to change as time goes on, and what isn't. For the stuff that is likely to change, use the interfaces and other SOLID concepts. For the stuff that won't, use YAGNI and just pass concrete types, forget the factory classes, forget all the runtime hooking up and configuration, etc, and forget a lot of the SOLID abstractions. In my experience, the YAGNI approach has proven to be correct far more often than it is not.

ContentLicense: CC BY-SA 3.0


问:
What is Quality Assurance's role in a company that practices Continuous Delivery?
I was listening to this podcast on Continuous Delivery and Jez Humble briefly talked about QA's role, but I didn't really get a "big picture" idea of they're doing on a day to day basis.  How is their job description changed when a company practices Continuous Delivery?</p>

答:
Ideally, your QA team's primary responsibility is in maintaining relevant acceptance tests. That means they spend most of their time coming up with clever ways to break the application, codifying those cases, and periodically pruning away obsolete or less helpful cases.

Beyond that, there are things that an automated suite can't test, which require an experienced QA and/or editorial and/or UX person's eye:

Does the UI look nice?

Is the UI/UX intuitive?

Are the graphics on the page helpful or distracting?

Is the language in paragraph X relevant and easy to ready?

Beyond that, it can be difficult to codify a singular automated test suite for functionality that crosses application or platform boundaries. For instance, a test runner may be designed to automate browser interactions, but not native applications. In that case, if the related native applications are pretty slender on functionality, it may be simpler to have a QA person spend 10 or 20 minutes to ensure the integration still functions.


问:
Is it worth even checking to see if Guid.NewGuid() is Guid.Empty?
In one of the projects I'm working on the following pattern is seen on a fairly regular basis:

```<code>var guid = Guid.NewGuid().ToString();
while (guid == Guid.Empty.ToString())
{
    guid = Guid.NewGuid().ToString();
}
</code>```

While I understand that a a GUID is not guaranteed to be unique and as per the MSDN documentation a generated GUID may be zero, is this a practical consideration actually worth sending cycles testing for both in the computational sense and in terms of developer time thinking about it?

答:
I would suggest it's not worth checking for Guid.Empty. The docs for Guid.NewGuid for some reason mention that

The chance that the value of the new Guid will be all zeros or equal to any other Guid is very low.

Guid.NewGuid is a wrapper for the Win32 API CoCreateGuid, which makes no mention of returning all zeroes.

Raymond Chen goes further, suggesting that

no valid implementation of CoCreateGuid can generate GUID_NULL

So, no, I wouldn't worry about it. I wont' guess as to why the Guid.NewGuid docs even mention it.

ContentLicense: CC BY-SA 4.0


问:
How to unit test that the correct implementation of an interface is used?
I have this problem with unit testing for years. Unit testing should test isolated units, that is, if we use interface/implementation vocabulary, it should test concrete implementation classes. Fine, let's do it. In a code that is the client of the interface, one should mock the interface to suit the tests. That's OK, let us do it where possible, too.

But then, in the productions code, there is some place where the actual implementation class is instantiated and used as the-instance-that-implements the interface. It may be factory methods, it can be somewhere else.

I have the problem how to actually test this glue between those two, correctly tested in isolation, layers. Using variants of instance of is brittle - not to say, the creator of the actual instance may be "smart" and choose different implementation based on circumstances. Even if not, it creates that instance using some configuration around.

So far, I either do not unit test in strict manner (so I do not do new Foo(directa, directb), but createApp(indirectA, indirectB).getFoo() instead), but that may not be proper unit testing. That does not test all the implementations, that test those-implementations-app-uses. Other approach I may see is to make tests of Foo implementation parametric, having a factory method makeFoo(a,b) and create subclasses for each implementations as well as one which creates those instances via an actual app.

Do you know of a good way on how to approach this?

In other words, the question may be simply "How to (unit) test glue code?"

答:
The way you test glue code is by running an integration test.

The purpose of integration testing is to verify functional, performance, and reliability requirements placed on major design items. These "design items", i.e. assemblages (or groups of units), are exercised through their interfaces using black box testing, success and error cases being simulated via appropriate parameter and data inputs.

Simulated usage of shared data areas and inter-process communication is tested and individual subsystems are exercised through their input interface. Test cases are constructed to test whether all the components within assemblages interact correctly, for example across procedure calls or process activations, and this is done after testing individual modules, i.e. unit testing.


答: There are two ways of writing unit tests.  Most people think there's only one way.  If you use sociable tests, you can test the glue as part of the test.

Title: How to unit test that the correct implementation of an interface is used?

Body:
I have this problem with unit testing for years. Unit testing should test isolated units, that is, if we use interface/implementation vocabulary, it should test concrete implementation classes. Fine, let's do it. In a code that is the client of the interface, one should mock the interface to suit the tests. That's OK, let us do it where possible, too.

But then, in the productions code, there is some place where the actual implementation class is instantiated and used as the-instance-that-implements the interface. It may be factory methods, it can be somewhere else.

I have the problem how to actually test this glue between those two, correctly tested in isolation, layers. Using variants of instance of is brittle - not to say, the creator of the actual instance may be "smart" and choose different implementation based on circumstances. Even if not, it creates that instance using some configuration around.

So far, I either do not unit test in strict manner (so I do not do new Foo(directa, directb), but createApp(indirectA, indirectB).getFoo() instead), but that may not be proper unit testing. That does not test all the implementations, that test those-implementations-app-uses. Other approach I may see is to make tests of Foo implementation parametric, having a factory method makeFoo(a,b) and create subclasses for each implementations as well as one which creates those instances via an actual app.

Do you know of a good way on how to approach this?

In other words, the question may be simply "How to (unit) test glue code?"


答:
If you find Guid.NewGuid() == Guid.Empty you have won the hardest lottery on earth. Don't bother with any uniqueness or collision checking. Not having to do that is what guids are for. I will spare you the math, it's everywhere on the web.

Also, Windows guids always have one "digit" equal to 4. There is some structure to guids.

That code snippet you posted looks like one dev forgot to initialize a Guid variable and found it to be Guid.Empty. He mistakenly identified Guid.NewGuid() as the cause. Now he will forever superstitiously believe in this.

In any case this is the wrong question to ask. I'm sure your code does not only depend on not ever drawing Guid.Empty but also on uniqueness. That while loop does not enforce uniqueness. Guids are there to produce a unique value without coordination. That is their use case.

Title: Is it worth even checking to see if Guid.NewGuid() is Guid.Empty?

Body:
In one of the projects I'm working on the following pattern is seen on a fairly regular basis:

```<code>var guid = Guid.NewGuid().ToString();
while (guid == Guid.Empty.ToString())
{
    guid = Guid.NewGuid().ToString();
}
</code>```

While I understand that a a GUID is not guaranteed to be unique and as per the MSDN documentation a generated GUID may be zero, is this a practical consideration actually worth sending cycles testing for both in the computational sense and in terms of developer time thinking about it?


答:
But then, in the productions code, there is some place where the actual implementation class is instantiated and used as the-instance-that-implements the interface. It may be factory methods, it can be somewhere else.

How do you test that?

There are three scenarios here.

The first is that you don't care about the instance used. Some code internally uses some concrete instance to do its work and that code is already "unit" sized. That's great. Ignore the implementation detail and test the inputs/outputs.

The second is some sort of factory. For some given inputs, you get the proper output. That is an easy to test unit like any other unit - provide some inputs (tending towards boundary conditions) and make sure the output is correct. Usually instanceof is sufficient, but you could check behavior of the resultant object if it's simple/obvious/unchanging.

The third is configuration sort of code. It might be configuration itself, or it might be hardcoded inputs to more general code. In almost all of my apps for example, all main does is specify concrete instances and glue them together. I do not unit test that code, and I do not recommend you do either.

Why? Because it provides no benefit. Unit testing exists to provide early, clear signs that something is wrong. In my experience, if you screwed up your concrete instantiation (and have a relatively sane architecture) then simply running the app provides a quick, clear and cheap indicator if things are configured correctly or not.


问:
Assigning default values from environment variable in Node.js
When attempting to set default values for parameters that may exist in environment variables in JavaScript, I often see this pattern:

```<code>var lag;

try {
    lag = process.env.THROTTLE_LAG;
}
catch ( e ) {
    lag = 100;
}
</code>```

I don't like it because, while it follows a common JavaScript pattern of declaring an empty variable for the purpose of later conditionally assigning it a value, the pattern of using try/catch as a logical branching stratagem seems kludgey. Examining technical factors, it tends to perform sub-optimally when compared with other branching strategies. Examining human factors, colleagues have argued that it lacks readability. Of course, opinions differ.

This shorter solution uses an empty catch block, which makes me cringe.

```<code>var lag = 100;

try {
    lag = process.env.THROTTLE_LAG;
}
catch ( e ) {}
</code>```

(I'm open to the idea that my cringe is reflexive and not reflective of a real problem.)

答:
Using try/catch for logical branching is not recommended in general, but there are legitimate uses. One example, when you have to query a third party API, and there is no other way to access it. To keep you code more readable, you could encapsulate the try/catch in single, isolated function like

```<code> function GetSomethingFromThirdPartyApi(parameter, defaultvalue)
 {
     try
     {
         return ThirdPartyApiCall(parameter);
     }
     catch(e)
     {
         return defaultvalue;
     }
 }
</code>```

In my eyes this function is very clear and concise.

So I recommend to avoid cargo cults like "I have heard that [xyz] is bad, thus I never want to use it" and stay pragmatic - when cleaner alternatives cause more headaches than they prevent, use what works, dogmas don't solve problems.

However, in the given example, you can indeed solve your problem without the use of try catch, by a function like

```<code>function GetEnvironmentVar(varname, defaultvalue)
{
    var result = process.env[varname];
    if(result!=undefined)
        return result;
    else
        return defaultvalue;
}
</code>```

now you can use it like

```<code> var lag = GetEnvironmentVar("THROTTLE_LAG",100);
</code>```

This is probably what you are looking for.

OwnerDisplayName: msanford

Body:
Using try/catch for logical branching is not recommended in general, but there are legitimate uses. One example, when you have to query a third party API, and there is no other way to access it. To keep you code more readable, you could encapsulate the try/catch in single, isolated function like

 function GetSomethingFromThirdPartyApi(parameter, defaultvalue)
 {
     try
     {
         return ThirdPartyApiCall(parameter);
     }
     catch(e)
     {
         return defaultvalue;
     }
 }

In my eyes this function is very clear and concise.

So I recommend to avoid cargo cults like "I have heard that [xyz] is bad, thus I never want to use it" and stay pragmatic - when cleaner alternatives cause more headaches than they prevent, use what works, dogmas don't solve problems.

However, in the given example, you can indeed solve your problem without the use of try catch, by a function like

function GetEnvironmentVar(varname, defaultvalue)
{
    var result = process.env[varname];
    if(result!=undefined)
        return result;
    else
        return defaultvalue;
}

now you can use it like

 var lag = GetEnvironmentVar("THROTTLE_LAG",100);

This is probably what you are looking for.


问:
Restrictions of using a CC BY-NC resource in software?
Lets say there is a resource published under the CC BY-NC license that is not itself in any way related to software, but rather a database of sorts for example. As I understand, this places restrictions on any publications or derivatives of this resource, but it's quite unclear to me how this can apply to software.

Simply put, if I were to use this resource in a software product (as in, make it crucial to the inner workings of it)

Would I be allowed to publish this software product as open source on GitHub (since this would, in theory, be a redistribution)? If so, would my choices in standard open source licenses be limited due to the CC BY-NC license applied to the data?

If the software itself was available for free, but contained paid ads, would this count as commercial use and thus be prohibited due to BY-NC?

Are there other issues that could arise?

答:
CC BY-NC prohibits commercial use of the library. This conflicts with the definition of open source and so, no, the aggregate software would not be open source.

Additionally, the definition of 'non commercial' is not well defined.  This is the realm of lawyers. Is a non-profit with advertisements (or a donation button) on the page backed by something with an NC license in violation of that license? That's a good question - for a lawyer.

When one starts asking about the legal restrictions for something, that is again the realm of the lawyers.

All a person reasonably familiar with open source licenses can say about CC BY-NC is that it isn't open source or compatible with open source licenses.


问:
Is it wise for a high level developer to spend time studying assembly?
It is clear that the knowledge of low level stuff is very important in our work.

But in a situation where you're already developing commercial software on a high level, and when you already have a chosen direction but don't have any assembly skill, isn't it more reasonable to focus on studying stuff related to your direction? Or is there a reason you should spend some time to learn the low-level basics anyway?

When is it too late, and when it is not? And if it is not too late, then how would one go about learning optimally (in the sense of not spending excessive time to get some depth and understanding)?

答:
Can't believe no one has mentioned debugging...

I haven't written a line of assembly code in many years now. But I read it reasonably often. High-level debugging is great when you have the source and symbol information, but when your fancy library is throwing an unhandled exception on customer machines, it's too late to require that to be included in the license...

But I can still open up the disassembler and see what your high-level logic eventually ended up doing, trace bad data back to its origin, find out who changed the FPU control register...

This has saved my bacon more often than I care to think about. And it's never too late to learn - there are plenty of great references and tutorials out on the 'Net, and just about any program running on your machine can provide a hands-on environment.

ContentLicense: CC BY-SA 2.5


问:
Database object mapping, good practices
I think I've understood the basic idea behind object mapping but there is one gap in my knowledge base that I hope to fill now. First let me tell you what I understand out of the whole thing.

I have my database tables alright, and for every table I have a separate class. Each instance of each class represents a row of the table, for example table users - id, name, password would be represented like

```<code>class User {
    protected $id;
    protected $name;
    protected $password;
}
</code>```

Which would have methods like setName, setPassword, create, save, getById and so on. This all makes a great lot of sense to me and brings a very good look to the code as well as maintainability, it's just awesome, I've fallen in love with this model of data handling ever since I discovered it.

However, now wo the thing that is not very clear to me. If I have a table that is a connecting table, sorry don't really know what the term for that is - a table which shows connection between other tables, how do I manipulate that table? Let me give an example again because I'm not very good with explanations. Say I add a table where users can add their contacts, just plain and simple, nothing fancy for the example. In the table contacts users can add other users like bookmarks. Since that table wouldn't have a PK, or would probably have a complex PK, It doesn't really fit very well in the above method - 1 row = 1 instance, because there is just no way to set up the "contact" object in the pattern shown above. Yeah I could probably do something like

```<code>class Contact {
    protected $forUser;
    protected $contact;
}
</code>```

Where forUser would be the user who's contact that is and contact would be the actual user the contact contains, but as I said it is just not looking very well and doesn't make perfect sense for me.

The method I've come up with is to have additional methods in the initial class itself that manage the "connecting" tables, something like

```<code>class User {
    ...

    public function addContact(\User $user){
        ...
    }
}
</code>```

Could you give me some guidance and tell me what are good and bad practices on this matter?

答:
The connecting table that you speak of is called a junction table.

Using the Wikipedia example, they have 3 tables defined.

```<code>User
----
User ID
User Login
User Password
User Name

Permission
----------
Permission ID
Permission Description

UserPermission
--------------
User ID
Permission ID
</code>```

Now, you can map these 3 tables to PHP classes.

It would probably be more intuitive to create a class with a user and a list of permissions.

For a different application, you might create a class with a permission and a list of users.

In a relational database, you have to have junction tables for a many to many relationship.  You don't have to create a PHP class for the junction table.

Title: Database object mapping, good practices

Body:
The connecting table that you speak of is called a junction table.

Using the Wikipedia example, they have 3 tables defined.

User
----
User ID
User Login
User Password
User Name

Permission
----------
Permission ID
Permission Description

UserPermission
--------------
User ID
Permission ID

Now, you can map these 3 tables to PHP classes.

It would probably be more intuitive to create a class with a user and a list of permissions.

For a different application, you might create a class with a permission and a list of users.

In a relational database, you have to have junction tables for a many to many relationship.  You don't have to create a PHP class for the junction table.


答:
If you always invert your dependencies, then all your dependencies are upside down. Which means that if you started with messy code with a knot of dependencies, that's what you still (really) have, just inverted. Which is where you get the problem that every change to an implementation needs to change its interface too.

The point of dependency inversion is you selectively invert the dependencies that are making things tangles. The ones that should go from A to B to C still do so, it the ones that were going from C to A that now go from A to C.

The result should be a dependency graph that is free of cycles - a DAG. There are various tools that will check this property, and draw the graph.

For a fuller explanation, see this article:

The essence of applying the Dependency Inversion Principle correctly is this:

Split the code/service/… you depend on into an interface and implementation.
The interface restructures the dependency in the jargon of the code using it, the implementation implements it in terms of its underlying techniques.

The implementation remains where it is. But the interface has a different function now (and uses a different jargon/language), describing something the using code can do. Move it to that package.
By not placing the interface and implementation in the same package, the (direction of the) dependency is inverted from user→implementation to implementation→user.


问:
Does current JIT optimize generated machine codes for branch prediction based on runtime statistics?
Some JVMs would compile Java byte code into native machine code. We know that there are lots of optimizations we could apply for that. Recently, I also learn that a branch operation may block the CPU and affect the performance significantly, if a CPU makes a wrong prediction. </p>

<p>Does anyone know if any JVM would generate machine codes easier for CPU making right prediction based on runtime statistics collected? </p>

答:
No, HotSpot does not add hints to the hardware branch predictor as stated on the OpenJDK mailing list:

It's been considered, and decided against.  The platforms which openjdk
  currently targets all have decent to spectacular hardware branch
  prediction.  Those that didn't, such as Niagara 1, ignored prediction
  bits.  Conclusion is that it's not worth complicating the code with, as
  David says, 'magic macros'.


问:
The recommended Way to exit a Loop
Occasionally - but recurringly - I face the following loop pattern problem:

```<code>CodeSnippet1
DO WHILE LoopCondition   //LoopCondition depends on some pre-calculation from CodeSnippet1
    CodeSnippet2         //CodeSnippet2 relies on LoopConditon=true
    CodeSnippet1
LOOP
</code>```

The problem I see here is the code duplication of CodeSnippet1.

At the first glance, it seems like I should move the condition to the end:

```<code>DO
    CodeSnippet1
    CodeSnippet2
LOOP WHILE LoopCondition
</code>```

This won't work since CodeSnippet2 assumes LoopCondition=true. The next try would be:

```<code>DO
    CodeSnippet1
    IF LoopCondition THEN CodeSnippet2
LOOP WHILE LoopCondition
</code>```

Again far from elegant.

In C-like programming languages, one can do the following:

```<code>while(complicated-expression-containing-CodeSnippet1-and-LoopCondition) {
    CodeSnippet2
}
</code>```

But

a) this can get difficult to understand and

b) not every programming language can perform arbitrary calculations, especially variable assigments, during evaluation of some loop condition.

Recently, I came up with the following way:

```<code>DO //endless loop
    CodeSnippet1

    IF NOT LoopCondition THEN EXIT LOOP

    CodeSnippet2
LOOP
</code>```

This tends to lead structured programming with loops ad absurdum / reminds me a bit of GoTo programming style.

My Question:

Are there (more or less) objective reasons to prefer one of the mentioned loop programming styles over the others?

EDIT:

I know in many occasions CodeSnippet1 together with LoopCondition can be encapsulated in a function returning the loop condition, and we're done. I agree with that. But this does not hold in general. Above in b) I tried to hint at "variable assignments". Here in detail:

My favourite minimal but real-world example: Using a BufferedReader in Java:

```<code>line = bufferedReader.readLine();
while(line != null) {
    //CodeSnippet2
    line = bufferedReader.readLine();
}
</code>```

vs.

```<code>while((line = bufferedReader.readLine()) != null) {
    //CodeSnippet2
}
</code>```

Both variants are not satisfying. Factoring out (line = bufferedReader.readLine()) != null into a function that returns a boolean has one new problem: How to retrieve line? Using a global variable / class member just for this purpose?

答:
Congratulations! You've just reinvented Ada's looping structure. Jean Ichbiah probably reinvented someone else's prior art.

This is de facto possible in a lot of languages, where you can create endless loops with programmed exits. For example, in Python:

```<code>while True:
    do_stuff()
    if not loop_continues:
       break
    do_more_stuff()
</code>```

The reason so many languages have a test-at-top loop (while), a test-at-bottom loop (do until), and a counting/iterating loop (for) is that those are the most common patterns, and most likely to be needed. But with modern break ("get me out of this loop!") and continue ("we're ready for the next iteration!") options, there really aren't nearly as many needs for bespoke loop syntax to cover all the options. Python, e.g., does with just for and while variants.

The early-exit (break) and early-continue (continue) operations are well-structured, with only a few well-designed places they can take you (namely to the bottom/exit of the loop, or to the top of the loop). They are not the "I may jump to pretty much any line!" wildcards of the olden GOTO days, and so they can get you (and whatever optimizer your compiler toolchain is using) into many fewer sticky situations.

Given that we now have (pretty much irrespective of language used) good structured means to test and manage loop behavior, I'm unclear why anyone would have a strong preference. Test where it makes sense for the algorithm involved: At the top, at the bottom, or some place in between.

Title: The recommended Way to exit a Loop

Body:
Congratulations! You've just reinvented Ada's looping structure. Jean Ichbiah probably reinvented someone else's prior art.

This is de facto possible in a lot of languages, where you can create endless loops with programmed exits. For example, in Python:

while True:
    do_stuff()
    if not loop_continues:
       break
    do_more_stuff()

The reason so many languages have a test-at-top loop (while), a test-at-bottom loop (do until), and a counting/iterating loop (for) is that those are the most common patterns, and most likely to be needed. But with modern break ("get me out of this loop!") and continue ("we're ready for the next iteration!") options, there really aren't nearly as many needs for bespoke loop syntax to cover all the options. Python, e.g., does with just for and while variants.

The early-exit (break) and early-continue (continue) operations are well-structured, with only a few well-designed places they can take you (namely to the bottom/exit of the loop, or to the top of the loop). They are not the "I may jump to pretty much any line!" wildcards of the olden GOTO days, and so they can get you (and whatever optimizer your compiler toolchain is using) into many fewer sticky situations.

Given that we now have (pretty much irrespective of language used) good structured means to test and manage loop behavior, I'm unclear why anyone would have a strong preference. Test where it makes sense for the algorithm involved: At the top, at the bottom, or some place in between.


答:
Because also of dovals comment:

Wrap codesnippet1 and the loopcondition in a function, because apparently the loopcondition is set by codesnippet1. Which then returns the loopcondition then you get:

```<code>DO WHILE CodeSnippet1AndLoopConditionFunction
  CodeSnippet2
LOOP
</code>```

Title: The recommended Way to exit a Loop

Body:
Occasionally - but recurringly - I face the following loop pattern problem:

```<code>CodeSnippet1
DO WHILE LoopCondition   //LoopCondition depends on some pre-calculation from CodeSnippet1
    CodeSnippet2         //CodeSnippet2 relies on LoopConditon=true
    CodeSnippet1
LOOP
</code>```

The problem I see here is the code duplication of CodeSnippet1.

At the first glance, it seems like I should move the condition to the end:

```<code>DO
    CodeSnippet1
    CodeSnippet2
LOOP WHILE LoopCondition
</code>```

This won't work since CodeSnippet2 assumes LoopCondition=true. The next try would be:

```<code>DO
    CodeSnippet1
    IF LoopCondition THEN CodeSnippet2
LOOP WHILE LoopCondition
</code>```

Again far from elegant.

In C-like programming languages, one can do the following:

```<code>while(complicated-expression-containing-CodeSnippet1-and-LoopCondition) {
    CodeSnippet2
}
</code>```

But

a) this can get difficult to understand and

b) not every programming language can perform arbitrary calculations, especially variable assigments, during evaluation of some loop condition.

Recently, I came up with the following way:

```<code>DO //endless loop
    CodeSnippet1

    IF NOT LoopCondition THEN EXIT LOOP

    CodeSnippet2
LOOP
</code>```

This tends to lead structured programming with loops ad absurdum / reminds me a bit of GoTo programming style.

My Question:

Are there (more or less) objective reasons to prefer one of the mentioned loop programming styles over the others?

EDIT:

I know in many occasions CodeSnippet1 together with LoopCondition can be encapsulated in a function returning the loop condition, and we're done. I agree with that. But this does not hold in general. Above in b) I tried to hint at "variable assignments". Here in detail:

My favourite minimal but real-world example: Using a BufferedReader in Java:

```<code>line = bufferedReader.readLine();
while(line != null) {
    //CodeSnippet2
    line = bufferedReader.readLine();
}
</code>```

vs.

```<code>while((line = bufferedReader.readLine()) != null) {
    //CodeSnippet2
}
</code>```

Both variants are not satisfying. Factoring out (line = bufferedReader.readLine()) != null into a function that returns a boolean has one new problem: How to retrieve line? Using a global variable / class member just for this purpose?

Body:
Because also of dovals comment:

Wrap codesnippet1 and the loopcondition in a function, because apparently the loopcondition is set by codesnippet1. Which then returns the loopcondition then you get:

DO WHILE CodeSnippet1AndLoopConditionFunction
  CodeSnippet2
LOOP


问:
What was the worst piece of code you fixed that you are proud of?
I have had a few that I am proud of and some of them were written by myself few years ago. It doesn't have to be necessarily buggy, just bad code. </p>

答:
I don't know about being proud of the fix because it was so obvious, but the most horrible code I remember fixing was this.

```<code>if (userName=="John O'Reily") { userName= "John O''Reily";}
if (userName=="Stacy O'Neil") { userName= "Stacy O''Neil";}
if (userName=="Finnegan O'Connor") { userName= "Finnegan O''Connor";}
...
someSQL = "SELECT * from Users where UserName='" + userName + "'";
</code>```

Apparently the previous developer just kept adding new lines every time a new (usually Irish) user started getting errors in the application.

I'll leave it as an exercise for the class as to how it was fixed.

Body:
I don't know about being proud of the fix because it was so obvious, but the most horrible code I remember fixing was this.

if (userName=="John O'Reily") { userName= "John O''Reily";}
if (userName=="Stacy O'Neil") { userName= "Stacy O''Neil";}
if (userName=="Finnegan O'Connor") { userName= "Finnegan O''Connor";}
...
someSQL = "SELECT * from Users where UserName='" + userName + "'";

Apparently the previous developer just kept adding new lines every time a new (usually Irish) user started getting errors in the application.

I'll leave it as an exercise for the class as to how it was fixed.


问:
Return values and exceptions
I wrote simple function that returns a string depending on which condition is TRUE. Here is my code:

```<code>private String getMyString() {
    if(!mStrigMember.isEmpty()) {
        return mStrigMember;
    }
    return Function_that_throws_Exception_return_String();
}
</code>```

Because of the Function_that_throws_Exception_return_String I was obliged to add a try catch block to end up with:

```<code>private String getMyString() {
    String TempString = "";
    if(!mStrigMember.isEmpty()) {
        return mStrigMember;
    }
    try {
        TempString = Function_that_throws_Exception_return_String();
    } catch (Exception e) { }
    return TempString ;
}
</code>```

But it's not elegant (TempString is created but not used when the first branch was TRUE). This is my opinion even though it's compiling and working properly.

Any suggestions?

答:
I usually do the following unless there is a good reason not to. The member check acts as a "Guardian Clause" and the need for temp variables disappears if you are returning a constant in the case of an exception.

```<code>private String getMyString() {
    if (!mStrigMember.isEmpty()) return mStrigMember;

    try {
        return Function_that_throws_Exception_return_String();

    } catch (Exception e) {
        return "";
    }
}
</code>```

It would be better, if possible, to catch a more specific Exception subclass instead of Exception as Exception includes a whole swag load of runtime exceptions i.e. everything Throwable that is not an Error, which is most likely not what you actually want.

Title: Return values and exceptions

Body:
I usually do the following unless there is a good reason not to. The member check acts as a "Guardian Clause" and the need for temp variables disappears if you are returning a constant in the case of an exception.

private String getMyString() {
    if (!mStrigMember.isEmpty()) return mStrigMember;

    try {
        return Function_that_throws_Exception_return_String();

    } catch (Exception e) {
        return "";
    }
}

It would be better, if possible, to catch a more specific Exception subclass instead of Exception as Exception includes a whole swag load of runtime exceptions i.e. everything Throwable that is not an Error, which is most likely not what you actually want.


答:
It seems to me that the original question is missing part of the point of the DIP.

The reason I am skeptical is because we are paying some price for following this principle. Say, I need to implement feature Z. After analysis, I conclude that feature Z consists of functionality A, B and C. I create a fascade class Z, that, through interfaces, uses classes A, B and C. I begin coding the implementation and at some point I realize that task Z actually consists of functionality A, B and D. Now I need to scrap the C interface, the C class prototype and write separate D interface and class. Without interfaces, only the class would wave needed to be replaced.

To truly take advantage of the DIP, you would create class Z first, and have it call the functionality of classes A, B and C (which are not yet developed).  This gives you the API for classes A, B and C.  Then you go and create classes A, B and C and fill in the details.  You effectively should be creating the abstractions you need as you're creating class Z, based entirely on what class Z needs.  You can even write tests around class Z before classes A, B or C are even written.

Remember that the DIP says that "High-level modules should not depend on low-level modules. Both should depend on abstractions."

Once you have worked out what class Z needs and the way in which it wants to get what it needs, you can then fill in the details.  Sure, sometimes changes will need to be made to class Z, but 99% of the time this won't be the case.

There will never be a class D because you worked out that Z needs A, B and C before they were written.  A change in requirements is a different story altogether.


答:
If you are going to check the GUID against the zero GUID, you by the same logic also need to do due diligence of checking it against all other GUIDs in your application (as the probability of getting a zero should be the same as the probability of getting any other GUID in your app*). You need to do this to prove the axiom you are acting under is that this GUID will be unique (which is actually the same axiom as testing vs 0).

Obviously doing this is absurd.

TLDR; If you can trust NewGuid() to produce unique results, you can also trust it to not produce any single known GUID.

* Its actually not the same probability as .NET GUIDs always fit the following {________-____-4___-____-____________} so NewGuid will NEVER generate a zero guid

Just for fun I suggested an improvement to the docs here: http://feedback.msdn.com/forums/257782-msdn-feature-suggestions/suggestions/7143498-fix-documentation-for-newguid


问:
can you have too many dto/bo - mapping method
I have a windows service, 2 web services and a web interface that need to follow the same path (data wise).

So I came up with two ways of creating my solution.

My concern is the fact that the UI/WS/etc will have their own kind of DTO (let's say the model in ASP.Net MVC) that should be mapped to a DTO so the SL can then map it to a BO then mapping it to the proper EF6 DTO so that I can save it in a database.

So I'm thinking of doing it this way

to remove one level of mapping.

Which one should I take? Or is there a 3rd solution?

答:
You could go with proper domain model, which can be used across SL,BL and DAL. And for WebServices / WindowsService and for UI i would use appropriate DTO, which could be different but that makes sense because each service might expose different functionality. For example imagine the domain is like,

```<code>Order
{
    long orderId { get; set;}
    decimal value { get; set;}
    Customer customer { get; set;}
    List<Orderline> orderlines { get }

    void Add(Product p,qty q)
    {
        orderlines.Add(new Orderline(){order = this, product = p,qty = q,unitPrice = p.unitPrice});
        value += p.unitPrice * q;
    }
}

Customer
{
    long customerId { get; set;}
    string firstName { get; set;}
    string lastName { get; set;}
}

OrderLine
{
    Order order { get; set; }
    Product product { get; set;}
    decimal qty { get; set;}
    decimal unitPrice { get; set;}
}

Product
{
   long productId { get; set;}
   string productName { get; set;}
   decimal unitPrice { get; set;}
}
</code>```

And this domain model can be persisted / contains business logic also. So this model can be used across SL/BLL/DAL.

In the web service when you want to get order details, you might want to map into a DTO like,

```<code>OrderWSDTO
{
     long orderId { get; set;}
     string customerName { get; set; }
}

OrderLineWSDTO
{
    string productName { get; set;}
    decimal quantity { get; set;}
    decimal value { get; set;}
}
</code>```

However in UI (order list) it could be totally different representation.

```<code>OrderSummaryUIDTO
{
    string orderId { get; set;}
    decimal value { get; set;}
    string commaSeparatedProductNames { get; set;}
}
</code>```

Body:
You could go with proper domain model, which can be used across SL,BL and DAL. And for WebServices / WindowsService and for UI i would use appropriate DTO, which could be different but that makes sense because each service might expose different functionality. For example imagine the domain is like,

Order
{
    long orderId { get; set;}
    decimal value { get; set;}
    Customer customer { get; set;}
    List<Orderline> orderlines { get }

    void Add(Product p,qty q)
    {
        orderlines.Add(new Orderline(){order = this, product = p,qty = q,unitPrice = p.unitPrice});
        value += p.unitPrice * q;
    }
}

Customer
{
    long customerId { get; set;}
    string firstName { get; set;}
    string lastName { get; set;}
}

OrderLine
{
    Order order { get; set; }
    Product product { get; set;}
    decimal qty { get; set;}
    decimal unitPrice { get; set;}
}

Product
{
   long productId { get; set;}
   string productName { get; set;}
   decimal unitPrice { get; set;}
}

And this domain model can be persisted / contains business logic also. So this model can be used across SL/BLL/DAL.

In the web service when you want to get order details, you might want to map into a DTO like,

OrderWSDTO
{
     long orderId { get; set;}
     string customerName { get; set; }
}

OrderLineWSDTO
{
    string productName { get; set;}
    decimal quantity { get; set;}
    decimal value { get; set;}
}

However in UI (order list) it could be totally different representation.

OrderSummaryUIDTO
{
    string orderId { get; set;}
    decimal value { get; set;}
    string commaSeparatedProductNames { get; set;}
}


问:
Declaring JS Functions in Two Ways : What's the Benefit?
I've come across JS code in which I see functions being declared in two different styles:

Method 1

```<code>function doSomething(){

   alert('This is one way of declaring a function');

}
</code>```

Method 2

```<code>doSomething = function() {

    alert('And this is another way of declaring the same function');

}
</code>```

So what is the difference between the two and is there a case scenario where it would make sense to follow one method over the other?

PS: Sorry if the title seems vague. I didn't know the technical term used to describe the way the above two functions are declared.

答:
Method 1

For Method 1, the function and its symbol is processed by the parser before any code in this file is run.  Thus the definition is "hoisted" to the top of whatever scope it is in and the symbol can be used anywhere in the scope it is defined in.  Order of declaration within a scope does not matter.

So, with the first method, you can do this:

```<code>hello();

function hello() {
    console.log("hello");
}
</code>```

because the first pass over the code to parse it will define the symbol hello to be your function.  Therefore, in the second pass when the code is actually executed, the symbol hello already exists so it can be called at any time.

Method 2

For Method 2, the function is processed by the parser, but the symbol that contains the function is not assigned a value until the assignment statement is executed at run-time.  Code in this scope before this line cannot use the symbol (because it doesn't yet have a value).  Order of assignment within a scope does matter and does have to be paid attention to.

Using, your second method, the same ordering as in the example above will not work:

```<code>hello();

var hello = function() {
    console.log("hello");
}
</code>```

because the symbol hello is not yet defined when you try to use it.  Instead, you would have to do this:

```<code>var hello = function() {
    console.log("hello");
}

hello();
</code>```

Summary

People seem to have a preference for one style vs. the other.  Personally, I like the first style as it just seems simpler to let the parser define all your function symbols and not have to worry about declaration order.  The one exception I make is if I'm actually assigning different functions to a given variable depending upon some condition.  Then, I may use the second style.

Body:
Method 1

For Method 1, the function and its symbol is processed by the parser before any code in this file is run.  Thus the definition is "hoisted" to the top of whatever scope it is in and the symbol can be used anywhere in the scope it is defined in.  Order of declaration within a scope does not matter.

So, with the first method, you can do this:

hello();

function hello() {
    console.log("hello");
}

because the first pass over the code to parse it will define the symbol hello to be your function.  Therefore, in the second pass when the code is actually executed, the symbol hello already exists so it can be called at any time.

Method 2

For Method 2, the function is processed by the parser, but the symbol that contains the function is not assigned a value until the assignment statement is executed at run-time.  Code in this scope before this line cannot use the symbol (because it doesn't yet have a value).  Order of assignment within a scope does matter and does have to be paid attention to.

Using, your second method, the same ordering as in the example above will not work:

hello();

var hello = function() {
    console.log("hello");
}

because the symbol hello is not yet defined when you try to use it.  Instead, you would have to do this:

var hello = function() {
    console.log("hello");
}

hello();

Summary

People seem to have a preference for one style vs. the other.  Personally, I like the first style as it just seems simpler to let the parser define all your function symbols and not have to worry about declaration order.  The one exception I make is if I'm actually assigning different functions to a given variable depending upon some condition.  Then, I may use the second style.


答:
The short answer is "almost never", but there are, in fact, a few places where the DIP doesn't make sense:

Factories or builders, whose job it is to create objects. These are essentially the "leaf nodes" in a system that fully embraces IoC. At some point, something has to actually create your objects, and can't depend on anything else to do that. In many languages, an IoC container can do it for you, but sometimes you need to do it the old-fashioned way.

Implementations of data structures and algorithms. Generally, in these cases the salient characteristics that you're optimizing for (such as running time and asymptotic complexity) depend upon specific data types being used. If you're implementing a hash table, you really need to know that you're working with an array for storage, not a linked list, and only the table itself knows how to properly allocate the arrays. You also don't want to pass in a mutable array and have the caller break your hash table by fiddling with its contents.

Domain model classes. These implement your business logic, and (most of the time) it only makes sense to have one implementation, because (most of the time) you're only developing the software for one business. Although some domain model classes might be constructed using other domain model classes, this is generally going to be on a case-by-case basis. Since domain model objects don't include any functionality that can be usefully mocked, there's no testability or maintainability benefit to the DIP.

Any objects which are provided as an external API and need to create other objects, whose implementation details you don't wish to expose publicly. This falls under the general category of "library design is different from application design". A library or framework may make liberal use of DI internally, but will eventually have to do some actual work, otherwise it's not a very useful library. Let's say you're developing a networking library; you really do not want the consumer to be able to provide its own implementation of a socket. You might internally use an abstraction of a socket, but the API you expose to callers is going to create its own sockets.

Unit tests, and test doubles. Fakes and stubs are supposed to do one thing and do it simply. If you have a fake that's complex enough to worry about whether or not to do dependency injection, then it's probably too complex (perhaps because it's implementing an interface that's also far too complex).

There might be more; these are the ones I see on a somewhat frequent basis.


问:
Reimplementing algorithm from GPL program
If I reimplement an algorithm of a program covered by GPL v2 do I have to also license my program as GPL v2?

And to be specific:

I need a javascript library to compare debian packages versions. There is no such. So I'm going to directly translate the comparison algorithm implemented in apt (C++) into JS and publish it thereafter.

答:
If you are literally translating the C++ code that implements the algorithm, then you are creating a derived work of apt and you must license your code under the GPL as well.

On the other hand, if you implement the algorithm based on a textual/mathematical description of the algorithm without looking at the C++ implementation, then your code is not a derived work and you are free to choose your license as you wish.

If you don't translate the C++ code, but you do look at it, then you are in a legal grey area. In that case, it is not entirely clear if your code will be considered a derived work or an independent implementation of the algorithm. To be on the safe side, you can best regard it as a derived work.

The difference exists because algorithms themselves are not subject to copyright, but their implementations are.


问:
Problems with OO design for application with pluggable components
I'm trying to refactor an ugly code and make it easly extendable in the future.

The application should be nothing else but a series of components that have input(s) and output(s). The components are chained in such manner that the current component's input is the output of one (or more) previous components.

Here's a quick overview of what I have so far:

Reader

Denotes a data source

Can be a file on HDD, online resource, database, etc.

Splitter

Input is Reader(s)

Splits the contents of what reader delivers into parts

Outputs are split contents of Reader(s)

Model

Input is Splitter(s)

Creates a model of something based on Splitter(s) outputs

Output is silent, but you can say that the output is an internal state that can be queried for individual inputs

Tester

Input is a model

It can query a model for a result on some data

Output is optional, but in case it is used, it's a stream of (queryInput, queryOutput) data

Writer

Input is practiacally anything that produces a collection of objects

Writes that collection to wherever

I dunno what the output should be right now

So, I want to do have the ability to plug them in the following manner:

-->Reader-->Splitter-->Model-->Tester-->Writer-->

However, this would also be a valid combination (it obviously does nothing more but a simply data transfer)

-->Reader-->Writer-->

Now, since I'd like to be able to plug (almost) everything to everything and (possibly) create quite long chains, I'd assume I'd have to have some sort of Pluggable interface.

Also, when creating such big chain, I'd probably want to wrap it behind a Facade. And since I'd want each pluggable component (class) to be replaced by some other, then Strategy pattern comes to mind.

Now, since I've already mentioned the term chain here, Chain of Responsibility pattern comes to my mind, in the following (or similar way):

```<code>public interface Pluggable<InputType, OutputType> {
    public void consume(Pluggable<?, InputType> previous);
    public Collection<OutputType> produce();
}
</code>```

For example, if I wanted to have my Splitter to split a list of Files provided by Reader, it might looks something like this:

```<code>public class Splitter<InputType, OutputType> implements Pluggable<?, InputType> {
    public void consume(Pluggable<?, InputType> previous) {
        // retrieves for example a list of InputType objects
    }

    public Collection<OutputType> produce() {
        // filters the collection it got and returns a sublist for example
    }
}
</code>```

In the end, the components might look something like this:

Reader<File, Foo> --> Splitter<Foo, Foo> --> Model<Foo, Void> --> Test<Model, Bar> --> Writer<Bar, DAO>

I don't know how else to describe the problem I'm having, but I'm sure something like this is quite achieveable. For visual example, here's the image of RapidMiner's process

Note that I'm not trying to replicate or copy Rapid Miner, it's just that the project I was assigned looks like it can be implemented in simiar way.

I'd appreciate any help regarding how to design such application.

答:
No, Chain of Responsibility doesn't make sense here, because it assumes all components have same interface. I don't think Java's type system is good enough to make this fully generic, so I would opt in to type erasure and some kind of "manager" that pipes output of one module into input of next one, while encapsulating the erasure.

The module's interface would look something like this:

```<code>public interface Pluggable {
    public Class inputType();
    public Class outputType();
    public Object handle(Object previous);
}
</code>```

The manager would accept list of instances that implement this interface, check if their input/output classes work and then do the piping between them.

If this was C#, I would make it even nicer by creating abstract class, that would be generic in same way as your interface, I would implement the Pluggable explicitly(to hide it from sight) and implement the inputType and outputType with typeof() and create abstract and wrap the handle method in generic abstract method. I don't know how that would be possible in Java.

```<code>public interface IPluggable
{
    Type InputType { get; }
    Type OutputType { get; }

    Object Handle(Object value);
}

public abstract class Pluggable<TInput, TOutput> : IPluggable
{
    Type IPluggable.InputType { get { return typeof(TInput); } }
    Type IPluggable.OutputType { get { return typeof(TOutput); } }
    object IPluggable.Handle(object value)
    {
        return Handle((TInput)value);
    }

    protected abstract TOutput Handle(TInput value);
}
</code>```

This is how the "manager" class might look like. Sorry C# again.

```<code>public class PluginPipeline
{
    public static PluginPipeline Create(IEnumerable<IPluggable> plugins)
    {
        EnsurePluginsAreInRightOrder(plugins);
        return new PluginPipeline(plugins);
    }

    private static void EnsurePluginsAreInRightOrder(IEnumerable<IPluggable> plugins)
    {
        Type previousType = typeof(object); // first is little special..
        foreach(IPluggable plugin in plugins)
        {
            if (plugin.InputType != previousType)
                throw new Exception("Invalid link in pipeline!");

            previousType = plugin.OutputType;
        }
    }

    private readonly IEnumerable<IPluggable> _plugins;

    private PluginPipeline(IEnumerable<IPluggable> plugins)
    {
        _plugins = plugins;
    }

    public void Execute()
    {
        object previousValue = null;

        foreach(IPluggable plugin in _plugins)
        {
            previousValue = plugin.Handle(previousValue);
        }
    }
}
</code>```

Body:
No, Chain of Responsibility doesn't make sense here, because it assumes all components have same interface. I don't think Java's type system is good enough to make this fully generic, so I would opt in to type erasure and some kind of "manager" that pipes output of one module into input of next one, while encapsulating the erasure.

The module's interface would look something like this:

public interface Pluggable {
    public Class inputType();
    public Class outputType();
    public Object handle(Object previous);
}

The manager would accept list of instances that implement this interface, check if their input/output classes work and then do the piping between them.

If this was C#, I would make it even nicer by creating abstract class, that would be generic in same way as your interface, I would implement the Pluggable explicitly(to hide it from sight) and implement the inputType and outputType with typeof() and create abstract and wrap the handle method in generic abstract method. I don't know how that would be possible in Java.

public interface IPluggable
{
    Type InputType { get; }
    Type OutputType { get; }

    Object Handle(Object value);
}

public abstract class Pluggable<TInput, TOutput> : IPluggable
{
    Type IPluggable.InputType { get { return typeof(TInput); } }
    Type IPluggable.OutputType { get { return typeof(TOutput); } }
    object IPluggable.Handle(object value)
    {
        return Handle((TInput)value);
    }

    protected abstract TOutput Handle(TInput value);
}

This is how the "manager" class might look like. Sorry C# again.

public class PluginPipeline
{
    public static PluginPipeline Create(IEnumerable<IPluggable> plugins)
    {
        EnsurePluginsAreInRightOrder(plugins);
        return new PluginPipeline(plugins);
    }

    private static void EnsurePluginsAreInRightOrder(IEnumerable<IPluggable> plugins)
    {
        Type previousType = typeof(object); // first is little special..
        foreach(IPluggable plugin in plugins)
        {
            if (plugin.InputType != previousType)
                throw new Exception("Invalid link in pipeline!");

            previousType = plugin.OutputType;
        }
    }

    private readonly IEnumerable<IPluggable> _plugins;

    private PluginPipeline(IEnumerable<IPluggable> plugins)
    {
        _plugins = plugins;
    }

    public void Execute()
    {
        object previousValue = null;

        foreach(IPluggable plugin in _plugins)
        {
            previousValue = plugin.Handle(previousValue);
        }
    }
}


答:
My guess is that prediction hints at the machine instruction level are at best a noise, and at worst a detriment (wasted instruction bytes) on modern out-of-order, speculative-executing architecture. Doing so would be like telling the CPU to dumb down - to stop doing its already intelligent things it is designed to perform.

Secondly, the degree to which branch prediction can be improved depends on the  the cause of the misprediction, and the ease with which one can measure the performance effects of, or to observe the tendency of the branch.

However, I think that the existing bag of JIT optimization tricks can already improve branch prediction to a certain extent, even without the help of CPU branch misprediction counters.

Just a very simple code example:

```<code>public void repeatHistory(int value)
{
    if (value == 1492)
    {
        landing();
    }
    else if (value == 1776)
    {
        ratifying();
    }
}
</code>```

Supposed that repeatHistory is called a lot of times. When the sampling-based performance monitor analyzes the call stack statistics, it may find that, for whatever reason, repeatHistory() calling ratifying() occurs more frequently than the former calling landing(). Based on this observation, the next pass of JIT code generation for the repeatHistory method will take this into account, and perform one or more optimizations:

Move the check for (value == 1776) ahead of the check for (value == 1492)

Attempt to inline the ratifying() method into the branch in repeatHistory()

If the repeatHistory() is called from another loop, try unroll the loop, or inline the repeatHistory() method into that loop.

And many others.

After applying one optimization, it is often necessary to analyze again to see if more optimizations can be applied, because a successful one will often open the door to more opportunities.

Title: Does current JIT optimize generated machine codes for branch prediction based on runtime statistics?

Body:
Some JVMs would compile Java byte code into native machine code. We know that there are lots of optimizations we could apply for that. Recently, I also learn that a branch operation may block the CPU and affect the performance significantly, if a CPU makes a wrong prediction. </p>

<p>Does anyone know if any JVM would generate machine codes easier for CPU making right prediction based on runtime statistics collected? </p>

Body:
My guess is that prediction hints at the machine instruction level are at best a noise, and at worst a detriment (wasted instruction bytes) on modern out-of-order, speculative-executing architecture. Doing so would be like telling the CPU to dumb down - to stop doing its already intelligent things it is designed to perform.

Secondly, the degree to which branch prediction can be improved depends on the  the cause of the misprediction, and the ease with which one can measure the performance effects of, or to observe the tendency of the branch.

However, I think that the existing bag of JIT optimization tricks can already improve branch prediction to a certain extent, even without the help of CPU branch misprediction counters.

Just a very simple code example:

public void repeatHistory(int value)
{
    if (value == 1492)
    {
        landing();
    }
    else if (value == 1776)
    {
        ratifying();
    }
}

Supposed that repeatHistory is called a lot of times. When the sampling-based performance monitor analyzes the call stack statistics, it may find that, for whatever reason, repeatHistory() calling ratifying() occurs more frequently than the former calling landing(). Based on this observation, the next pass of JIT code generation for the repeatHistory method will take this into account, and perform one or more optimizations:

Move the check for (value == 1776) ahead of the check for (value == 1492)

Attempt to inline the ratifying() method into the branch in repeatHistory()

If the repeatHistory() is called from another loop, try unroll the loop, or inline the repeatHistory() method into that loop.

And many others.

After applying one optimization, it is often necessary to analyze again to see if more optimizations can be applied, because a successful one will often open the door to more opportunities.


问:
Observer pattern: Prevent multiple firings on changed internal property
I have an object Foo that has 2 public properties: A and B.

These properties can be changed from outside, as the application I'm working on is using a data-binding architecture. This is the front-end (client) code, but it's also communicating with a server to fetch data.

So my object is listening for changes to both A and B.

Any change in A or B is triggering the update() method, which triggers a request to the server.

I also have a piece of logic in my object Foo that says every time you change B, you have to reset A to its initial value.

My problem is, how do I deal with updating B without triggering the update() method twice?

Looking at the image above, the green path should always trigger an update. The red path ends up sometimes triggering 2 updates, because by changing B it changes A (if it's not the initial value), which always triggers an update.

I have to add that everything is asynchronous so the observers for my properties don't notify me immediately after changing objects. (design choice of the platform and language I'm working in – Polymer.JS). So this makes it harder to set a flag before changing B from A - I tried this but it didn't work, as the watcher method gets triggered after the chain of changes has executed.

As I come from the front-end world, with a background in graphic design, I don't have the knowledge necessary to spot the mistakes I might be doing, but I want to learn, so I'd like you to point me to reference material and/or books I can read about the correct applications of the observer pattern.

Is there a pattern that deals with this particular scenario and what are possible solutions to this?

If the observer pattern isn't the right choice for this, is there another pattern I could use internally that allows me to expose only the two properties A and B to the outside world?

A third option would be that I'm applying the right pattern, but the platform doesn't support what I'm trying to achieve. I'd like to know this so I can post the question on StackOverflow under the right tags.

答:
You make a special message to A that changes it in a way that is not propagated. Its a common idiom where you want general updates to send notifications, but not internal updates or refreshes.

For example, I have a dialog that has notification handlers for changes to various controls, but in the initialisation I want to set the controls initial state - without sending these notifications. In this case, I simply set an 'initialising' flag that the notification handler checks for, if its set the handler simply does nothing.

If you cannot set a flag to change the state of A to prevent notification, then you will have to send it with the change message. So you have 2 messages, one to update A (the general case) and another to quietly change A that is sent by B but still allows for changes to A to be triggered when others change it. I don't know how you make these updates so the implementation specifics is up to you.


问:
SQL - Algorithm for finding availability of a resource
I'm having trouble creating a mysql compatible algorithm for this.

Background

App with mysql, perl and JS. It's a booking system where each booking is comprised of a start, end and qty.  Start and end are timestamps.

Schema simplified to a single table:

|  bookings
|-------------------
| id    | pkey
| start | timestamp
| end   | timestamp
| qty   | int
```

<h2>Question</h2>

<p>In SQL, how do you check how many resources are booked at once for a given <code>timeRange</code>? Code with explanation or an algorithm that is SQL compatible both work.</p>

<p>So, for the following schedule:</p>

<pre class="lang-none prettyprint-override"><code>09:00 -----               <-|
09:30 |   |                 | A maximum of 12 are booked at once during this range
10:00 |x7 |                 |
10:30 ----- ----- -----     |
11:00       |   | |   |     |
11:30       |x2 | |x10|   <-|
12:00       |   | |   |
12:30       ----- -----
</code>```

I should get 12 since the x2 and x10 bookings don't overlap with the x7 booking, so there are never more than 12 items booked at once between 9:00 and 11:30.

Progress

--It's been heavily shrunk to show just the relevant part, so it might have some errors
SELECT coalesce(max(qtyOverlap.sum),0) booked
FROM (
    SELECT coalesce(sum(b2.qty),0) sum
        FROM booking b1
        LEFT JOIN (
            SELECT b.qty, b.tStart, b.tEnd FROM booking b
        ) b2
        ON b1.tStart < b2.tEnd AND
           b1.tEnd > b2.tStart AND
           b2.tStart < '2015-02-19 16:30:00' AND
           b2.tEnd > '2015-02-19 06:00:00'
        WHERE
              b1.tStart < '2015-02-19 16:30:00' AND
              b1.tEnd > '2015-02-19 06:00:00'
        GROUP BY b1.id
) qtyOverlap
GROUP BY qtyOverlap.itemId
```

<p>Which is this algorithm:</p>

<pre class="lang-none prettyprint-override"><code>Max of
    For each booking that overlaps given timeRange
        return sum of
            each booking that overlaps this booking and given timeRange
</code>```

In the schedule above this would be:

```<code>max([7],[2+10],[10+2]) = 12
</code>```

But given a schedule like:

09:00 -----               <-|
09:30 |   |                 | A maximum of 17 are booked at once during this range, not 19
10:00 |x7 |                 |
10:30 |   |       -----     |
11:00 -----       |   |     |
11:30       ----- |x10|   <-|
12:00       |x2 | |   |
12:30       ----- -----
```

<p>This gives:</p>

```max([7+10],[2+10],[10+7+2]) = 19
```

<p>Which is wrong.</p>

<p>The only way I can think of to fix this is to use recursion (which isn't mysql compatible afaik).</p>

<p>It would look something like (in working JS code)</p>

```function getOverlaps(bookings,range) {
    return bookings.filter(function(booking){
        return isOverLapping(booking,range);
    });
}
function isOverLapping(a, b) {
    return (a.start  b.start);
}
function maxSum(booking, overlaps) { // main recursive function
    var currentMax = 0;
    var filteredOverlaps = getOverlaps(overlaps,booking);
    for (var i = 0; i < filteredOverlaps.length; i++) {
        currentMax = Math.max(
            maxSum(filteredOverlaps[i], removeElement(filteredOverlaps,i)),
            currentMax
        );
    }
    return currentMax + booking.qty;
}
function removeElement(array,i){
    var clone = array.slice(0)
    clone.splice(i,1);
    return clone;
}
var maxBooked = maxSum(timeRange, getOverlaps(bookings,timeRange));
```

Visual JSFiddle demo

Any way to do this in SQL? (any reasonable way, that is)

Update
I just tried to use a stored procedure recursion emulation method as documented here. But part way through implementing it, I tried it with the demo data and decided the performance was far too terrible. Actually, it just needed indexing. Now it's just 'kinda' bad.

答:
This is tricky, because you've modeled your bookings as time intervals with granularity as fine as your DB allows. Perfectly natural to do, but as you've found out it makes some comparisons difficult.

Max of
    For each booking that overlaps given timeRange
        return sum of
            each booking that overlaps this booking and given timeRange
```

<p>The problem with this algorithm is that it checks that each other booking interval matches the one currently being examined (the foreach iteration), but it doesn't check overlapping bookings against each other, to see if they line up. A run through of your second example goes like this:</p>

<ul>
<li>Select 7x booking
<ul>
<li>7x does not overlap with 2x; +0</li>
<li>7x overlaps with 10x; +10</li>
<li>Total 17</li>
</ul></li>
<li>Select 2x booking
<ul>
<li>2x does not overlap with 7x; +0</li>
<li>2x overlaps with 10x; +10</li>
<li>Total 12</li>
</ul></li>
<li>Select 10x booking
<ul>
<li>10x overlaps with 7x; +7</li>
<li>10x overlaps with 2x; +2</li>
<li>[Missing step: check if 7x and 2x overlap]</li>
<li>Total 19 </li>
</ul></li>
<li>Max 19</li>
</ul>

<p>Is it reasonably possible to map your data to nice, neat discrete chunks of some size? For example, do your bookings generally begin and end on the 15s (12:00, 12:15, 12:30, 12:45)? If so, you can change your algorithm to compare bookings against a static time interval, rather than each other, and drastically reduce the required number of comparisons:</p>

<pre class="lang-none prettyprint-override"><code>Max of
  For each 15 minute chunk in timeRange
    Sum quantities of all bookings overlapping this chunk
</code>```

In terms of SQL implementation, choose an interval size and use a numbers or tally table to generate an inline query to create the chunks:

```<code>select @startTime + interval (15 * numbers.value) minute as start
, @startTime + interval (15 * (numbers.value + 1)) minute as end
from numbers
where (@startTime + interval (15 * numbers.value) minute) < @endTime
</code>```

(Off the cuff, may contain minor syntax or math errors)

This is a relatively sane way of performing this query in SQL without recursion. It has the obvious drawback that it will never perfectly align with your current schema, but do you really need absolute perfection?

I've used 15 minutes as an example size. You can easily make this as finely grained as you like: 5 minutes, 1 minute, 1 second, etc. There must be some point at which the granularity is too fine, because MySQL's timestamp type does not possess arbitrary precision. "Booking" to me implies something involving humans actually showing up. If this is true, I can't imagine that an interval size smaller than one minute would be appropriate.

In the comments you expressed some concern about performance because of a large number of comparisons. Complexity for this algorithm is O(n*m), where n is the number of chunks (time range / interval size) and m is the number of booking rows within the given time range. I'll hazard that in practice, n >> m, meaning that what really matters to the computation time is the number of intervals. This should be a non-issue, as long as you use sane timeframes and your DB is indexed and maintained correctly. For example, using an interval size of one second for the time range in your question (9:00 - 11:30) is only 9000 intervals to inspect. 9000 rows is paltry to an SQL server. I trust this to be performant a lot more than I do using dynamic SQL to emulate recursion.

If the interval size is 50 million times smaller than the time range, then yes, this will take a significant amount of time to run (notice I didn't say perform poorly), because you'll be running a query against 50 million rows. But is querying the maximum bookings for every millisecond in a twelve hour span (43.2 million ms) reasonable and necessary? There are only 604800 seconds in a week. Performing a query on a set that size, while not trivial, shouldn't give an SQL server any difficulty.

What does your data look like? How fine of an inspection period do you need? If there's a two minute (or second, decasecond, millisecond...) interval where there are 105 bookings instead of 100 because someone entered an "unusual" end time, will that destroy the integrity of your report, or can that data be discarded as noise? I can't answer these questions, but some simple data and requirements analysis on your part can.

Body:
This is tricky, because you've modeled your bookings as time intervals with granularity as fine as your DB allows. Perfectly natural to do, but as you've found out it makes some comparisons difficult.

Max of
    For each booking that overlaps given timeRange
        return sum of
            each booking that overlaps this booking and given timeRange

The problem with this algorithm is that it checks that each other booking interval matches the one currently being examined (the foreach iteration), but it doesn't check overlapping bookings against each other, to see if they line up. A run through of your second example goes like this:

Select 7x booking

7x does not overlap with 2x; +0

7x overlaps with 10x; +10

Total 17

Select 2x booking

2x does not overlap with 7x; +0

2x overlaps with 10x; +10

Total 12

Select 10x booking

10x overlaps with 7x; +7

10x overlaps with 2x; +2

[Missing step: check if 7x and 2x overlap]

Total 19

Max 19

Is it reasonably possible to map your data to nice, neat discrete chunks of some size? For example, do your bookings generally begin and end on the 15s (12:00, 12:15, 12:30, 12:45)? If so, you can change your algorithm to compare bookings against a static time interval, rather than each other, and drastically reduce the required number of comparisons:

Max of
  For each 15 minute chunk in timeRange
    Sum quantities of all bookings overlapping this chunk

In terms of SQL implementation, choose an interval size and use a numbers or tally table to generate an inline query to create the chunks:

select @startTime + interval (15 * numbers.value) minute as start
, @startTime + interval (15 * (numbers.value + 1)) minute as end
from numbers
where (@startTime + interval (15 * numbers.value) minute) < @endTime

(Off the cuff, may contain minor syntax or math errors)

This is a relatively sane way of performing this query in SQL without recursion. It has the obvious drawback that it will never perfectly align with your current schema, but do you really need absolute perfection?

I've used 15 minutes as an example size. You can easily make this as finely grained as you like: 5 minutes, 1 minute, 1 second, etc. There must be some point at which the granularity is too fine, because MySQL's timestamp type does not possess arbitrary precision. "Booking" to me implies something involving humans actually showing up. If this is true, I can't imagine that an interval size smaller than one minute would be appropriate.

In the comments you expressed some concern about performance because of a large number of comparisons. Complexity for this algorithm is O(n*m), where n is the number of chunks (time range / interval size) and m is the number of booking rows within the given time range. I'll hazard that in practice, n >> m, meaning that what really matters to the computation time is the number of intervals. This should be a non-issue, as long as you use sane timeframes and your DB is indexed and maintained correctly. For example, using an interval size of one second for the time range in your question (9:00 - 11:30) is only 9000 intervals to inspect. 9000 rows is paltry to an SQL server. I trust this to be performant a lot more than I do using dynamic SQL to emulate recursion.

If the interval size is 50 million times smaller than the time range, then yes, this will take a significant amount of time to run (notice I didn't say perform poorly), because you'll be running a query against 50 million rows. But is querying the maximum bookings for every millisecond in a twelve hour span (43.2 million ms) reasonable and necessary? There are only 604800 seconds in a week. Performing a query on a set that size, while not trivial, shouldn't give an SQL server any difficulty.

What does your data look like? How fine of an inspection period do you need? If there's a two minute (or second, decasecond, millisecond...) interval where there are 105 bookings instead of 100 because someone entered an "unusual" end time, will that destroy the integrity of your report, or can that data be discarded as noise? I can't answer these questions, but some simple data and requirements analysis on your part can.


问:
Authenticating users across multiple web services
User details (name, address, etc) are stored across multiple sites that are vendor specific. For example, vendor A holds information concerning room bookings while vendor B holds information specific to cabs, vendor C holds information regarding parking, and the list continues. They also hold credentials specific to each of those services so there isn't a shared credential system or the concept of an identity provider. The information across these systems may hold the same information e.g. name, address, etc

Each of these vendors publish an API or web service of sorts. Since there is now a requirement to aggregate these services however provide users a single journey (as opposed to redirecting them to a vendor specific site), what options are available to authenticate users across all systems.

Bear in mind we have no control over vendor specific web services nor in some instances is there interest from the vendor to change their API to support an identity provider system.

答:
You'll have to authenticate to a single system that, in turn handles the connections to the other services. Then the user should see a single 'logon' user and a single website. The back-end then has to deal with retrieving data and aggregating it for display.

The service will have to have knowledge of all the other service's authentication mechanisms, possibly storing and associating each 3rd party service login info with the single user login you now manage (a bit like how some banks will provide you with an aggregated service from your other financial provider's services by asking you for your password and storing it). However, if the 3rd parties only require a login for authorisation to access their service, you can now have a single user that belongs to your new aggregation service. This depends if the information you receive is tailored to a specific user registration.


问:
How to efficiently determine when changes occur in event lists
We have a system that stores event information.
There is a primary list of events as well as a secondary list, these may overlap.
Secondary lists are combined with the primary based on 3 main rules.

Default - only displayed when no events are current

Events - only displayed when primary events are current

Override - displayed in stead of events

A new 3rd party system we have to integrate with means we need to get each of the different states throughout the days of what events/secondary events should be showing.
Eg, from 9-5 these events are current based on the timings/ rules, but then after 5 these events are current based on the timings and rules.

A simple example

Primary Events

Event alpha | 10:30 - 14:30

Event bravo | 14:00 - 16:00

Event charlie | 18:30 - 20:00

Secondary Events

Event zulu | 00:00 - 23:59 | default

Event yankee | 09:00 - 11:00 | default

Event xray | 09:00 - 11:30 | events

Event whiskey | 19:00 - 19:15 | override

Just on this very small example this would result as the following lists that we would need to generate

00:00-09:00
Event zulu

09:00-10:30
Event zulu
Event yankee

10:30-11:30
Event alpha
Event xray

11:30-14:00
Event alpha

14:00-14:30
Event alpha
Event bravo

14:30-16:00
Event bravo

16:00-18:30
Event zulu

18:30-19:00
Event charlie

19:00-19:15
Event whiskey

19:15-20:00
Event charlie

20:00-23:59
Event zulu

This is a tiny example in production there is usually hundreds to thousands of events over many days.
At present the only end points deal with this problem dynamically on the fly, this third party system requires we provide the data in this way.

It's all written in php, and we have the primary and secondary event lists in an array each.

What is the most efficient way of making these lists ?

We have considered doing a minute by minute check, but this seems horribly inefficient and I'm hoping there is a better way.

答:
So heres what I did in the end, rather than looping through each minute of each day and checking what should be showing I created a list of all the start and stop times (in one single list) then removed duplicates and sorted them in order. </p>

<p>This way I can just cycled through that array and that will give me the start/end times when things change. </p>

Body:
So heres what I did in the end, rather than looping through each minute of each day and checking what should be showing I created a list of all the start and stop times (in one single list) then removed duplicates and sorted them in order.

This way I can just cycled through that array and that will give me the start/end times when things change.


问:
Algorithm to find minimal set
I have a set of sets S and I want to find a minimal set of elements M such that each set in S shares at least one element with M.

```<code>S = set of sets
∀ f∈S ∃e · e∈f ∧ e∈M
</code>```

For example:

```<code>S = {{1}, {1, 2, 3}, {3, 4}, {5, 6}}
M = {1, 3, 5} or {1, 3, 6} or {1, 4, 5} or {1, 4, 6}
</code>```

Is there a name for this problem? What algorithms exist to find an approximation of M?

答:
If you think about it, this problem is very similar to the variation of the Boolean satisfiability problem of 3-satisfiability aka 3-SAT.

Take each set within S into individual boolean expressions separated by "or" gates.  Then each of these expressions would then be separated by "and" gates.  For example {{A}, {A, B, C}, {C, D}, {E, F}} could be translated into A ∧ (A ∨ B ∨ C) ∧ (C ∨ D) ∧ (E ∨ F).

Determining if a solution to this exists is NP-complete.  Though your particular problem always has a solution (worse case scenario being that you have no items in common), I fear that it is a sophistication of the 3-SAT problem.  Not only do you want a possible solution, you ideally want the one that requires the least number of items choosen.

If you want the very best solution, I think the best you can do is to search every possible solution and test it.  However, if an approximate solution is acceptable, you could begin searching for a solution by counting the number of items each set has in common with other sets and counting the number of times each unique value is used in every set.  Then attempt to formulate an approximation by choosing the most used value in each set starting with the set which has the most items in common with other sets and moving down, stopping if you manage to find a valid solution.  Again, while it isn't guaranteed to be an optimal solution, it will likely be a decent approximation.

Best of luck.

Title: Algorithm to find minimal set


答:
Generally you would have values A and B hidden using a mixin, changeable only through a method setA and setB (or better still by using a setter function).  Internally, you would simply assign A or B directly without calling the setA or setB directly, and then call update() which triggers the event.

In other words, you'd have setA that assigns A and then resets the value of B without calling  setB.  Take a look at this quick example:

```<code>function Obj() {
  var A, B;

  function resetB() {
    console.log('Resetting B');
    B = '';
  }
  function update() {
    console.log('Values updated');
  }
  return {
    get A() { return A; },
    get B() { return B; },
    set A(aVal) {
      A = aVal;
      resetB();
      update();
    },
    set B(bVal) {
      B = bVal;
      update();
    }
  };
}
var obj = new Obj();
obj.B = 'test';
// Console output:
// Values updated

// assert(obj.B == 'test')
obj.A = 'me';
// Console output:
// Resetting B
// Values updated

// assert(obj.A == 'me')
// assert(obj.B == '')
</code>```

Title: Observer pattern: Prevent multiple firings on changed internal property

Body:
I have an object Foo that has 2 public properties: A and B.

These properties can be changed from outside, as the application I'm working on is using a data-binding architecture. This is the front-end (client) code, but it's also communicating with a server to fetch data.

So my object is listening for changes to both A and B.

Any change in A or B is triggering the update() method, which triggers a request to the server.

I also have a piece of logic in my object Foo that says every time you change B, you have to reset A to its initial value.

My problem is, how do I deal with updating B without triggering the update() method twice?

Looking at the image above, the green path should always trigger an update. The red path ends up sometimes triggering 2 updates, because by changing B it changes A (if it's not the initial value), which always triggers an update.

I have to add that everything is asynchronous so the observers for my properties don't notify me immediately after changing objects. (design choice of the platform and language I'm working in – Polymer.JS). So this makes it harder to set a flag before changing B from A - I tried this but it didn't work, as the watcher method gets triggered after the chain of changes has executed.

As I come from the front-end world, with a background in graphic design, I don't have the knowledge necessary to spot the mistakes I might be doing, but I want to learn, so I'd like you to point me to reference material and/or books I can read about the correct applications of the observer pattern.

Is there a pattern that deals with this particular scenario and what are possible solutions to this?

If the observer pattern isn't the right choice for this, is there another pattern I could use internally that allows me to expose only the two properties A and B to the outside world?

A third option would be that I'm applying the right pattern, but the platform doesn't support what I'm trying to achieve. I'd like to know this so I can post the question on StackOverflow under the right tags.

Body:
Generally you would have values A and B hidden using a mixin, changeable only through a method setA and setB (or better still by using a setter function).  Internally, you would simply assign A or B directly without calling the setA or setB directly, and then call update() which triggers the event.

In other words, you'd have setA that assigns A and then resets the value of B without calling  setB.  Take a look at this quick example:

function Obj() {
  var A, B;

  function resetB() {
    console.log('Resetting B');
    B = '';
  }
  function update() {
    console.log('Values updated');
  }
  return {
    get A() { return A; },
    get B() { return B; },
    set A(aVal) {
      A = aVal;
      resetB();
      update();
    },
    set B(bVal) {
      B = bVal;
      update();
    }
  };
}
var obj = new Obj();
obj.B = 'test';
// Console output:
// Values updated

// assert(obj.B == 'test')
obj.A = 'me';
// Console output:
// Resetting B
// Values updated

// assert(obj.A == 'me')
// assert(obj.B == '')


问:
How to unit test that the correct implementation of an interface is used?
I have this problem with unit testing for years. Unit testing should test isolated units, that is, if we use interface/implementation vocabulary, it should test concrete implementation classes. Fine, let's do it. In a code that is the client of the interface, one should mock the interface to suit the tests. That's OK, let us do it where possible, too.

But then, in the productions code, there is some place where the actual implementation class is instantiated and used as the-instance-that-implements the interface. It may be factory methods, it can be somewhere else.

I have the problem how to actually test this glue between those two, correctly tested in isolation, layers. Using variants of instance of is brittle - not to say, the creator of the actual instance may be "smart" and choose different implementation based on circumstances. Even if not, it creates that instance using some configuration around.

So far, I either do not unit test in strict manner (so I do not do new Foo(directa, directb), but createApp(indirectA, indirectB).getFoo() instead), but that may not be proper unit testing. That does not test all the implementations, that test those-implementations-app-uses. Other approach I may see is to make tests of Foo implementation parametric, having a factory method makeFoo(a,b) and create subclasses for each implementations as well as one which creates those instances via an actual app.

Do you know of a good way on how to approach this?

In other words, the question may be simply "How to (unit) test glue code?"

答:
In an aftermath of https://vimeo.com/80533536 talk of @jbrains, posted by @ThomasRuiz, I came to this conclusion:

Write contract tests (the talk has strict definition of them, I have loose one: "tests that only use public API of the class").

Stop using new FooImpl(fooConfig) to create implementations of "instance that fulfills Foo contract", instead, make it mandatory for your code to have createFoo(fooConfig) factory method to instantiate the Foo contract worker (maybe it should be called hireFoo ;-) ).

Your contract tests should test against client.createFoo(testFooConfig). It may be you end up with the need of client being higherClient.createBar(...) itself. This is the weak spot of the whole thing. Maybe I should ask.jbrains.ca ... :-\

EDIT: Talked with @jbrains. The result is:

Your constructors should not create the collaborators. Ideally, they get them injected, like new Foo(collab1, collab2);

Applying this to the extreme, it ends up with creating all (!!!) collaborators up front in the topmost layer. See http://blog.thecodewhisperer.com/2011/12/07/refactor-your-way-to-a-dependency-injection-container. See it as an app config.

Citation "new A(new B(new E()), new C(new F(), new G()), new D()) is fine. A creating B, which creates E (and so on) causes problems", in https://twitter.com/jbrains/status/570974691013337089.

I finally know what actual dependency injection is and why it is important (your code becomes actually testable and decoupled, all the glue code is in one place and is the only untested piece).


问:
What are the deciding factors in choosing to expose a web service as a SOAP or REST service?
As far as I can see consuming SOAP requires a SOAP stack, so it is harder for your clients to consume i.e. they need to ensure that they have a SOAP stack in place that formats the POST data and the headers correctly and then gives you back some data structure, whereas with REST you just make an HTTP GET request with the arguments in the query string and get back some text that I guess is probably XML.

So what does the extra overhead / complexity of SOAP give you, when do you need it and when could you and should you do without it?

答:
It is now 2015. I would have hoped that SOAP has died by now, but it still lingers like a bad smell. For anything but the most basic of "example" applications, integrating with a SOAP service is frought with challenges. It is a complex architecture, with many options at multiple levels, combined with the quirks of multiple implementations and subtle (and not so subtle) incompatibilities. I've never had a single good experience with it. REST, on the other hand, is a breeze: everyone understands HTTP. For most cases, JSON has so muh more utility than XML InfoSet.

To give you an idea of the complexity of SOAP, try integrating a SOAP library into your project. For Java, the most basic Apache Axis2 client (using simple ADB data binding) pulls in 23 new JARs. Twenty three! 20MB of library bloat. CXF is similar: 21 JARs, when I last counted.

If you really wanted to, you can do REST with a simple HTTP library.


问:
forking but not exiting
It is normal for the child in a fork() to call exec() or _exit().

Are there any realistic scenarios where the child might return from the function that called fork() instead?

```<code>void foo() {
  pid_t pid = fork();
  if(pid == 0) {
     ...
     return; //<-- the child is going to unwind the cloned call stack
  }
  ...
</code>```

So what legitimate uses are there for a forked child returning?  Are there any standards that govern this?

答:
A child calling  exec is not terminated, it is replaced by a new program (running in the same process).

And the execve(2) syscall may fail for several reasons (so you always should handle such a failure). Then execution continues after the exec !

Read e.g. Advanced Linux Programming for details. It has at least a whole chapter about these issues.

Title: forking but not exiting