问:
Behavior Driven Development and Unit Testing in Python
We might be interested in starting to incorporate a unit test suite to our project, which is coded in Python (and it uses Redis, PostgreSQL and some third-party libraries, if that bears into the solution).  The benefits we want to achieve are:

Once the project is up to speed, we want to be able to specify new behavior quickly and efficiently, to help improve communication and team productivity.  Read: We want BDD, but have already started coding without it.

Excellent textual support (i.e. the tests can be read almost as natural text), so as to make it easier to write and read tests.

Ability to automatically run tests (at the very least, to be able to include the running in a Bash script or something like that).  We use Windows and Linux for development, and Linux servers, so Linux support is our primary requirement.

Integration with github.  I don't know if it is possible, but I've seen some projects in github which have a "Passing" or "Failing" status on them and it would be great to have that for our project.

What are good tools / libraries that can help us do this, and, most importantly, what are good ways to incorporate BDD into a Python project?

Thank you very much!  Any suggestions are appreciated.

答:
I've been working on a BDD framework called Contexts, inspired by C#'s Machine.Specifications.

Contexts encourages you to write descriptive user-centric sentences for your tests (which is what BDD is all about, really) by spreading out test-cases across a whole class. The arrange/act/assert phases of the test are put in individual short methods, and Contexts figures out which method is which based on their names.

A picture speaks a thousand words, so here's an example from the readme:

```<code>import requests

class WhenRequestingAResourceThatDoesNotExist:
    def given_that_we_are_asking_for_a_made_up_resource(self):
        self.uri = "http://www.github.com/itdontexistman"
        self.session = requests.Session()

    def because_we_make_a_request(self):
        self.response = self.session.get(self.uri)

    def the_response_should_have_a_status_code_of_404(self):
        assert self.response.status_code == 404

    def the_response_should_have_an_HTML_content_type(self):
        assert self.response.headers['content-type'] == 'text/html'

    def cleanup_the_session(self):
        self.session.close()
</code>```

Contexts also has a number of modern features like parametrised tests, 'assertion-rewriting' (inspired by py.test), and a plugin framework.

I've used Contexts to test itself, as well as on a few other projects (even non-Python projects), and found it to yield understandable, behavioural tests at all levels of the testing triangle (unlike unittest which was not designed for acceptance testing, or Lettuce which was not designed for unit testing).

Body:
I've been working on a BDD framework called Contexts, inspired by C#'s Machine.Specifications.

Contexts encourages you to write descriptive user-centric sentences for your tests (which is what BDD is all about, really) by spreading out test-cases across a whole class. The arrange/act/assert phases of the test are put in individual short methods, and Contexts figures out which method is which based on their names.

A picture speaks a thousand words, so here's an example from the readme:

import requests

class WhenRequestingAResourceThatDoesNotExist:
    def given_that_we_are_asking_for_a_made_up_resource(self):
        self.uri = "http://www.github.com/itdontexistman"
        self.session = requests.Session()

    def because_we_make_a_request(self):
        self.response = self.session.get(self.uri)

    def the_response_should_have_a_status_code_of_404(self):
        assert self.response.status_code == 404

    def the_response_should_have_an_HTML_content_type(self):
        assert self.response.headers['content-type'] == 'text/html'

    def cleanup_the_session(self):
        self.session.close()

Contexts also has a number of modern features like parametrised tests, 'assertion-rewriting' (inspired by py.test), and a plugin framework.

I've used Contexts to test itself, as well as on a few other projects (even non-Python projects), and found it to yield understandable, behavioural tests at all levels of the testing triangle (unlike unittest which was not designed for acceptance testing, or Lettuce which was not designed for unit testing).


问:
What is the most productive way to handle development-related failures?
We've all been there:

Your project failed or got cancelled.

The code you spent days working on got rejected by your team.

The design pattern you introduced to the team created chaos.

Everyone ignores your ideas.

My question is, what is the most productive way for a programmer to handle development-related failures such as these?

答:
You build something.

For me (I don't think it's right for everybody), building something (comics, drawings, little games, anything) is like building a bit of confidence to get back to fighting failure. It might also be a good way to express your anger or bitterness or any feelings relative to the failure, but in a "constructive" way.

That works for me anyway.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 2.5


问:
Accepting a numerical range in a function call
I have encountered two ways of doing it:

```<code>void foo(int from, int to); /* 'from' inclusive, 'to' exclusive */

void foo(int startIndex, int rangelength);
</code>```

Has one style historically been preferred over the other? If so, was it just a matter of convention or was it due to some deeper underlying reason?

I'm currently programming in Java and noticed that the Arrays class uses the former style. The exclusivity of the to argument felt somewhat unintuitive to me, which led me to ask this question.

答:
There isn't a hard-and-fast rule.  That's because one of the fundamental tenets of API design is making your callers' lives as easy as possible by giving them an interface that takes the kinds of values they're likely to have on hand.

Your example has parallels to C's memcpy(dest, src, n) function, which copies a range of memory n bytes long starting at src to a range of n bytes long starting at dest.  Most of the function's callers will be copying a primitive or data structure whose size in bytes can be determined using the sizeof operator:

```<code>some_structure src;
some_structure dest;
memcpy(&dest, &src, sizeof dest);  // Easy to understand
</code>```

Had the function been implemented as memcpy(dest, src_start, src_end) (where src_start and src_end are pointers to the first and last bytes in the structure, the caller would have to do a lot more gymnastics to figure out where the source structure ends:

```<code>memcpy(&dest, &src, ((void *)&src) + sizeof src - 1);  // Harder to understand
</code>```

What doesn't work well for memcpy() might work very well for functions that do counting.  If you know your callers have upper and lower range bounds in hand, it's much better to give them count(int from, int to) than count(int start, int how_many):

```<code>int lower;
int upper;
count(lower, upper);  // No gymnastics
</code>```

...versus...

```<code>count(lower, upper-lower+1);  // Gymnastics
</code>```

Even if the innards of count() need to know the number of iterations, it's better to calculate it in one place (inside the function) than force your callers who have upper and lower bounds to calculate it every time.

Sometimes which is better may be a toss-up.  In those cases, you provide two functions, one that does the grunt work and another that's just a wrapper that does the additional calculation:

```<code>count_iters(int start, int iterations) {
    // Do whatever this function does
}

count_range(int lower, int upper) {
    count_iters(lower, upper-lower+1);
}
</code>```

Providing the wrapper centralizes the calculation of the number of iterations, which means that fixing a bug in it will correct the problem for everything at once and you won't have to find and change every caller that's doing it wrong.

Bottom line:  If you pick one or the other arbitrarily or because someone says one style is better than the other, you haven't examined the use cases and made a decision.

Body:
There isn't a hard-and-fast rule.  That's because one of the fundamental tenets of API design is making your callers' lives as easy as possible by giving them an interface that takes the kinds of values they're likely to have on hand.

Your example has parallels to C's memcpy(dest, src, n) function, which copies a range of memory n bytes long starting at src to a range of n bytes long starting at dest.  Most of the function's callers will be copying a primitive or data structure whose size in bytes can be determined using the sizeof operator:

some_structure src;
some_structure dest;
memcpy(&dest, &src, sizeof dest);  // Easy to understand

Had the function been implemented as memcpy(dest, src_start, src_end) (where src_start and src_end are pointers to the first and last bytes in the structure, the caller would have to do a lot more gymnastics to figure out where the source structure ends:

memcpy(&dest, &src, ((void *)&src) + sizeof src - 1);  // Harder to understand

What doesn't work well for memcpy() might work very well for functions that do counting.  If you know your callers have upper and lower range bounds in hand, it's much better to give them count(int from, int to) than count(int start, int how_many):

int lower;
int upper;
count(lower, upper);  // No gymnastics

...versus...

count(lower, upper-lower+1);  // Gymnastics

Even if the innards of count() need to know the number of iterations, it's better to calculate it in one place (inside the function) than force your callers who have upper and lower bounds to calculate it every time.

Sometimes which is better may be a toss-up.  In those cases, you provide two functions, one that does the grunt work and another that's just a wrapper that does the additional calculation:

count_iters(int start, int iterations) {
    // Do whatever this function does
}

count_range(int lower, int upper) {
    count_iters(lower, upper-lower+1);
}

Providing the wrapper centralizes the calculation of the number of iterations, which means that fixing a bug in it will correct the problem for everything at once and you won't have to find and change every caller that's doing it wrong.

Bottom line:  If you pick one or the other arbitrarily or because someone says one style is better than the other, you haven't examined the use cases and made a decision.


问:
Domain Model vs View Model
I'm in the early stages of my programming career and I've been working with MVC for just about a year now. I've spent much time learning about the pattern and the concepts behind it, but as the projects I'm working with get larger I'm starting to think that maybe I don't have the best understanding of how the model layer is supposed to work.

I hear a lot about always having a View Model to protect your Domain Model but how does this work in practice? What does the relationship between the two look like? What if a model doesn't need any extra "view" logic, should I just create a copy of it? Why?

答:
You asked exactly the right question: "Why?"

MVC, MVP, MVVM, and probably a thousand minor deviations of those... There are so many design patterns out there, and the differences are very subtle. The only way to get clear grasp of how to design the GUI layer of your application is probably to lean back, collect your requirements and weigh them against each other. For example,

Do you need automated GUI tests? To what extent?

Do your screens include "complex" behavior that isn't easily covered by data binding? How many?

Do you need to be platform-independent?

What components will you likely want to reuse? For example, does your application target vastly different screen sizes but you want to reuse the business logic for all of them?

Example:

If you know you're not going to run automated tests and you only target the Swing platform (i.e. PCs with a relatively narrow range of screen resolutions), don't bother splitting your code in three classes and creating a Swing-independent view model. You gain nothing from it.

On the other hand, if you develop a GWT application that requires automatic tests because you have non-trivial business logic, you'll likely leverage the loose coupling MVP provides you so that you can run your tests in a lightweight fashion (i.e., without GWT components in a pure Java environment).

It's all about the specific requirements of your application and technology stack... And that is probably the reason why there are so many reincarnations of the same pattern.

Title: Domain Model vs View Model


问:
Scrum: how to integrate work done by an overachieving developer out of band?
We have a "typical" SCRUM team and we commit to work for a sprint, and also maintain a backlog. Recently we have run into a problem of trying to integrate/handle the work of an overachieving developer doing out of band work (choosing to work outside of the normal working hours/sprint).

To give an example, if the team takes in 50 points of work, let's say that they will complete all that work within the SCRUM framework by the end of the sprint and they and the company is happy. One of the team members decides to work on their own, on a backlog item, on their own free time. They do not check in this work, but instead save it (we use TFS and it is in a shelveset).

How to handle this? A few of the problems ..

During the next sprint this team members says the programming work is 99% done and just needs code review and testing. How do you deal with this in the SCRUM and agile methodology?

Other developers complain about not being involved in design decisions related to these stories, since the work was done out of band.

Our product owner is tempted to pull in this "free" work and the overachieving members is likely doing this on purpose in order to get more features into the product that the team otherwise would not be able to accomplish in the sprint(s). There is a view that this is breaking the "process". Obviously QA, UI and documentation work still need to be done on this work.

I see a lot of discussion about not forcing a SCRUM team to work overtime, but what about a member of the team working above and beyond the expectations put forth during planning and execution of sprints? I would hesitate to reign this person in and say you cannot work extra (cautioning on burn out of course), but at the same time it seems to be causing some issues with certain members of the team (but not all).

How to integrate work done by an overachieving member into the SCRUM and agile process for software development?

答:
Does this developer write tests and clean/solid code or is he/she just pushing out whatever he can get done quickly? I personally wouldn't allow anyone to work outside of the defined hours as it will mess up your estimates and as you pointed out other issues occur.

However, you should never be rigid in your process. Scrum is just a framework so you can always adjust the process to include the extra time (but again its difficult to plan for what someone might do).

You could also ask him to work on things other than the project. Looking at new tech or creating training on things he does differently. Bottom line though is anything done outside your planned schedule will destroy you estimates and I wouldn't let that happen.


问:
How using tab affects commands like diff
In the page at http://pear.php.net/manual/en/standards.indenting.php, it is advised to use space instead of tab as it causes issue with diff, patches. Here is the excerpt from the page.

Use an indent of 4 spaces, with no tabs. This helps to avoid problems with diffs, patches, SVN history and annotations.

So, my question is if we are using tabs everywhere, how it is going to affect these commands?

答:
If you are rigorous about using tabs everywhere in the project, then it really won't affect the command.  Usually the issue is mixing tabs and spaces.

If you mix tabs and spaces, you have to deal with two lines looking identical to humans but being different in regards to tools like diff:

```<code>if(i == 0) {
    do something;
</code>```

and

```<code>if(i == 0) {
    do something;
</code>```

The reason people avoid tabs and prefer spaces is that tabs display according to editor settings, so one developer writes this:

```<code>for(i=0; i<10; i++) {
    do this;
    do that;
    do it again;
}
</code>```

Another guy comes along with tabs set to two instead of four and makes an edit:

```<code>for(i=0; i<10; i++) {
  do this;
  do it different;
  do it again better;
}
</code>```

The other guy opens the code and it looks like:

```<code>for(i=0; i<10; i++) {
    do this;
  do it different;
  do it again better;
}
</code>```

Multiple by ten developers and the code quickly looks horrid for everybody.  So someone "fixes" it, and then your history is full of things like this:

```<code>for(i=0; i<10; i++) {
    -do this;
    -do it different;
    -do it again better;
    +do this;
    +do it different;
    +do it again better;
}
</code>```

Someone coming along wanting to use blame to figure out what developer to talk to about doing it different can't, because the log is full of formatting fixes.

Then someone gets the bright idea to change all tabs to spaces, and then a diff shows the entire file as having been changed.

Best to avoid the issue with spaces instead of tabs.  This avoids issues caused by someone hitting spacebar four times instead of the tab key.

Body:
If you are rigorous about using tabs everywhere in the project, then it really won't affect the command.  Usually the issue is mixing tabs and spaces.

If you mix tabs and spaces, you have to deal with two lines looking identical to humans but being different in regards to tools like diff:

if(i == 0) {
    do something;

and

if(i == 0) {
    do something;

The reason people avoid tabs and prefer spaces is that tabs display according to editor settings, so one developer writes this:

for(i=0; i<10; i++) {
    do this;
    do that;
    do it again;
}

Another guy comes along with tabs set to two instead of four and makes an edit:

for(i=0; i<10; i++) {
  do this;
  do it different;
  do it again better;
}

The other guy opens the code and it looks like:

for(i=0; i<10; i++) {
    do this;
  do it different;
  do it again better;
}

Multiple by ten developers and the code quickly looks horrid for everybody.  So someone "fixes" it, and then your history is full of things like this:

for(i=0; i<10; i++) {
    -do this;
    -do it different;
    -do it again better;
    +do this;
    +do it different;
    +do it again better;
}

Someone coming along wanting to use blame to figure out what developer to talk to about doing it different can't, because the log is full of formatting fixes.

Then someone gets the bright idea to change all tabs to spaces, and then a diff shows the entire file as having been changed.

Best to avoid the issue with spaces instead of tabs.  This avoids issues caused by someone hitting spacebar four times instead of the tab key.


答:
Alright, so someone's enthusiastically writing great code that needs to be done, just not in order.  With all due emphasis:

LET THEM

It's causing some complications in your scrum sprints.  Does it really matter in the grand scheme of things?  If he's accomplishing what he's supposed to, then let him go on and build great things for you.

I know several amazing programmers who have left companies because they did not let the programmers outside of the constraints of an artificial system like Scrum (I myself left my last job after being treated like nothing more than glorified QA).  If there are complaints from other developers about input (perfectly valid complaints, I may add), it may be best to introduce a "20% time" program to let him (and others) do what they do best with minimal interference.

Instead of future stories (that may require input from others), let the developer experiment with new tech or features.  You may find a great new opportunity that never would have been explored otherwise.  I'm sure this developer has a few things they'd like to try out if you just let them.

Title: Scrum: how to integrate work done by an overachieving developer out of band?

Body:
We have a "typical" SCRUM team and we commit to work for a sprint, and also maintain a backlog. Recently we have run into a problem of trying to integrate/handle the work of an overachieving developer doing out of band work (choosing to work outside of the normal working hours/sprint).

To give an example, if the team takes in 50 points of work, let's say that they will complete all that work within the SCRUM framework by the end of the sprint and they and the company is happy. One of the team members decides to work on their own, on a backlog item, on their own free time. They do not check in this work, but instead save it (we use TFS and it is in a shelveset).

How to handle this? A few of the problems ..

During the next sprint this team members says the programming work is 99% done and just needs code review and testing. How do you deal with this in the SCRUM and agile methodology?

Other developers complain about not being involved in design decisions related to these stories, since the work was done out of band.

Our product owner is tempted to pull in this "free" work and the overachieving members is likely doing this on purpose in order to get more features into the product that the team otherwise would not be able to accomplish in the sprint(s). There is a view that this is breaking the "process". Obviously QA, UI and documentation work still need to be done on this work.

I see a lot of discussion about not forcing a SCRUM team to work overtime, but what about a member of the team working above and beyond the expectations put forth during planning and execution of sprints? I would hesitate to reign this person in and say you cannot work extra (cautioning on burn out of course), but at the same time it seems to be causing some issues with certain members of the team (but not all).

How to integrate work done by an overachieving member into the SCRUM and agile process for software development?


答:
There are two things I think you should consider here:

Don't hinder someone's creative flow.

If a dev wants to do out-of-hours work, then let them.

Don't create work for others.

If a dev wants to do out-of-hours work, it sure as hell better not be creating more work for others.

Point 2 is likely what the other developers are worried about.

Like you mentioned, they don't like the fact that the code is written without the entire team's input.  This may be because, in terms of design, it ends up being inferior.  And code with inferior design has a way of infecting other code around it.

So, what can you do?

Let the ambitious dev code to his heart's content, but make it clear that there is no reason to assume his extracurricular code will be used.

After all, he is part of a team, and so the team should be involved in how all code is developed.

If, however, his work is sound and fits in with the team's agreed upon design then he'll be able to use much of what he's already written (bonus!).  If not, it'll force him to think more about his design the next time he decides to get a head start.

This way, nobody gets told NO, and nobody has extra work created for them.


答:
I'm going to answer a different question.
I think how to deal with this situation in Scrum is really not important. Scrum is more like a guideline anyway. If you want this to happen find a simple way to adapt your process like simply assuming the work is already done.

The real question is whether you want this dev to do what he is doing.
I think several aspects play a key role in the answer to that question:

Is the programmer doing good work.

Is everybody okay with him doing his work on his own (be it good or bad). He is dodging the design process, after all!

Are the extra hours paid or not.

All of these influence whether it makes sense for your product that he is doing what he is doing. Again, incorporating your decision in the design process is not really an issue. Just be flexible.


问:
Software architecture which allows for growth, real life situation
I know of Interfaces, Abstract classes that serve as Base class, I've been reading up on loose coupling, ... But I can't come up with a decent solution when a property of a class changes, and the new type needs to be implemented in other classes using this updated class.

Example

Below is a simplified representation of a real life situation. Invoice contains a Contact object which has an Address property.

```
Abstract Class Contact{
    string Name{get;set;}
    string Address{get;set;}
}
```

```
Class Customer:Contact{
    string CustomerNumber{get;set;}
}
```

```
Class Invoice{
    string DocumentNumber{get;set;}
    Customer Customer{get;set;}
}
```

Next, we decide to upgrade the Contact class to contain multiple Addresses. Of which the Invoice will need one.

```
Class Address{
    string Street{get;set;}
}
```

```
Abstract class Contact{
    string Name{get;set;}
    List<Address> Addresses{get;set;}
}
```

Logically, the Invoice class needs to be changed to something like

```
Class Invoice{
    string DocumentNumber{get;set;}
    Customer Customer{get;set;}
    Address InvoiceAddress{get;set;}
}
```

Problem

You immediately see that everywhere I used the string property Address before, I will now have to change it to an occurence of the type Address

As stated before, this is just a simplified example. The real life problem would be much, much bigger as contacts will be used throughout the entire software.

Conclusion

I want to develop the software with a principle that will keep my software light for new versions of certain modules. So that if I decide to create a new Contact module, the impact to the other modules is close to non-existing. So, the added functionality can be implemented gradually.

I want to know how I can tackle such versioning problems. This project is currently still in the architectural design stage, and I want this sorted out before we continue.

答:
Follow S.O.L.I.D Design Principles and don't be afraid to refactor as soon as you feel the need to.
Remove unused code, it can make refactoring difficult in the future.

Don't try to build a perfect design at once. Make it work then make it better. Follow Pareto principle: 20% efforts gives 80% of the result.


问:
Multiple var statements in JavaScript
Writing a single var declaration per function is considered to be good for readability and maintainability.

But, when I went through some of standard libraries, their dev version doesn't strictly follow this. For example, Underscore code has multiple var statements in many function which are spread randomly and declared as required.

Is there any reason to not to follow the single-var-rule?

答:
This is mostly a matter of personal preference and taste, and which coding style you are using (NPM, jQuery, Idiomatic.js, etc.), since there are valid arguments both for and against multiple var statements.

Oleg mentioned commenting. If you use a single statement, comments will break up the code in a way that may reduce readability. Indenting of comments may look strange (not aligned) depending on how you indent, but you could always do something like this:

```<code>var
  // This variable does this
  variableOne = 1,

  // This variable does that.
  variableTwo = 2
</code>```

Oleg also mentions JSDoc commenting, which may break things up further:

```<code>var
  /**
   * This variable does this.
   *
   * @private
   */
  variableOne = 1,

  /**
   * Object containing preferences for X. Access by calling
   * the public API method Y or whatnot.
   *
   * @private
   * @example
   * . . .
   *
   * @property {Object} preferences A can of fresh preferences
   * @property {Boolean} preferences.optionA Enable something
   * @property {Boolean} preferences.optionB Disable something
   * @property {String} preferences.optionC Name something
   */
  preferences = applyPreferencesToDefaults(userPreferences, {
    optionA: false,
    optionB: true,
    optionC: 'Hello'
  })
</code>```

Another argument for using multiple statements is that it's slightly easier to move them around, and there's less risk of comma or semicolon related problems (such as accidentally leaving one out when moving a line).

NPM advocates the comma-first (and semicolon-less) style to avoid such issues (which incidentally also aligns declarations neatly—if you use two spaces):

```<code>var variableOne = 'one'
  , variableTwo = 'two'
  , variableThree = 'three'
</code>```

Arguments for using a single var statement include: it looks better/simpler/cleaner; it's less typing, it's how JavaScript hoisting works; it forces you to declare at the top; Crockford says you're an idiot if you don't; it's a religion and/or cult more opinionated than Satan's.

In the end, the most important argument works just as well for either side: consistency.

If you use a consistent style, which you should, then it doesn't really matter if there's a var on each line or a comma on the left. It's important not to get religious about these things. Besides, a decent minifier will mangle the code own to the same one-liner either way.

I personally prefer multiple var statements simply because I like to neatly comment my variables, but I'm perfectly fine with either way.

Now, if we could all just agree that both styles work and that consistency is way more important than the actual choice—what a wonderful world that would be. Heck, can't it just be fun to switch it up once in a while?

This post by Ben Alman goes through it all in more detail, with more examples. The comments are, of course, also very interesting.

Update

I just read something else interesting, by Isaac of NPM:

Two var statements gzip better than a single var with a comma.

It's from a comment to this Gist, in which Isaac explains why he chooses comma-first for NPM. The comments are very interesting.

Title: Multiple var statements in JavaScript

Body:
This is mostly a matter of personal preference and taste, and which coding style you are using (NPM, jQuery, Idiomatic.js, etc.), since there are valid arguments both for and against multiple var statements.

Oleg mentioned commenting. If you use a single statement, comments will break up the code in a way that may reduce readability. Indenting of comments may look strange (not aligned) depending on how you indent, but you could always do something like this:

var
  // This variable does this
  variableOne = 1,

  // This variable does that.
  variableTwo = 2

Oleg also mentions JSDoc commenting, which may break things up further:

var
  /**
   * This variable does this.
   *
   * @private
   */
  variableOne = 1,

  /**
   * Object containing preferences for X. Access by calling
   * the public API method Y or whatnot.
   *
   * @private
   * @example
   * . . .
   *
   * @property {Object} preferences A can of fresh preferences
   * @property {Boolean} preferences.optionA Enable something
   * @property {Boolean} preferences.optionB Disable something
   * @property {String} preferences.optionC Name something
   */
  preferences = applyPreferencesToDefaults(userPreferences, {
    optionA: false,
    optionB: true,
    optionC: 'Hello'
  })

Another argument for using multiple statements is that it's slightly easier to move them around, and there's less risk of comma or semicolon related problems (such as accidentally leaving one out when moving a line).

NPM advocates the comma-first (and semicolon-less) style to avoid such issues (which incidentally also aligns declarations neatly—if you use two spaces):

var variableOne = 'one'
  , variableTwo = 'two'
  , variableThree = 'three'

Arguments for using a single var statement include: it looks better/simpler/cleaner; it's less typing, it's how JavaScript hoisting works; it forces you to declare at the top; Crockford says you're an idiot if you don't; it's a religion and/or cult more opinionated than Satan's.

In the end, the most important argument works just as well for either side: consistency.

If you use a consistent style, which you should, then it doesn't really matter if there's a var on each line or a comma on the left. It's important not to get religious about these things. Besides, a decent minifier will mangle the code own to the same one-liner either way.

I personally prefer multiple var statements simply because I like to neatly comment my variables, but I'm perfectly fine with either way.

Now, if we could all just agree that both styles work and that consistency is way more important than the actual choice—what a wonderful world that would be. Heck, can't it just be fun to switch it up once in a while?

This post by Ben Alman goes through it all in more detail, with more examples. The comments are, of course, also very interesting.

Update

I just read something else interesting, by Isaac of NPM:

Two var statements gzip better than a single var with a comma.

It's from a comment to this Gist, in which Isaac explains why he chooses comma-first for NPM. The comments are very interesting.

ContentLicense: CC BY-SA 4.0


答:
Much as I like the idea that adding free work into the mix is a good thing, this isn't free work - not unless that single developer is also the tester, and the QA and the build guy and the designer and everything else. If his work can be put into the next sprint without any impact, then.. go for it. But I think that is never the case. Everyone else, at the very least, has to understand what he's done and what impact it has on them. They have to understand that his changes are in and so not to duplicate his efforts - its hard to tell someone they've worked hard on a task only to find the rogue guy did it last week.

You're working in an agile environment though, and one thing I do know about agile is that it is designed to work for you, not against you. So you need to change the way you work to allow this kind of extra-curricular activity to happen. That means getting everyone's input and agreement, you cannot do this without their buy-in. Its vital. If the team doesn't like it, then the rogue guy stops doing it. End of. It isn't one guy doing what he likes, no matter how good his work might be, its a team effort all the way. The team comes first.

So you need to sit everyone down at the next planning meeting and discuss this, all team members need to decide to allow it, or to change your process to manage this kind of activity better.

Maybe you'll get a solution where everyone works on their favoured projects and brings them to the table (you can imagine the chaos to your delivery that'd cause :) which highlights the problem with it in the first place) or you can mandate area where each dev has automomy to develop whatever solution they like that is the 'contributed' similarly to how many open source projects work, or you can give everyone some free time to experiment (the old 20% time).


问:
Common Methodologies for Writing "Post-Mortem" Reviews
We recently added a relatively large feature to our product that involved the entire R&D department (with all the different teams within it).

This feature included UI development, server side development, and huge migrations of SQL schemes (and other stuff that I myself was not involved in at all).

The development process for this feature was chaotic - Front-End and Server teams were not synchronized, SQL migrations broke the DB, and product specifications were incomplete which meant that with every step of the way we found new issues with the initial definition, requiring changes to core concepts that the developers had relied upon.

All in all, a feature that was planned to be released within 10-14 days, took roughly 24 (intensive) days of development.

I was requested to write a report of 'What went wrong' (from my team's side - each team writes such a report from their pov).

What are the common methodologies for writing such reports, specifically in the field of software development?

Also - Is there some formal name for such reports?

EDIT & ANSWER:

Apparently, such a report/review-process is commonly referred to as 'Project Post-Mortem' (other names exist as well).

After figuring this out, I found these two resources that outline suggested methodologies for gathering the necessary data, organizing it, analyzing it, and formulating solutions for discovered issues (as well as some general information on these reviews and their purposes):

'A Defined Process For Project Post Mortem' -

http://www.csee.umbc.edu/courses/undergraduate/345/spring12/mitchell/readings/aDefinedProcessForProjectPostMortemReview.pdf

'Post-Mortem Reviews: Purpose and Approaches in Software Engineering' -   http://www.uio.no/studier/emner/matnat/ifi/INF5180/v10/undervisningsmateriale/reading-materials/p08/post-mortems.pdf

答:
Having done this many times, this is the format that I have used successfully in the past. The order these headings are presented in will also make a difference in how the report is received by management. Whenever possible, leave them with a good taste in their mouths.

This shouldn't have to be said, but... keep your language professional throughout the report.

What happened?

Describe what happened, both good and bad. Give details about each incident. Do not place blame. Keep opinions out of it. Imagine your self as a reporter who is telling the story of what occurred.

What went wrong?

This is the hard part. Admit to what you, your team, or other teams did wrong. Keep blame out of this! Just state the facts. "We (my team) made breaking changes to the database that caused delays for entire development group by X number of days."

What went right?

Part of the telling of this story should include where your team, or other teams, did the right thing. Communication of delays, changes, etc. "We added significantly more columns to tables X, Y, and Z. These columns will allow us to track something."

How do we improve the process?

This is where you start to display some opinions. You were asked what happened and what could be done to fix it. State your opinions supported with facts. "When we made the breaking database change, we should have implemented these changes on a separate development database."


问:
Why does the boolean type in C++ support ++ but not --?
Why does the operator -- not exist for bool whereas it does for operator ++?

I tried in C++, and I do not know if my question apply to another language. I will be glad to know also.

I know, I can use the operator ++ with a bool. It makes any bool equal to true.

```<code>bool b = false;
b++;
// Now b == true.
</code>```

Why can't we use the operator -- in an opposite way?

```<code>bool b = true;
b--;
// Now b == false;
</code>```

It is not very useful, but I am curious.

答: To partially cope with legacy code which used int or similar as its boolean type.


答:
In the old days of C, there was no boolean type.  People used the int for storing boolean data, and it worked mostly.  Zero was false and everything else was true.

This meant if you took an int flag = 0; and later did flag++ the value would be true.  This would work no matter what the value of flag was (unless you did it a lot, it rolled over and you got back to zero, but lets ignore that) - incrementing the flag when its value was 1 would give 2, which was still true.

Some people used this for unconditionally setting a boolean value to true.  I'm not sure it ever became idiomatic, but its in some code.

This never worked for --, because if the value was anything other than 1 (which it could be), the value would still not be false.  And if it was already false (0) and you did a decrement operator on it, it wouldn't remain false.

When moving code from C to C++ in the early days, it was very important that C code included in C++ was still able to work.  And so in the specification for C++ (section 5.2.6 (its on page 71)) it reads:

The value obtained by applying a postfix ++ is the value that the operand had before applying the operator. [Note: the value obtained is a copy of the original value ] The operand shall be a modifiable lvalue. The type of the operand shall be an arithmetic type or a pointer to a complete object type. After the result is noted, the value of the object is modified by adding 1 to it, unless the object is of type bool, in which case it is set to true. [Note: this use is deprecated, see annex D. ]

The operand of postfix -- is decremented analogously to the postfix ++ operator, except that the operand shall not be of type bool.

This is again mentioned in section 5.3.2 (for the prefix operator - 5.2.6 was on postfix)

As you can see, this is deprecated (Annex D in the document, page 709) and shouldn't be used.

But thats why.  And sometimes you may see the code.  But don't do it.

Title: Why does the boolean type in C++ support ++ but not --?

Body:
Why does the operator -- not exist for bool whereas it does for operator ++?

I tried in C++, and I do not know if my question apply to another language. I will be glad to know also.

I know, I can use the operator ++ with a bool. It makes any bool equal to true.

```<code>bool b = false;
b++;
// Now b == true.
</code>```

Why can't we use the operator -- in an opposite way?

```<code>bool b = true;
b--;
// Now b == false;
</code>```

It is not very useful, but I am curious.


问:
Is it okay to make coding style changes on an open source project that doesn't follow best practices?
Recently, I came across a number of open source Ruby (or majority of it was Ruby) projects on GitHub that when checked with a code analyzing tool like Rubocop, create a lot of offenses.

Now, most of these offenses include using double quotation marks instead of single quotes (when not interpolation), not following the 2 spaces per level rule, exceeding the 80 character line length rule, or using { and } for multi-line blocks.

[The] Ruby style guide recommends best practices so that real-world
  Ruby programmers can write code that can be maintained by other
  real-world Ruby programmers. ~ Source: Ruby Style Guide

Although they are small and easy to fix, is it appropriate to change the coding style of an open source project by fixing the offenses and making a Pull Request? I acknowledge that some projects, like Rails, do not accept cosmetic changes and some are just too large to "fix" all at once (Rails for example generates over 80,000 offenses when Rubocop is run - regardless, they have their own small set of coding conventions to follow when contributing). After all, the Ruby Style Guide is there for a reason together with tools like Rubocop.

People appreciate consistency so making these kinds of changes is kind of doing a good thing for the Ruby community in general, right?

[The author(s) of the Ruby Style Guide] didn't come up with all the
  rules out of nowhere - they are mostly based on my extensive career as
  a professional software engineer, feedback and suggestions from
  members of the Ruby community and various highly regarded Ruby
  programming resources, such as "Programming Ruby 1.9" and "The Ruby
  Programming Language". ~ Source: Ruby Style Guide

Isn't not following community coding style conventions and best practices basically encouraging bad practices?

答:
I have a couple of moderately successful .NET projects, and I have had a couple of PRs from people who appear to have gone through the code with ReSharper and StyleCop and "fixed" a bunch of stuff. I don't accept those PRs, for a couple of reasons:

While many of the changes are for the better, some of them negatively impact the code in some way, usually performance, and cherry-picking the good parts is too much hard work.

Even if all the changes were either benign or even beneficial, every change in every file in every commit needs to be reviewed, and again, it just takes too long.

That said, if anyone wanted to add some better error checking or doc comments, I'd accept that PR in a heartbeat.


问:
MIT License - possible to steal code?
Say your company has some closely-guarded internal software that happens to have an MIT License. Maybe it was based on MIT Licensed software but has been heavily modified over the years. Your company does not want to share it with the outside world. However, one day an employee decides to post the software up on GitHub against the wishes of the company. Is this legal? Does it violate the license?</p>

答:
However, one day an employee decides to post the software up on GitHub against the wishes of the company. Is this legal? Does it violate the license?

Posting the code doesn't violate the MIT license.

(And the flipside is that your company not publishing the code isn't a violation either ...)

However, it is almost certainly illegal for an employee to do that.  Your company probably has grounds for dismissing the employee, possibly suing him personally, and possibly reporting him to the police.  (If in doubt, ask a lawyer who is familiar with your national / state laws.)

And if the position is (really) as described, your company most likely has grounds for demanding that Github take down the offending code immediately:

Github DCMA takedowns: https://help.github.com/articles/dmca-takedown-policy

Github contact: https://github.com/contact

I would be extremely surprised if Github (or any other reputable software project hosting company) didn't take this kind of thing seriously.

Title: MIT License - possible to steal code?


答:
Get him back into the team

You should ask yourself (or better the team, including the overachiever):

Why is this behavior a problem?

Since you label the developer as a overachiever I guess his work is of good quality, so I gonna assume this isn't a problem.

But there seem to other problems:

The extra work is not tested properly

it is not documented

the rest of the team doesn't know it

the developer decides on the next thing to implement, not the PO

the developer doesn't get any feedback from the various stakeholders to incorporate in his work.

The next Why I would as is:

Why does the developer do it?

If at the end of the sprint isn't enough work left, there should be a team decision (including the PO) about what to tackle next. Why does the developer avoid this decision?

Once you have answer to these questions you can start answering your own question:

if it isn't a problem, let him do his thing. Although some people treat SCRUM as a religion, it shouldn't be like this.

More likely you have two problems in the team: the one(s) caused by the rogue developer and the one(s) triggering the behavior of the rogue developer. Find a way to solve the later and the first one will go away.


问:
Doing localization each Sprint
We need to support 5 languages for our product. This means that in order to have a potentially shippable product we need to translate all text new to the Sprint to all these  languages. It doesn't make sense to me because the text might change after a few Sprints during which the users will use the application and give feedback. So paying the translating company for translating text that will most likely change doesn't seem to be a wise decision. So what do you do with localization in Scrum?</p>

答:
Put simply this, like many process questions, comes down to a cost-benefit decision.

Quite a few of the practices described in the agile processes are about reducing the time spent in the "last mile" - this is an example of one of them.

Unlike practices with other aims (quality, correctness, etc), the practices aimed at ensuring you can release the product at any time have a net cost associated with them.

Ensuring that the product you are developing remains ready to release at all times has a cost that is not directly turned into benefit in the same way as ensuring it is at production quality.

I split those two aspects up as they have important differences.  For example:

Ensuring a product is well tested and bug free at all times has a cost, but the benefit is reduced time to fix bugs as they are found, produce new features, and decreased chance of large scale rework after bugs are found to be fundamental.  Almost all the time the tangible benefit will be greater than the tangible cost.

Ensuring a product is quick and simple to release has a cost but will will save you when you come to release, and the benefit is multiplied when you release frequently.  The more often you release the more likely that the cost will be realised in savings.  Again, the tangible benefit will generally be greater than the cost.

Ensuring a product is properly localised at all time has a cost, but will rarely result in a tangible cost benefit.  This is particularly true when a third party is involved as a long standing and ongoing relationship with a third party will generally cost more (in time and cost) than short bursts of piece-work.

The question is, are there other benefits that you gain that makes the cost worthwhile?

In this case the biggest benefit is likely to be the ability to reduce time taken from release candidate to actual release - it comes back to the 'last mile'.

One way to think about it is as stock in a warehouse.  Developing software is a way of building up stock - until that stock is on the shelves (the software is released) it does not generate revenue.  In some scenarios it even drops in value as it sits on the shelf.

So one question you can ask is "How long can we put up with our stock being on the shelf without generating value?".  For internal efficiency based systems this may be weeks, for innovative first-to-market products this might be hours. The shorter the time is, the more "ready for production" you need your software to be at all times.

Another question may be "How likely is it that our customer will decide at an arbitrary point to release the software?".  That is, in sprint 3 of 6 they decide that they like the software so much that they want it straight away.  If the situation is likely, how long will they be comfortable waiting?

Also, will seeing the software in its entirely localised state throw light onto questions that would otherwise remain unanswered?  Does seeing a translated version of the site generally make the customer change direction, or help validate the current direction?  Is there therefore value in seeing it earlier in your process?

Do you have other processes in the "last mile" that will hold you up longer?  If the only thing you're waiting for in the last 2 weeks are the translations then you will generate a bigger benefit than if would still have to wait 2 weeks for infrastructure to be upgraded, senior stakeholders to sign work off, etc.

Why do you find you need to do re-translations?  Is it because the requirements of the text change as the system develops - an inevitable consequence of change in the system.  Or is it more that people are unwilling to commit to a body of text early in the process when they probably should be able to.  Could continual translation focus their minds on ensuring correctness at all times?

Finally, how much extra will this all cost?  Have you looked at the amount of re-translation will be required?  What is the incremental cost of doing the translation piecemeal?  If this is a cost-benefit decision, you need not only to clarify the benefits, but work out the tangible cost.

So, my advice would be:

Work out the benefits in your particular situation.

Work out the costs.

Make the decision based on facts.

Title: Doing localization each Sprint


问:
Why does it seem so hard for non programmers to understand versioning?
In the past I have worked with designers, BAs and project managers, all who regularly produce project artifacts, yet very really do they understand the concept of versioning.  When I try to explain it to them (even in its most simple form of multiple differently named files) they seem to have some kind of mental block.  Why do you think this is?</p>

答:
My guess is that most people have a number of things to care about, so versioning doesn't make it to the top of their list. It's like insurance, the payback is of low probability and it's not free.

For the project artifacts that you outline, if there is only one person involved (e.g. a BA's document describing a calculation), they may quite reasonably assess the payback of keeping old versions to be zero.

Requiring more careful versioning of these kinds of things may introduce a hostile element into a project's atmosphere, as the reasons for doing it may be kind of adversarial, i.e. people are expecting to have arguments about old vs. new versions, so they want the old versions to be available as proof.


问:
Advantages and disadvantages of PHP/Ruby
I've been a front-end developer for about two years now, and I'm attempting to break into the server side of things. Ideally I'd like to work for a startup social network on the back-end side so I want to try and be as marketable as possible.

In my quest to learn a new scripting language I've dug myself into the PHP vs Ruby hole. What are the main advantages and disadvantages of the two? I would really appreciate words from experience with the two, but will settle for any experience.

Cheers.

答:
I've been a PHP developer for about five years, and in the last year I started looking into the Ruby (on Rails) world. I'm never going to go back. Here's why.

Inconsistency

I was displeased with PHP mostly because of its inconsistency: PHP was originally intended as a tool for amateurs, and it couldn't cope with the exponential growth it has seen over the years. In PHP you have random function names, random parameter order, random return values, random error handling and lots of other randomness.

Object-orientation

I was looking for a language that was truly object-oriented (i.e. a language where everything's an object) and that had a beautiful syntax. Ruby seemed to be the most appropriate option. Sure, it has its problems like every other technology (I don't really like this monkey-patching stuff, and Rails in particular seems to be quite slow compared to other frameworks).

Syntax

This is a subjective matter, but I'll put it anyway. I wanted my code to be expressive, concise, and beautiful. To me, PHP code has always been an ugly mess.

Here's an example: suppose that you have an array of objects and that you want to call a method on those objects and sum the returned values. Here's the PHP code for it:

```<code>array_sum(array_map(function($object) {
    $object->foo();
}, $objects));
</code>```

Not so bad, is it? Here's the same with Ruby:

```<code>objects.collect(&:foo).sum
</code>```

Now, this might seem a small improvement, but when you're writing lots of code I can assure you that it does make a difference.

Community

With the birth of modern web frameworks like Symfony (God bless the authors!) and Laravel this situation has slightly improved, but this point is still partially true.

The PHP community is terrible: most of them have no interest in improving the tools they're working with, and just care about getting stuff done as quickly as possible with as little effort as possible. The amount of wrong/outdated information about PHP out there is impressive.

That's why I've decided to maintain the Italian translation of PHP: The Right Way, even though I don't use PHP anymore. I know that PHP isn't going anywhere, at least for the next decade, and I'd like to improve all the terrible spaghetti code that I've read over the years.

What is PHP good for?

As I've said, PHP is a language designed for amateurs. All web hostings out there support it, and you can just upload your script through an FTP client and let it run. This works well for small applications that don't require a lot of design or maintenance.

All the other technologies, on the other hand, require a bit of setup and tweaking to work well, but it pays off in the long run.

Further reading

There are many rants out there about PHP. The best are:

PHP: a fractal of bad design

The PHP Singularity

Body:
I've been a PHP developer for about five years, and in the last year I started looking into the Ruby (on Rails) world. I'm never going to go back. Here's why.

Inconsistency

I was displeased with PHP mostly because of its inconsistency: PHP was originally intended as a tool for amateurs, and it couldn't cope with the exponential growth it has seen over the years. In PHP you have random function names, random parameter order, random return values, random error handling and lots of other randomness.

Object-orientation

I was looking for a language that was truly object-oriented (i.e. a language where everything's an object) and that had a beautiful syntax. Ruby seemed to be the most appropriate option. Sure, it has its problems like every other technology (I don't really like this monkey-patching stuff, and Rails in particular seems to be quite slow compared to other frameworks).

Syntax

This is a subjective matter, but I'll put it anyway. I wanted my code to be expressive, concise, and beautiful. To me, PHP code has always been an ugly mess.

Here's an example: suppose that you have an array of objects and that you want to call a method on those objects and sum the returned values. Here's the PHP code for it:

array_sum(array_map(function($object) {
    $object->foo();
}, $objects));

Not so bad, is it? Here's the same with Ruby:

objects.collect(&:foo).sum

Now, this might seem a small improvement, but when you're writing lots of code I can assure you that it does make a difference.

Community

With the birth of modern web frameworks like Symfony (God bless the authors!) and Laravel this situation has slightly improved, but this point is still partially true.

The PHP community is terrible: most of them have no interest in improving the tools they're working with, and just care about getting stuff done as quickly as possible with as little effort as possible. The amount of wrong/outdated information about PHP out there is impressive.

That's why I've decided to maintain the Italian translation of PHP: The Right Way, even though I don't use PHP anymore. I know that PHP isn't going anywhere, at least for the next decade, and I'd like to improve all the terrible spaghetti code that I've read over the years.

What is PHP good for?

As I've said, PHP is a language designed for amateurs. All web hostings out there support it, and you can just upload your script through an FTP client and let it run. This works well for small applications that don't require a lot of design or maintenance.

All the other technologies, on the other hand, require a bit of setup and tweaking to work well, but it pays off in the long run.

Further reading

There are many rants out there about PHP. The best are:

PHP: a fractal of bad design

The PHP Singularity


问:
C#/C++ GUI development without drag and drop?
I'm currently programming Java, I have played around with C++ before, but I have never touched GUI as I feel "cheat-like" when using its drag and drop system. I feel good and enjoy programming my own GUI like I do in Java, it feels much more rewarding.

Is there any way I can program the GUI for C#/C++ like in Java, without the drag and drop system, and if so could someone possibly recommend me a tutorial (A lot of the tutorials are using the drag and drop system)?

So far I have tried researching this and really can't find much explaining how I would do it.

答:
I don't know the GUI libraries for C++, so I'm going to talk about C# only. There, there are two common GUI libraries: the older Windows Forms (Winforms for short) and the newer Windows Presentation Foundation (WPF):

Winforms is primarily based on drag-and-drop graphical GUI editor. This editor is somewhat clumsy: for example, I wasn't able to figure out how to place a button at the bottom center of a window (exactly). So, using Winforms might be okay if you're creating non-resizable windows and if you're okay either with the limited tools that are available or with manually deciding the pixel position of every control.

What this editor actually generates is a .Designer.cs file containing code like:

```<code>this.button1 = new System.Windows.Forms.Button();

this.button1.Location = new System.Drawing.Point(124, 258);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "OK";
this.button1.UseVisualStyleBackColor = true;
</code>```

And you can write code like this into your normal .cs files too, bypassing the graphical editor (though I would probably use object initializer syntax here). But since there will be no IDE preview, it will probably take some time to make it look the way you want. And it still doesn't fix the issues that Winforms have, like window resizing.

WPF, on the other hand, while still supporting drag-and-drop to a limited degree, is all about writing structured code in XAML. By “structured”, I mean that controls are placed into groups called panels, which can themselves be in other panels, creating a structure of the window. And each panel decides the placement of controls in it, so by combining panels, you can achieve pretty much any layout, which is now resizable.

For example, to place two buttons at the bottom center of a window, you could write:

```<code><DockPanel LastChildFill="False">
  <StackPanel DockPanel.Dock="Bottom" Orientation="Horizontal" HorizontalAlignment="Center">
    <Button Margin="5" Width="100">OK</Button>
    <Button Margin="5" Width="100">Cancel</Button>
  </StackPanel>
</DockPanel>
</code>```

(The repetition of Margin and Width can be avoided, but it requires more advanced features of WPF.)

And while you're editing the XAML code, the IDE shows you the layout you're creating, so you get one of the main advantages of graphical editors too.

You can also write the same code in C# instead of XAML, but there's only rarely a reason to do that.

Body:
I don't know the GUI libraries for C++, so I'm going to talk about C# only. There, there are two common GUI libraries: the older Windows Forms (Winforms for short) and the newer Windows Presentation Foundation (WPF):

Winforms is primarily based on drag-and-drop graphical GUI editor. This editor is somewhat clumsy: for example, I wasn't able to figure out how to place a button at the bottom center of a window (exactly). So, using Winforms might be okay if you're creating non-resizable windows and if you're okay either with the limited tools that are available or with manually deciding the pixel position of every control.

What this editor actually generates is a .Designer.cs file containing code like:

this.button1 = new System.Windows.Forms.Button();

this.button1.Location = new System.Drawing.Point(124, 258);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "OK";
this.button1.UseVisualStyleBackColor = true;

And you can write code like this into your normal .cs files too, bypassing the graphical editor (though I would probably use object initializer syntax here). But since there will be no IDE preview, it will probably take some time to make it look the way you want. And it still doesn't fix the issues that Winforms have, like window resizing.

WPF, on the other hand, while still supporting drag-and-drop to a limited degree, is all about writing structured code in XAML. By “structured”, I mean that controls are placed into groups called panels, which can themselves be in other panels, creating a structure of the window. And each panel decides the placement of controls in it, so by combining panels, you can achieve pretty much any layout, which is now resizable.

For example, to place two buttons at the bottom center of a window, you could write:

<DockPanel LastChildFill="False">
  <StackPanel DockPanel.Dock="Bottom" Orientation="Horizontal" HorizontalAlignment="Center">
    <Button Margin="5" Width="100">OK</Button>
    <Button Margin="5" Width="100">Cancel</Button>
  </StackPanel>
</DockPanel>

(The repetition of Margin and Width can be avoided, but it requires more advanced features of WPF.)

And while you're editing the XAML code, the IDE shows you the layout you're creating, so you get one of the main advantages of graphical editors too.

You can also write the same code in C# instead of XAML, but there's only rarely a reason to do that.


答:
For C# winforms, I found this little tutorial: http://zetcode.com/gui/csharpwinforms/. It's mono-centric, so it uses the unix philosophy that programmers are actually capable of writing code. It should be enough to teach you the basic architecture - for more complex things you can use the MSDN Winforms documentation.

As for C++ - stay away from WinAPI and from MFC! They are nothing like the orderly component hierarchy that are Winforms, WPF, SWT, Swing or even old AWT! You'll only find there a messy swap of Hungarianly notated, macro configured, manually registered low level components with  weird names and poor documentation. Even if you prefer to write the GUI code yourself - if you happen to be forced to use the C++ native windows windowing libraries you should make an exception and stick with the GUI builders. That's the only way to preserve your sanity!

Or - try a third party library...

Title: C#/C++ GUI development without drag and drop?

Body:
I'm currently programming Java, I have played around with C++ before, but I have never touched GUI as I feel "cheat-like" when using its drag and drop system. I feel good and enjoy programming my own GUI like I do in Java, it feels much more rewarding.

Is there any way I can program the GUI for C#/C++ like in Java, without the drag and drop system, and if so could someone possibly recommend me a tutorial (A lot of the tutorials are using the drag and drop system)?

So far I have tried researching this and really can't find much explaining how I would do it.


问:
Lean Startup MVP: Quality Code or Quick and Dirty
Hello some programmers might know about the lean philosophy,

building a minimal viable product Lean Startup MVP.

I ask myself (when building Webapps):

"Should I put effort into writing good reusable code, testing etc."

or

"Write quick and dirty code. It just works. The customer does not care
  what kind of programming pattern you used etc. He/she just wants to use it."

So reading the article about a MVP is a bit paradox to me.
On the one hand it says:

"version of a new product which allows a team to collect the maximum
  amount of validated learning about customers"

on the other:

...begin the learning process as quickly as possible

So which actually has a higher priority? To me this is a trade-off between time and quality. Correct me if I did not understand it.

Thanks.

答:
Dirty code just gets dirtier, never cleaner. After a first release you rolled out very fast, you will have to continue to iterate fast, and roll out better and better releases. If you start from a mess, this will get increasingly harder and harder, to the point of impossible.

Dirty code is harder to test. So you will have even fewer automated tests than you normally would have had otherwise with clean code. And if you have fewer automated tests, you'll have higher chance of embarrassing, show-stopper bugs.

Dirty coding is a vicious cycle. Don't get sucked into it.


问:
What programming language generates fewest hard-to-find bugs?
What language, in your opinion, allows the average programmer to output features with the least amount of hard-to-find bugs? This is of course, a very broad question, and I'm interested in very broad and general answers and wisdoms.

Personally I find that I spend very little time looking for strange bugs in Java and C# programs, while C++ code has its distinct set of recurring bugs, and Python/similar has its own set of common and silly bugs that would be detected by the compiler in other languages.

Also I find it hard to consider functional languages in this regard, because I've never seen a big and complex program written in entirely functional code. Your input please.

Edit: Completely arbitrary clarification of hard-to-find bug: Takes more than 15 minutes to reproduce, or more than 1 hour to find cause of and fix.

Forgive me if this is a duplicate, but I didn't find anything on this specific topic.

答:
Since Excel is the most widely used DSL, I'll go with Excel. (excluding VBA of course)

It fits the bill:

It's always easy to reproduce (here's a spreadsheet - it's not working)

It's pretty easy to find the bug, as it's totally "functional" - start with the cell that's wrong and trace back all of its dependencies.


问:
How does working in a team (in an OO project) work?
I'm programming in Java, in a very OO style, by myself. Never had the chance to work with other programmers (I'm not a professional, at least yet).

Out of curiosity, I wanted to ask: How does working with a team on a project work, especially when working on an OO project?

How does splitting tasks work? How do you develop something that will succesfully work with something another programmer developed?  How and when do programmers communicate?

Thanks

答:
Hopefully I can help you a little, or at least point you in the right direction!

As a bit of a disclaimer though, it's a huge topic - and one that I really think takes "getting thrown in" to get a deep understanding of. That said, I'll give a quick run down of the two major issues:

The code and source control

Communications and some tips.

Regarding OOP projects specifically - I honestly can't see too many issues specific to OOP that aren't present elsewhere.

In fact, I think OOP-style programming is incredibly suited to team development. One key ethos of OOP is that I shouldn't know all the details about every object I interact with: I just need to know what it can do, and how I can get it to do that.

The abstractions that OOP can provide are awesome in a team.

Source Control

There needs to be a central place for the project to be stored, and one which allows multiple developers to access the codebase at any one time. This is where systems such as Git (or SVN) come in to play.

I can only speak specifically about Git, as I've never used SVN - however I gather they are similar but with different terminology.

Using Git I can create a repository with all the source code for a given project, and then allow my team to access to the repository. For every feature or bug fix that is then made, individual developers can create their own "branch" which means development can happen on parallel tracks.

Once a feature or fix is completed, it can then be "merged" back in to the main project's codebase. Any "conflicts" can then be detected by Git and resolved at the source level by the developer responsible.

I'm not sure if you'll have used Git before, but it can seem quite complex at first - but thanks to its recent popularity (in part to Github) there is a whole wealth of tutorials and resources out there.

If you haven't used it before, then I recommend signing up to GitHub and getting a feel for it that way! (Alternatively, Bitbucket is a similar alternative, but it allows you to have private repositories for free.)

Git Flow is an excellent Git based work flow that is incredibly useful for teams. Like Git in general, once you work with it for a while it gets difficult to imagine working in a team without it!

Communications

Once you get past all the technical barriers, you really come down to the fundamental issue that plagues most projects (technical or not) - and that's communication.

The whole team needs to be aware of who is doing what, when they're doing it and what it affects.

Responsibility needs to be clearly defined

This is obvious, but most projects will use some form of ticketing system - where any feature requests or bugs are logged, and then subsequently assigned to a specific member of staff. (JIRA, Unfuddle etc.) Often these are built in to the source control system which makes life a little simpler. (BitBucket and GitHub both provide issue tracking for Git repositories hosted with them.)

This stops, or helps prevent at least, developers accidentally working on the same issues.

This isn't a complete fix though; you still need to ensure developers are aware about other developers responsibilities. I know in the past that I've fixed other issues that I've stumbled across in the course of fixing a specific bug, purely because it makes sense. ("Well, I'm already here. This could do with a refactor and perhaps I can check for any other issues.") Then I've had to apologise to other developers as they were working on those other issues that I've fixed - wasting both of our time.

In general those, these issues can be fixed by...

Regular meetings

Some project management/development methodologies dictate specific communication methods or meeting intervals. In general, the most productive systems I have seen have been morning stand-up meetings where everyone in a team will give a quick run down of what they're doing - if you limit this to development team members only and have clear guidelines about what to communicate then these can be incredibly effective. I've always tried to stick to:

I am working on X,

To achieve/fix Y,

Which involves modifying/amending Z.

Other team members can immediately take in that "Fergus is working on fixing that bug which was logged the other day, however that means he's working on some code that I need to look at - I'll check with him before I make any changes.".

Architectural meetings

I recently worked with a great team that had a fortnightly "tech chat", where bigger/architectural issues would be discussed. Every member of the team had time to understand the bigger issues facing the project and could discuss potential fixes.

I personally loved this, I didn't contribute much as I was quite new to the project - but being able to listen to the discussions gave me a lot of insight; pretty soon I could understand the project as well as individual thinking styles.

Communication is the one issue that can bring any team down. Technical or not, if people aren't aware of the bigger picture then there is a greater chance that they will fail.

Other issues

It's good to ensure everyone has the same configuration or style when working in a team. What do I mean?

Configuration

If you're working on a Java project - then perhaps ensuring (for development environments at least, certainly not for testing.) JVM versions are common amongst the team may be a good idea? Then IDEs. It helps majorly if the whole team is using Eclipse or NetBeans or your IDE of choice.

On a web project it might be that all the developers need a specific stack; with specific Apache or PHP versions.

Thinking of factors like this just allow the team to "gel" a bit quicker in my mind.

Style

Tabs vs spaces? CamelCase or spacing_with_underscores? As small as these questions may be when you're working alone, when you're working with a bigger team you really want to strive towards a common style.

In fact, you shouldn't really be able to tell who wrote a specific section of code - you should just know that it belongs.

This is why many open source projects openly publish source code format guidelines/styleguides - for an idea of what these contain, take a look at the Google StyleGuides for their own open source projects.

Tasks and Unit Tests

This isn't limited to teams, but I'm going to quickly touch upon this for one reason in particular: it makes team life a lot easier.

If you have a complex workflow with lots of dependencies, or a long build process - then often it's useful to automate this using a task runner. For web projects GruntJS is awesome, although coming from Java I guess Apache Ant may be quite similar.

As an individual I use GruntJS to build my site before I deploy it to my FTP server - one Grunt command is all I need for my CSS/Sass to be compiled and minified, my assets to be compressed and then my files to be uploaded.

As a team member though, I can use GruntJS to check that I haven't broken any tests - and that I haven't introduced any bugs by not being fully aware about other parts of the project. This is of course, additional to the benefits that it affords me as an individual developer.

I can also use it so that I can clone a project using my fancy source control package (Git) - and run one command to install all my dependencies. This is a big plus, as the time spent getting a new developer in to the position where they can actually begin developing can be quite large - without even considering the time it takes to get used to an unfamiliar codebase.

Documentation

The best projects I have seen have had documentation (and often quite excessive.) aimed at developers. These kind of documents may explain things like:

1. The development environment:

"We're currently deploying to a server running a LAMP stack, as such developers should be targeting the versions outlined in.."

2. Work flow

"All features are to be developed on a 'feature/*' branch and merged in to the 'testing' branch prior to being considered as release ready."

3. Responsibilities in the team:

"For database issues, talk to Steve. For platform issues, talk to David."

4. A "pipeline" for the future

"When developing new code remember that as of June 2014 we wish to implement x - legacy code may need to be reviewed before this occurs."

Examples

It may be worth looking at the work flow of an open source project to get a feel for how it works - whether that be an established one with their own workflow (often heavily documented), or one of the many examples on GitHub.

A final word of warning

If you find yourself working in a team that manages to do all of this right.. you'll hate being anywhere else..! Take it from me, once you've experience a good team then suddenly issues elsewhere can really drag you down. (That's a story for another post however!)


答:
The question is why does the internal software have an MIT license. Only the original software the code was based on would be required to be MIT licensed. New code and modifications could be copyrighted with all rights reserved.

If the whole project is not meant to be MIT licensed then it should be made clear that only the original code is under the MIT licence and that the rest is all rights reserved.

See the answers to this question.
mit-license-why-isnt-it-considered-viral

Title: MIT License - possible to steal code?

Body: Say your company has some closely-guarded internal software that happens to have an MIT License. Maybe it was based on MIT Licensed software but has been heavily modified over the years. Your company does not want to share it with the outside world. However, one day an employee decides to post the software up on GitHub against the wishes of the company. Is this legal? Does it violate the license?</p>


问:
Whats a good structure to save and retrieve locations of images?
I got a java-ee application, where I collect informations about movies. Im my backend I provide data like the name, description, genre and a random uuid.

I also got lots of related files, which are stored on a file server. Including some screenshots, the dvd or bluRay cover and video trailers.

My current approach is:

When saving the files to the fileserver, I retrieve the movies random uuid (which is the primary key btw.). I then rename the files screenshot_[UUID]_1, screenshot_[UUID]_2 ... etc.

Now, there are lots of other ways to handle this, like saving all filenames in a database or creating a dir structure on the fileserver for every uuid and, e.g., return all images in the "[uuid]/screenshots" folder via REST.

I expect about 30k requests a day, so the service has to be pretty performant.

Whats the best way to solve this?

答: The best way to solve this is to forget about any micro-optimizations like "use of a directory structure" vs. "each file name containing all the UUID" (though you should check if there is a limitation in the file system you are going to use about the number of files in one directory). Implement a simple solution which fits well into your existing infrastructure, create some sample requests and measure if the solution is fast enough.  If not, measure which part of your solution is exactly too slow, then improve that part. Everythig else is most probably premature optimization.


答:
This violates a tenant of Scrum because the team is not deciding the work in the sprint.  This is a scrum team.  The team needs to discipline this programmer if discipline is to be handed out.

Another issue this creates is that it screws with the team's velocity.  Out of band work does not count towards velocity and burn down.  So, this out of band work gets done, the team is averaging 50 points in velocity, but more than 50 points gets done.  The product owner will see this and demand higher velocity in the next sprint.  Velocity that might not be possible.

The team (not the PO or the ScrumMaster) needs to address this with the rogue programmer.


答:
Some of the other answers have suggested that the "overachieving" developer is "rogue" or "violating the principles of Scrum". This is incorrect and this developer should be encouraged (although you should not ask people to work on anything specific in this extra time, but you could make suggestions and help foster ideas).

There is nothing in Scrum to prescribe how people work and anything extra he did would naturally be incorporated into the velocity of the team.

His work should be brought in to the product backlog and estimated in the next planning meeting. If you can't predict what the remaining effort is straight away you should time box some time of the sprint to figure it out (that is, a Spike).

Interesting you describe the developer as "overachieving", I assume this means he is adding a lot more value than the other team members.

The difficulties doing extra work creates implies there is something sub-optimal (or maybe even dysfunctional) in your team.

If this is the case, you should ask yourself why is he achieving so much more, with presumably only a little bit of extra effort?

Is it possible for you enable the rest of the team to achieve more?

I've seen the situation where teams have been micro-managed, potentially over prescriptive user stories, definition of done, which ends up being stifling to developers. Is this developer doing the work that he wants to? I'm assuming he is making good decisions. Would working this way in the working week help the rest of the team too?


问:
secure photos on server
I would like to hear advice from the more experienced developers. The project is now in the design stage. It's mobile application and a simple web application. Content is pictures, comments, personal correspondence.

Pictures can be quite personal. Need a very serious attitude to security.

The question is simple: where to store photos and how to secure it?

I think it's will be in the following way:

1. User make some photo. Via SSL the application sends photo to the server.

2. The server recieve photo, encrypt it and store somewhere.

Also, via app the user can see all own photos.

1. Request to server for photos.

2. Server decrypt stored photos and send via SSL to client.

I need some technical advices: where to save images, I know that database is quite slow for this case, which algorithms use for encrypt/decrypt, what about cache. It will be highload project and performance is very important.

Mobile application is planned on cross-platform framework like phoneGap, Titanium. On the server is .NET. But it is planned. I also consider full stack frameworks for javascript.

答:
I would recommend using Amazon S3.

They have a pretty decent API for .net and I use it for all my image storage.

You can set privacy on an image "bucket" which means without accessing with the user/password or token they will be perfectly secure.

Also of course, you get all the cloud rednundancy and location based hosted services, also would be great if you are going to be using it with mobile and web, as you won't be restricted by having your images stuck on a web server.

http://aws.amazon.com/s3/faqs/

Title: secure photos on server


问:
What negative consequences can arise from this language design rule?
Clarification: the rule is meant to prevent accessing variables that are not declared yet.

Clarification 2: the rule mandates that the compiler follows calls to functions which are defined in the same scope as the call and happen before the actual definition (forward referencing)  - making the compiler much alike an interpreter.

I'm thinking about a fictional programming language that behaves similar to JavaScript when declaring functions: that is, when using the function keyword to create named functions, they get "hoisted" to the top of the scope and can be used anywhere where their name is visible.

For example, the following is legal:

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

However, there is a potential problem: what if the function f uses a variable x, that is defined after the call, like here:

```<code>f();
var x = 1;
function f() { console.log(x); }
</code>```

In case of JavaScript, this is also legal, because variables are hoisted as well - the program gets essentially transformed into something like this:

```<code>var x;
function f() { console.log(x); }

f();
x = 1;
</code>```

And therefore just prints undefined.

In my fictional language, variables wouldn't get hoisted, which means that the example before would produce an error. The rule concerns how this error is generated:

Functions are visible for the entire block in which they are defined,
  but it is illegal to call a function that accesses a variable declared
  after the call.

This means that each time the compiler for this language would encounter a function call, it would have to check if the function is defined in the current scope, and if it is, check if it accesses variables in the current scope that are declared after the call.

The reason for this rule is that it makes no sense to access variables before they are declared. Hoisting the variables to the top of their scopes like JavaScript does is a hack that only leaves room for error! This is why I believe it must not be done, but such situations should be detected and treated as errors (because they are, you're referencing something that doesn't chronologically exist yet).

I'm looking for reasons why this is a bad rule, i.e. results in complications or inconsistencies.

The reason I suspect that the rule is a bad one is that it does not exist in the Scala language. Scala solved this problem with a much more general rule:

The scope of a name introduced by a declaration or definition is the
  whole statement sequence containing the binding. However, there is a
  restriction on forward references in blocks: In a statement sequence
  s[1]...s[n] making up a block, if a simple name in s[i] refers to
  an entity defined by s[j] where j >= i, then for all s[k]
  between and including s[i] and s[j],

s[k] cannot be a variable definition.

If s[k] is a value definition, it must be lazy.

UPDATE:

For the time being I have adopted Scala's approach.

This approach is a more general version of my rule: it will catch all illegal accesses, but also some that are not - this is a tradeoff that I'm willing to make since I think that my rule may be too complicated or even impossible to implement.

Here's the rephrased/explained rule from Scala:

Variables cannot be forward-referenced, but lazy values, functions defined with def (which are just syntax sugar for lambdas assigned to (lazy) values, might even remove them as Doval suggested), classes, and modules can.

The restriction is that between the reference and the declaration (inclusive), there must be no variable definitions, because they might be altered by the entity being referenced before they are introduced to the program.

答:
The term "before it is declared" is not really well defined. For example, the following is fine in Haskell:

```<code>let
   f x = x + y
   y = something else
in f 42
</code>```

What I want to say is: Just because "f" appears earlier in the code when you read it top down, does not mean "it is defined before". On the contrary, in Haskell and related languages all items in the same declaration group are considered defined (or bound) at the same time.

To answer your question, the negative consequence for the user of your fictional language is that, if you enforce "order of definition" in an arbitrary way, it must order the definitions manually. Another thing that follows from that is that mutually recursive definitions are not possible, or that you handle things with function types differently than things with other types, without good reason.

Body:
The term "before it is declared" is not really well defined. For example, the following is fine in Haskell:

let
   f x = x + y
   y = something else
in f 42

What I want to say is: Just because "f" appears earlier in the code when you read it top down, does not mean "it is defined before". On the contrary, in Haskell and related languages all items in the same declaration group are considered defined (or bound) at the same time.

To answer your question, the negative consequence for the user of your fictional language is that, if you enforce "order of definition" in an arbitrary way, it must order the definitions manually. Another thing that follows from that is that mutually recursive definitions are not possible, or that you handle things with function types differently than things with other types, without good reason.


问:
Is it ok for services to reference one another?
I have a service that needs information implemented by another service in the same layer. Is it good practice for one service to take a dependency on another service in the same layer?</p>

答:
Yes. I have seen architectural diagrams of SOA (Service Oriented Architecture) where exactly this happens. A service should be written in such a way that it doesn't care if user is calling it, a service in the 'same layer', or it is being combined into a composite service.

The Open Group SOA Reference Architecture diagram shows services calling services in the 'same layer': Figure 22-2 (http://pubs.opengroup.org/architecture/togaf91-doc/arch/chap22.html)

The Open Service Integration Maturity Model (OSIMM) is also a good diagram, the link is talking about IBM Process Server but Kim Clark and Brian Petrini give a really good explanation: Figure 1 (http://www.ibm.com/developerworks/websphere/library/techarticles/0904_clark/0904_clark.html)


答:
I use my services within each other. This way I am able to reuse my service methods, instead of copying algorithms all over the layer.

In my experience, one thing to be aware of is circular dependency.

When initializing a service class, say in the constructor, initializing other service object fields may lead to never ending circular calling if the field also depends on the initializing service.

When calling a method, a service method may call another service call and that may also call another service method which can lead to circular call again.

Title: Is it ok for services to reference one another?

Body: I have a service that needs information implemented by another service in the same layer. Is it good practice for one service to take a dependency on another service in the same layer?</p>


问:
How do I explain to my boss what a 'Virtual Machine' means?
Most probably my boss didn't write a single word on a keyboard in his entire life.

He saw computers and he has a cell phone. He is a smart man.

How can I explain to him what a 'virtual machine' is?
(VM as in VMWare + virtual Box, not the VM as in Java, LLVM, .NET)

One of the reasons for asking this is that I want to tell him that having a Linux VM to connect to internet with a Windows host is safer than connecting directly to Windows.

答:
There are three possible ways.  You may need to use all of them.

By definition.

"A virtual machine is a program that simulates a physical computer."

By example

A VM is kind of like those Emulators that let you play old NES games on your current PC.

Smartphone developers use VM's, so that instead of buying a hundred smartphone models they can just test on a hundred free VM's.

By demonsration

Here, this is a virtual machine ("Fire up VirutalBox on your desktop.")

I'm flabbergasted as to why you thinking running Linux through a VM on a Windows host is somehow more secure than just installing it on hardware.  Did you mean to say the other way?  Or are you testing Linux distributions from unknown companies that may have black-hat backdoors in them?


问:
How can I capture an incoming email with ASP.net-mvc?
I would like to write a web system that can capture and parse incoming emails, traditionally the web system I write are asp.net-mvc, running in a cloud hosted environment like AppHarbour or Azure.

How can I leverage those (and potentially my DNS) to acheive this?

答:
Unfortuantely this isn't quite easy nor straightforward. Your typical ASP.NET app listens for HTTP requests, not incoming email requests which land on a different port and use an entirely different protocol than your typical HTTP application understands.

The best bet is to leverage some sort of email recieving service which is capable of translating your incoming email into a HTTP request an ASP.NET app running on azure or appharbor could understand.


问:
Keeping database connection
Say you are developing a desktop application that extensively uses a database, should you have one handle for the database that the entire app references? Or should you open a connection when you need data, get the data, and then close the connection when data isn't necessary. </p>

答:
You have already listed the two major schools of thought about database connections. Each has positive and negative aspects.

Open a connection and leave it open for the duration of the application

Positive: This works better in a fully connected environment (desktop or server application primarily). You limit the number of connections to your database to a minimum. You don't have the overhead of making the connection and shutting it down every time you want to execute a query.

Negative: This doesn't work well in a disconnected environment or one where the connection is likely to be severed midstream frequently.

Open a connection long enough to do what you need

Positive: This works best in an environment where you are needing data infrequently. You free up a connection for another process in a heavily utilized server. If you get disconnected midstream, just restart the query process with a different connection.

Negative: There is an overhead for making a connection to the database every time. It gets worse when you have SSL and/or VPN in addition to the connection. Database connection pooling can help with this. You have to be aware that INSERTing or UPDATEing data can put you in a race condition with another user/process. It is easy to mitigate, but will require additional design and coding steps.

For a desktop application, I would normally recommend using an open connection. You will still have to have error handling in place for when the connection fails (someone restarts the database on you).

All of the negatives I have listed can be mitigated or limited somewhat by designing your application with error situations in mind (e.g., before you execute a query, you insure the connection is still open).

Title: Keeping database connection


答:
Don't get caught up explaining the technical detail - that's why your boss has hired you.

An explanation of virtualisation in this situation is as simple as "it allows you to run multiple computers inside one".

The benefit your boss will care about, and understand a lot better - is that virtualisation allows you to maximise utility on the servers you already have (ie: potentially lower cost to the business).

There are more comprehensive arguments to this, but from OP it sounds like virtualisation has very little to do with what you're trying to solve (put a security/nat/firewall appliance between the internet and some guests).

Title: How do I explain to my boss what a 'Virtual Machine' means?

Body:
Most probably my boss didn't write a single word on a keyboard in his entire life.

He saw computers and he has a cell phone. He is a smart man.

How can I explain to him what a 'virtual machine' is?
(VM as in VMWare + virtual Box, not the VM as in Java, LLVM, .NET)

One of the reasons for asking this is that I want to tell him that having a Linux VM to connect to internet with a Windows host is safer than connecting directly to Windows.


问:
How to slow down your computer (for testing purposes)?
As most people agree, encouraging developers to make  fast code by giving them slow machines is not a good idea. But there's a point in that question. My dev machine is fast, and so I  occasionally write code that's disturbingly inefficient, but that only becomes apparent when running it on other people's machines.

What are some good ways to temporarily slow down a turbocharged dev machine? The notion of "speed" includes several factors, for example:

CPU clock frequency.

Amount of CPU cores.

Amount of memory and processor cache.

Speed of various buses.

Disk I/O.

GPU.

etc.

答:
The way to spot significant algorithm inefficiency is to profile you code.  The way to catch memory overuse is to first understand how much memory your target uses have, and then design accordingly, and regularly test in that environment.

If you are writing threaded code, testing on multiple machines with differing CPU speeds will help highlight specific timing related bugs in your thread handling, but aggressive unit testing of thread logic is a must.


答:
you could use "chain of responsibility" design pattern to achieve this.

http://www.blackwasp.co.uk/ChainOfResponsibility.aspx