问:
How to set up something like an integration server that measures the quality of code and reject the code if the score is below a certain number?
Even if I don't like enforcing people to do things (and I believe that it may decline the productivity and cause anger), I really want to enforce good coding style.

Is there a way to set up something like an integration server that measures the quality of code (for example it runs resharper or some other static checker) and reject the code if the score is below a certain number?

Also, do you think this is a good approach?

答:
Style

If you're talking purely about style, then it's an excellent idea. Style rules are objective and so are the results: if style rule tells that the team uses four spaces to indent the code, a line of code which is indented with two spaces is a mistake. Clear enough.

Note that while style rules are objective (example: "The code is indented using four spaces"), choosing among contradictory rules is subjective and often hard (example: "Why four spaces is better than two? I disagree, ...")

DON'T invent your own set of rules. Chances are you'll spend weeks drafting them, and months discussing them with your team. Parkinson's Law of Triviality works very well here: since most style decisions have no effect on the project and since there is no single right answer, the team can easily spend an enormous amount of time discussing style rules, or simply be blocked and stop the project.

DO pick an existent set of rules among popular ones. For C#, it's Microsoft's style provided through the default rules of StyleCop. For JavaScript, it might be Google's style guide. Other languages have other well or not well established standards which may or may not be commonly used.

Picking an existent set of rules mitigates the risk of long, useless arguments. We use four spaces because Microsoft's official style says it's four. That's all. End of discussion.

It has an additional benefit: you can more easily find a person who either uses or at least knows the well-known style, compared to the chance to find a person who uses or knows the style you invented yourself (unless you work for Google or Microsoft).

The last benefit: there are more chances to find a tool which already checks those popular rules. For example, StyleCop for C# or Google Closure Linter for  Google JavaScript Style Guide.

The fact that style rules are objective also means that computers are good at making the checking, while humans, not so.

DON'T expect people to check style themselves. They won't, because it's boring. Some may be inclined to match a given style and encourage others to do it, while others would try to behave as cowboy coders. In both cases, they will let a few errors into the repository, and, often under time pressure, would be inclined to stop checking.

DO use a style checker through a pre-commit hook: no non-compliant code gets in, so it's easy to keep the code base clean.

Note that setting style rules for an existent project which had no rules until now is a specific case which should be treated specifically.

DON'T set a pre-commit hook for an existent project: setting such pre-commit hook on a code base which already contains a few thousands of errors would be a disaster both for the schedule and the morale of the team.

DO fix style errors progressively in an existent project, and only then set the pre-commit hooks.

Code quality

If you're talking not about style, but about code quality, any automatic rejection of code based on scores is out of question.

Code quality is a subjective measure and it involves a huge amount of factors. Measuring one aspect of it and enforcing the metrics through Continuous integration is a recipe for a disaster.

Example: a pre-commit hook makes it mandatory to limit the depth of the methods to two. A member of a team have written a method which is clear, readable code:

```<code>/**
 * Computes the actual price, based on the options which were selected during the check-in.
 */
public PriceInfo compute()
{
    Price amount = Price.createZero(Currency.Dollars);
    foreach (CheckInOption option in this.Options) {
        foreach (OptionVariant variant in option.Variants) {
            if (variant.Enlisted) {
                amount.add(variant.Price);
            }
        }
    }

    return amount.toImmutable();
}
</code>```

Pair programming being used, the other programmer agrees the code is good enough. Developers commit the code and prepare to leave for a weekend, but a pre-commit hook rejects it, because it has a depth of three. What would be the reaction?

Chances are, the angry developer would split the method in two, creating a useless private method with not-so-clear name and the XMLDoc which paraphrases the method name.

```<code>/**
 * Computes the actual price, based on the options which were selected during the check-in.
 */
public PriceInfo compute()
{
    Price amount = Price.createZero(Currency.Dollars);
    foreach (CheckInOption option in this.Options) {
        this.addOption(option, amount);
    }

    return amount.toImmutable();
}

/**
 * Adds options to price.
 */
private void addOption(CheckInOption option, Price price)
{
    foreach (OptionVariant variant in option.Variants) {
        if (variant.Enlisted) {
            amount.add(variant.Price);
        }
    }
}
</code>```

Now, the code is ugly as hell, and one can spend half an hour explaining how wrong it is. But the static checker doesn't complain any longer, the commit can be done, and developers can leave for a weekend; wasn't that the goal?

Same rule, another example:

```<code>for (var x = 0; x < matrixSize.x; x++) {
    for (var y = 0; y < matrixSize.y; y++) {
        for (var z = 0; z < matrixSize.z; z++) {
            // Do cool 3D stuff here.
        }
    }
}
</code>```

Now imagine the exact terms the developer would pick when forced to modify this code to match the depth-two rule?

Automated enforcement of code quality has three issues:

Chose one metric, and people will concentrate themselves on this metric, instead of the code quality itself. In the first example, the fact that I needed to concentrate on depth level caused me to omit readability, proper naming, proper commenting, proper use of object oriented programming, etc.

Many things cannot be checked automatically with today's technology. In the first example, no today's checker would be able to tell that the newly created comment is useless (and even if it could, it would be easy to game).

Hard limits are too rigid. In the second example, any code reviewer would accept a depth of three, because it simply doesn't matter here. Most code reviewers would also accept three depths in the first example, while suggesting to refactor the code later if needed to get cleaner and more object oriented design.

Code quality is too complex and subjective to be done automatically; keep this task for people, though code reviews. This doesn't forbid you from gathering metrics for statistical purposes during nightly builds.

I myself use some code quality tools, including Visual Studio's Code metrics. I often noticed that my refactoring lead to drops of one or several criteria used by Code metrics, while the code itself was becoming more readable and maintainable. Those are only metrics: objective and reliable, but also blind and rigid. Use them as hints, not as something which tells you what to do.

You can set long-term goals, and use different techniques to encourage people to attain them. Fixing a goal of 90% code coverage for January 2015 and displaying in the hall of your company the photos of the developers who achieved the best code coverage according to the last commit stats is one thing. But forcing everyone to have 80% code coverage right now would only push developers to add useless tests of boilerplate code just to be able to get back to work, especially if there are good reasons for some teams to have less than 80% code coverage.

Personal considerations

Enforcing anything for the sake of doing it is usually a bad idea. Ask yourself:

What is the primary issue?

Is enforcing something the best solution?

Examples:

You want to force developers to increase the code coverage. What is the primary issue? The fact that the number of bugs is too big compared to your expectations? Was your expectations realistic? While the number of bugs correlates well with testing, are there bugs essentially because of the lack of testing? Or because there are no written requirements, and developers don't understand the needs of end users? Or because you hired programmers which are not skilled enough? Or maybe because there is too much noise at the workplace?

Let's assume that the only thing you can do to decrease the number of bugs is to increase the number of tests. Ask yourself, why aren't programmers writing enough unit tests in the first place? Maybe it's because management constantly pushes them to release faster? Maybe because they don't understand the pleasure of TDD? Maybe because they believe that it's up to Quality Assurance folks to write those tests?

You want to set up some code quality checks. What's the primary issue? The gap between the code written by best and worst programmers in the team? Wouldn't pair programming help? Do you do code reviews? Can't you simply fire programmers who are not skilled enough, and hire better ones?

Let's assume you can't fire anyone and you can't do code reviews or pair programming. But can't you simply talk with the problematic programmers, explain them the issues, listen to their point of view? What if they are talented guys, but just hate to write PHP code? What if they simply don't want to write high quality code, because management already cancelled two previous projects, and they don't believe this one would survive?

Body:
Style

If you're talking purely about style, then it's an excellent idea. Style rules are objective and so are the results: if style rule tells that the team uses four spaces to indent the code, a line of code which is indented with two spaces is a mistake. Clear enough.

Note that while style rules are objective (example: "The code is indented using four spaces"), choosing among contradictory rules is subjective and often hard (example: "Why four spaces is better than two? I disagree, ...")

DON'T invent your own set of rules. Chances are you'll spend weeks drafting them, and months discussing them with your team. Parkinson's Law of Triviality works very well here: since most style decisions have no effect on the project and since there is no single right answer, the team can easily spend an enormous amount of time discussing style rules, or simply be blocked and stop the project.

DO pick an existent set of rules among popular ones. For C#, it's Microsoft's style provided through the default rules of StyleCop. For JavaScript, it might be Google's style guide. Other languages have other well or not well established standards which may or may not be commonly used.

Picking an existent set of rules mitigates the risk of long, useless arguments. We use four spaces because Microsoft's official style says it's four. That's all. End of discussion.

It has an additional benefit: you can more easily find a person who either uses or at least knows the well-known style, compared to the chance to find a person who uses or knows the style you invented yourself (unless you work for Google or Microsoft).

The last benefit: there are more chances to find a tool which already checks those popular rules. For example, StyleCop for C# or Google Closure Linter for  Google JavaScript Style Guide.

The fact that style rules are objective also means that computers are good at making the checking, while humans, not so.

DON'T expect people to check style themselves. They won't, because it's boring. Some may be inclined to match a given style and encourage others to do it, while others would try to behave as cowboy coders. In both cases, they will let a few errors into the repository, and, often under time pressure, would be inclined to stop checking.

DO use a style checker through a pre-commit hook: no non-compliant code gets in, so it's easy to keep the code base clean.

Note that setting style rules for an existent project which had no rules until now is a specific case which should be treated specifically.

DON'T set a pre-commit hook for an existent project: setting such pre-commit hook on a code base which already contains a few thousands of errors would be a disaster both for the schedule and the morale of the team.

DO fix style errors progressively in an existent project, and only then set the pre-commit hooks.

Code quality

If you're talking not about style, but about code quality, any automatic rejection of code based on scores is out of question.

Code quality is a subjective measure and it involves a huge amount of factors. Measuring one aspect of it and enforcing the metrics through Continuous integration is a recipe for a disaster.

Example: a pre-commit hook makes it mandatory to limit the depth of the methods to two. A member of a team have written a method which is clear, readable code:

/**
 * Computes the actual price, based on the options which were selected during the check-in.
 */
public PriceInfo compute()
{
    Price amount = Price.createZero(Currency.Dollars);
    foreach (CheckInOption option in this.Options) {
        foreach (OptionVariant variant in option.Variants) {
            if (variant.Enlisted) {
                amount.add(variant.Price);
            }
        }
    }

    return amount.toImmutable();
}

Pair programming being used, the other programmer agrees the code is good enough. Developers commit the code and prepare to leave for a weekend, but a pre-commit hook rejects it, because it has a depth of three. What would be the reaction?

Chances are, the angry developer would split the method in two, creating a useless private method with not-so-clear name and the XMLDoc which paraphrases the method name.

/**
 * Computes the actual price, based on the options which were selected during the check-in.
 */
public PriceInfo compute()
{
    Price amount = Price.createZero(Currency.Dollars);
    foreach (CheckInOption option in this.Options) {
        this.addOption(option, amount);
    }

    return amount.toImmutable();
}

/**
 * Adds options to price.
 */
private void addOption(CheckInOption option, Price price)
{
    foreach (OptionVariant variant in option.Variants) {
        if (variant.Enlisted) {
            amount.add(variant.Price);
        }
    }
}

Now, the code is ugly as hell, and one can spend half an hour explaining how wrong it is. But the static checker doesn't complain any longer, the commit can be done, and developers can leave for a weekend; wasn't that the goal?

Same rule, another example:

for (var x = 0; x < matrixSize.x; x++) {
    for (var y = 0; y < matrixSize.y; y++) {
        for (var z = 0; z < matrixSize.z; z++) {
            // Do cool 3D stuff here.
        }
    }
}

Now imagine the exact terms the developer would pick when forced to modify this code to match the depth-two rule?

Automated enforcement of code quality has three issues:

Chose one metric, and people will concentrate themselves on this metric, instead of the code quality itself. In the first example, the fact that I needed to concentrate on depth level caused me to omit readability, proper naming, proper commenting, proper use of object oriented programming, etc.

Many things cannot be checked automatically with today's technology. In the first example, no today's checker would be able to tell that the newly created comment is useless (and even if it could, it would be easy to game).

Hard limits are too rigid. In the second example, any code reviewer would accept a depth of three, because it simply doesn't matter here. Most code reviewers would also accept three depths in the first example, while suggesting to refactor the code later if needed to get cleaner and more object oriented design.

Code quality is too complex and subjective to be done automatically; keep this task for people, though code reviews. This doesn't forbid you from gathering metrics for statistical purposes during nightly builds.

I myself use some code quality tools, including Visual Studio's Code metrics. I often noticed that my refactoring lead to drops of one or several criteria used by Code metrics, while the code itself was becoming more readable and maintainable. Those are only metrics: objective and reliable, but also blind and rigid. Use them as hints, not as something which tells you what to do.

You can set long-term goals, and use different techniques to encourage people to attain them. Fixing a goal of 90% code coverage for January 2015 and displaying in the hall of your company the photos of the developers who achieved the best code coverage according to the last commit stats is one thing. But forcing everyone to have 80% code coverage right now would only push developers to add useless tests of boilerplate code just to be able to get back to work, especially if there are good reasons for some teams to have less than 80% code coverage.

Personal considerations

Enforcing anything for the sake of doing it is usually a bad idea. Ask yourself:

What is the primary issue?

Is enforcing something the best solution?

Examples:

You want to force developers to increase the code coverage. What is the primary issue? The fact that the number of bugs is too big compared to your expectations? Was your expectations realistic? While the number of bugs correlates well with testing, are there bugs essentially because of the lack of testing? Or because there are no written requirements, and developers don't understand the needs of end users? Or because you hired programmers which are not skilled enough? Or maybe because there is too much noise at the workplace?

Let's assume that the only thing you can do to decrease the number of bugs is to increase the number of tests. Ask yourself, why aren't programmers writing enough unit tests in the first place? Maybe it's because management constantly pushes them to release faster? Maybe because they don't understand the pleasure of TDD? Maybe because they believe that it's up to Quality Assurance folks to write those tests?

You want to set up some code quality checks. What's the primary issue? The gap between the code written by best and worst programmers in the team? Wouldn't pair programming help? Do you do code reviews? Can't you simply fire programmers who are not skilled enough, and hire better ones?

Let's assume you can't fire anyone and you can't do code reviews or pair programming. But can't you simply talk with the problematic programmers, explain them the issues, listen to their point of view? What if they are talented guys, but just hate to write PHP code? What if they simply don't want to write high quality code, because management already cancelled two previous projects, and they don't believe this one would survive?


问:
Choosing name for open-source project -- how to view existing trademarks/names used for other programs?
I'm trying to choose a good name for a new open-source project. The problem is, there is already so much software in the world that Google search reveals one or more existing programs with every good name I can think of (and there have been several already).

Obviously, names like "Linux" or "Windows" or "Java" or "Excel" are off-limits. But what about names which may have been used by some little-known program? Does it make a difference if the name is trademarked in one or more countries?

In one case, I found that there is a commercial software package marketed by a Canadian company, using a name which I wanted to use. The same name is trademarked in the US, but by a different company. I couldn't find any evidence that the holder of the trademark is actually marketing software under that name. In Canada, the name is not trademarked.

In other cases, I found several programs all using the same name, some commercial, some university-student research projects. So maybe this is normal in the software industry?

What if I use a name which is not trademarked, and someone else trademarks it later? Could I face legal pressure to stop using it?

Would it help to avoid legal problems if I prefix the name? For example, say I want to call my project "Broomflip", but other software is already being marketed under that name. If, assuming I am associated with an organization called "Hoplock", I call it "Hoplock Broomflip", would that be better?

I'm hoping someone with a good understanding of IP law can shed some light on some or all of the above questions. Of course, personal opinions from those without special legal knowledge are also welcome, but please try to back them up with evidence or relevant references. Anecdotal evidence is welcome.

答:
I think to be on the safe side you need to pay for a name search.

That is what an article from Gamedev.net (http://www.gamedev.net/page/resources/_/business/business-and-law/legal-issues-for-rookie-development-studios-par-r1985)
says:

Trademarks
  Trade and service marks, usually both called "trademarks",
  are words, symbols and other things use to identify the source of a
  product in commerce. Some little know trademarks are Kodak Yellow and
  the sound of a Harley. Both are protected. But usually trademarks are
  names and logos. Again, from the PTO:

"A trademark is a word, name, symbol or device which is used in trade
  with goods to indicate the source of the goods and to distinguish them
  from the goods of others. A servicemark is the same as a trademark
  except that it identifies and distinguishes the source of a service
  rather than a product. The terms "trademark" and "mark" are commonly
  used to refer to both trademarks and servicemarks. "Trademark rights
  may be used to prevent others from using a confusingly similar mark,
  but not to prevent others from making the same goods or from selling
  the same goods or services under a clearly different mark. Trademarks
  which are used in interstate or foreign commerce may be registered
  with the Patent and Trademark Office. The registration procedure for
  trademarks and general information concerning trademarks is described
  in a separate pamphlet entitled 'Basic Facts about Trademarks'."

Trademarks are associated with a product and are limited to that
  particular product type in terms of the scope of protection. So,
  Domino Pizza and Domino sugar ad Domino software all get to trademark
  the same word because the basic idea around trademark law is to avoid
  confusion as to origination in the marketplace. Though it reaches a
  point where a trademark becomes what is classified as a "famous" mark
  and then the scope of protection expands across product categories.
  So, forget the idea of naming your game Coca Cola!

The first thing to do if you are interested in getting a trademark is
  to make sure the term you want to TM is not descriptive. For example
  you cannot trademark the word "bread" for use with the sale of bread.
  It is generic and descriptive. But you can certainly TM the word
  "Bread" for a band (oh yeah someone already did that), or even for a
  game. You also need to make sure the mark or any close variation is
  not already in use. There are companies that do comprehensive name
  searches - the charge for a full trademark search is usually from $400
  - $1200 depending on the geographic scope - from national to worldwide. Once you determine that the mark is relatively clean,
  trademarks are acquired by registering an application with the PTO,
  and then waiting and waiting, responding if there is a similar mark or
  if the examiner thinks it is too generic, and then, hopefully, get
  your TM registered. It takes some time and effort but it is not nearly
  as expensive as the patent application process mentioned above.

Not sure how that makes sense, though. You pay $1200 just to find out that you can not use the name you wanted to use?

Seems like they actually are not implicit, so you have to register the trademark to have that kind of protection.

ContentLicense: CC BY-SA 3.0


答:
Somehow, the number of software projects is way bigger than the number of names people can come op with for those projects, especially if you want descriptive, pronounceable names. That makes that it is only natural that there will be multiple projects with the same name.

Having multiple projects with the same or similar names is no problem, as long as people won't be confusing those projects. Especially if the projects serve different, non overlapping, markets, then it is unlikely that there will be confusion which project is meant by the name "Broomflip".

With trademarks, the situation is similar, except that the company holding the trademark now has better legal means to put a stop to someone else using their name in a way that could cause confusion as to what the name refers to.

Having trademarked a name also doesn't mean that nobody else can use that name for any purpose. That depends on how well-known your name is. A name like Coca-Cola can probably not be re-used, because it is too well known, but if you are working in a niche market and have trademarked your product name, then someone else could still use that same name in a completely different context.

Trademarks also don't work in such a way that you can force a competitor out by just trademarking their name. Then it would be too easy to stifle competition for large companies.

tl;dr: Don't worry too much about using similar names as existing projects, as long as you don't cause any confusion amongst users which product/project is meant by the name "Broomflip".

Title: Choosing name for open-source project -- how to view existing trademarks/names used for other programs?

Body:
I'm trying to choose a good name for a new open-source project. The problem is, there is already so much software in the world that Google search reveals one or more existing programs with every good name I can think of (and there have been several already).

Obviously, names like "Linux" or "Windows" or "Java" or "Excel" are off-limits. But what about names which may have been used by some little-known program? Does it make a difference if the name is trademarked in one or more countries?

In one case, I found that there is a commercial software package marketed by a Canadian company, using a name which I wanted to use. The same name is trademarked in the US, but by a different company. I couldn't find any evidence that the holder of the trademark is actually marketing software under that name. In Canada, the name is not trademarked.

In other cases, I found several programs all using the same name, some commercial, some university-student research projects. So maybe this is normal in the software industry?

What if I use a name which is not trademarked, and someone else trademarks it later? Could I face legal pressure to stop using it?

Would it help to avoid legal problems if I prefix the name? For example, say I want to call my project "Broomflip", but other software is already being marketed under that name. If, assuming I am associated with an organization called "Hoplock", I call it "Hoplock Broomflip", would that be better?

I'm hoping someone with a good understanding of IP law can shed some light on some or all of the above questions. Of course, personal opinions from those without special legal knowledge are also welcome, but please try to back them up with evidence or relevant references. Anecdotal evidence is welcome.


答:
You should probably mention the language. For Java there is Checkstyle (http://checkstyle.sourceforge.net/).

I have not used it personally, but colleagues said that it can be used in a continuous integration setup.

Maybe you can find something for your language in this article by searching for "style":
http://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis

I think automatically rejecting the code is not a good idea, though.
You need the programmers to commit to / agree on the coding style and make sure people react to a low score by fixing the style. I would still call the build successful (just with warnings). You probably do not want to work with programmers who refuse to go for conventions and a coherent style.
But there will be tense moments when you do not want the strict style checking to get in the way.

You should also look at the IDE integration for the tools. That might be a better place to be strict (better than the continuous integration server).

Title: How to set up something like an integration server that measures the quality of code and reject the code if the score is below a certain number?

Body:
Even if I don't like enforcing people to do things (and I believe that it may decline the productivity and cause anger), I really want to enforce good coding style.

Is there a way to set up something like an integration server that measures the quality of code (for example it runs resharper or some other static checker) and reject the code if the score is below a certain number?

Also, do you think this is a good approach?


问:
Functional or non-functional requirement?
I'm wondering about functional or non-functional requirements. I have found lot of different definitions for those terms and I can't assign some of my requirement to proper category.

I'm wondering about requirements that aren't connected with some action or have some additional conditions, for example:

On the list of selected devices, device can be repeated.

Database must contain at least 100 items

Currency of some value must be in USD dollar.

Device must have a name and power consumption value in Watts.

are those requirements functional or non-functional ?

答: i do think the functional requirements are necessary thing describing the system and its behavior but non-functional requirements are not necessary to the system and not gathered during the negotiations of the designing the system are just the out come of the system such as speed coverage quality,security,maintainability etc.from the built system. </p>


问:
Function overloading? Yes or no
I'm developing a statically- and strongly-typed, compiled language, and I'm revisiting the idea of whether to include function overloading as a language feature. I realized that I'm a little bit biased, coming mainly from a C[++|#] background.

What are the most convincing arguments for and against including function overloading in a language?

EDIT: Is there nobody who has an opposing opinion?

Bertrand Meyer (creator of Eiffel back in 1985/1986) calls method overloading this: (source)

a vanity mechanism that brings nothing to the semantic power of an O-O language, but hampers readability and complicates everyone's task

Now those are some sweeping generalizations, but he's a smart guy, so I think it's safe to say he could back them up if he needed to. In fact, he almost had Brad Abrams (one of the CLSv1 developers) convinced that .NET shouldn't support method overloading. (source) That's some powerful stuff. Can anyone shed some light on his thoughts, and whether his viewpoint is still justified 25 years later?

答:
Grrr .. not enough privilege to comment yet ..

@Mason Wheeler: Be aware then of Ada, which does overload on return type.
Also my language Felix does it too in some contexts, specifically, when a function returns another function and there is a call like:

```<code>f a b  // application is left assoc: (f a) b
</code>```

the type of b can be used for overload resolution. Also C++ overloads on return type in some circumstances:

```<code>int (*f)(int) = g; // choses g based on type, not just signature
</code>```

In fact there are algorithms for overloading on return type, using type inference. It's actually not that hard to do with a machine, the problem is that humans find it hard. (I think the outline is given in the Dragon Book, the algorithm is called the see-saw algorithm if I remember correctly)

ContentLicense: CC BY-SA 4.0

Title: Function overloading? Yes or no

Body:
Grrr .. not enough privilege to comment yet ..

@Mason Wheeler: Be aware then of Ada, which does overload on return type.
Also my language Felix does it too in some contexts, specifically, when a function returns another function and there is a call like:

f a b  // application is left assoc: (f a) b

the type of b can be used for overload resolution. Also C++ overloads on return type in some circumstances:

int (*f)(int) = g; // choses g based on type, not just signature

In fact there are algorithms for overloading on return type, using type inference. It's actually not that hard to do with a machine, the problem is that humans find it hard. (I think the outline is given in the Dragon Book, the algorithm is called the see-saw algorithm if I remember correctly)

ContentLicense: CC BY-SA 2.5


问:
What should plugins use: hooks, events or something else?
Consider an app that allows plugins to react to its program flow.

I know 2 ways to achieve this: hooks and events

1. Hooks

Use calls to empty functions inside the main program flow. These functions can be overriden by plugins.

For example, Drupal CMS implements hooks which are available to modules and themes. Here's an example of how hook is implemented in a file_copy function.

```<code>function file_copy(stdClass $source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
    // ... [File copying routine]

    // Inform modules that the file has been copied.
    module_invoke_all('file_copy', $file, $source);

    return $file;
    // ...
}
</code>```

A module can implement a modulename_file_copy($file, $source) function which will be called by the module_invoke_all in file_copy. After this function finishes, the file_copy will resume execution.

2. Events

Have the app dispatch events, which can be listened to by the plugins. After receiving an event that it's been subscribed to, a plugin will intercept the program flow and perform neccessary operations.

For example, a jQuery gallery plugin Fotorama implements several events. As an example, here's a part of its show method that fires the fotorama:show event.

```<code>  that.show = function (options) {
    // ... [show the new frame]

    // [fire the event]
    options.reset || triggerEvent('show', {
      user: options.user,
      time: time
    });

    // ... [do lots of other stuff with navigation bars, etc.]
  };
</code>```

A script can listen to this event and do something when it fires:

```<code>$('.fotorama').on(
  'fotorama:show',
  function (e, fotorama, extra) {
    console.log(e.type + (extra.user ? ' after user’s touch' : ''));
    console.log('transition duration: ' + extra.time);
  }
);
</code>```

QUESTION

Are there other mainstream ways to implement such plugin behaviour?

If not, when should one use hooks, and when should one use events? Considering the ultimate goal is to make the code more maintanable and readable, from both the app and the plugin developer's perspective?

答:
The main difference between a hook and event is loose coupling versus tight coupling.

A hook is a generic way to broadcast that something has happened. You can add new hooks without having to recompile plugins, and all hooks follow a generic design pattern. Once the hook API is defined it doesn't change so the coupling between the app and plugin isn't likely to break.

Events are more tightly coupled to the app. Events can define parameters that are attached to the event, and if you change those parameters you break the API with existing plugins.

They both achieve the same results. It just depends upon how you want to couple the plugin to the app.

Hooks can offer you a more dynamic coupling that isn't likely to break as new versions of your app are released, but the disadvantage is you don't get any compile time warnings that the plugins no longer are compatible.

Events offer you the ability to get compile time errors that the plugin needs to be modified, because some of the event signatures have changed.

You asked for alternative approaches.

Commands:

Instead of plugins responding to triggered events. Plugins push command objects to the application. Each command object implements an interface used by commands. When the application needs to execute a feature it runs all the commands for that feature. This is very much like events, except that it's implemented as objects instead of callback functions.

Macros:

Instead of plugins responding to when things happen. Plugins proactively cause things to happen. A macro is a small high-level language that runs above the application telling it what to do.

State Change Listeners:

Events are triggered by the application with forethought by the developer. The developer has to knowingly write code that issues the event. Instead, an alternative approach is to make objects automatically broadcast when their internal state has changed. Either the changing of a property or other indicators. Plugins can then listen for these specific state changes and react accordingly. The advantage of this approach is that the programmer does not have to remember to broadcast events. For example, there might be an Document object and the programmer sets a flag to mark that the document needs to be saved. This state change is broadcasted to listening plugins, and there could be a plugin that changes the document title to include an asterisk.


问:
Is recursive code slower than non-recursive code?
Now I'm only a novice programmer, but what my friends that are studying programming tell me is that recursive code is a good thing, it leads to less code duplication and it looks more elegant.

Now it may be so, but everytime I've tried my hand with recursive code I've always found it to be significantly slower than non-recursive code, I'm not sure if it's something about the ways I've used it but I highly doubt it, I've used it for fairly simply thing's like Collatz Conjecture and Fibonacci number generation but whenever I've compared it against normal iterative code the recursive approach will consistently clock at around twice the time of the iterative solutions.

答:
Recursion is slower and it consumes more memory since it can fill up the stack. But there is a work-around called tail-call optimization which requires a little more complex code (since you need another parameter to the function to pass around) but is more efficient since it doesn't fill the stack.

Unfortunately C# does not support this so I would suggest you to use recursion with care, because you might get stack overflow for large values.

As a conclusion, in functional languages you only have recursion and have to deal with it; but in imperative languages iteration is more natural and more efficient. The majority of the most-used imperative languages either does not support (Java, C#, Python) or does not guarantee (C, C++) tail call optimization.


答:
It is good to at least understand how recursion works, because some algorithms are naturally recursive and thus much easier to express using recursion.

Also, recursive algorithms (or implementations) are not inherently slower than iterative ones. In fact, every recursive algorithm can be implemented by an equivalent iterative implementation at the cost of having to keep track some intermediate/temporary values yourself, where the recursive version automatically keeps track of those in the function call stack.

One example of a naturally recursive algorithm is if you want to apply an operation to all the nodes of a tree. The most natural implementation here is to have a function that performs the operation on one node and calls itself recursively for each of the children of the node.

For some algorithms, like calculating a Fibonacci sequence, recursion seems natural, but a naive implementation will be much slower than an iterative implementation, because the recursive version keeps re-doing the same work over and over again. This just means that for those particular algorithms, recursion may not be the best choice, or that you need to use some techniques to remember intermediate values that might be needed again elsewhere in the algorithm.

For other algorithms, in particular those that use divide-and-conquer tactics, you will find that you need a stack to keep track of some thing in the iterative solution. In those cases, a recursive version is much cleaner, because the stack handling becomes implicit.

Title: Is recursive code slower than non-recursive code?

Body:
Now I'm only a novice programmer, but what my friends that are studying programming tell me is that recursive code is a good thing, it leads to less code duplication and it looks more elegant.

Now it may be so, but everytime I've tried my hand with recursive code I've always found it to be significantly slower than non-recursive code, I'm not sure if it's something about the ways I've used it but I highly doubt it, I've used it for fairly simply thing's like Collatz Conjecture and Fibonacci number generation but whenever I've compared it against normal iterative code the recursive approach will consistently clock at around twice the time of the iterative solutions.


问:
How do I explain to non-programers what .NET is?
I don't work at a software company, and I'm one of a small handful of people in the company that know anything about programming. I spend a lot of time automating other programs that are used in the office through public APIs, and I've also created a few stand alone applications. I work almost entirely in C#.NET as every application we seem to use in the office seems to have some form of .NET API.

I've had a few people here ask me about learning "how to program", and where they should start. I think it makes a lot more sense to learn a .NET language as nearly all the programs they would want to automate have a .NET API, and it sounds like VBA is on it's way out and being replaced by VSTA.

However, I'm trying to figure out how to explain what .NET is and why they should learn it to a someone that doesn't know anything about programming. It's not really a language, as there are a number of languages that are considered .NET languages. Plus I think there is a distinction between ".NET" and "The .NET framework" as the latter is more about the libraries provided by Microsoft.

答:
It's a Big Fluffy Cloud..

Tell them that Its Microsoft sexy new technology. And that it allows developers from different languages to all hold hands and make super sexy code. Tell them that it auto-magically works on things like PC's, XBOX's and Windows Phone. And also tell them that they can make anything from games to boring business applications with them as well as websites too.

Keep it short:

Its a Big Fluffy Cloud :)

Its Microsoft Tech

Runs on PCs, XBOX, Windows Phone

It "understands" many different languages

Can make, Games, Businees Applications & websites with them


问:
How important is graceful degradation of JavaScript?
Should web developers continue to spend effort progressively enhancing our web applications with JavaScript, ensuring that features gracefully degrade, thereby ensuring accessibility?  Or should we spend that time focused on new features or other areas of development?

The subtext of that question would be:  How many of our customers/clients/users utilize our websites or applications with JavaScript disabled?  Do you have any projects with requirements that specifically demand JavaScript functionality (almost all of mine do), and do those requirements also demand graceful degradation?

For the sake of asking this question, I pulled up programmers.stackexchange.com without JavaScript enabled, and I was greeted with this message: "Programmers - Stack Exchange works best with JavaScript enabled".  It was difficult to log in, albeit the site seemed to generally work okay.  (I wasn't able to vote up any questions.)

I think this is a satisfactory approach to development.  Imagine the effort involved in making all of the site's features work with plain old HTML and server-side logic. On the other hand, I wonder how many users have been alienated by this approach.

We've all been trained (at least the good developers among us) to use progressive enhancement and to ensure our web applications' dynamic features degrade gracefully.  Is this progressive enhancement just pissing into the wind, or do some of our customers actually utilize certain web services without JavaScript enabled?

答: I just answered a question on AskUbuntu.com -- I had to (temporarily - at the moment) enable JavaScript on the site.  I use NoScript and enable JavaScript for a site when I think it is clear - but not until.  By default, JavaScript is off for sites I've not visited before.</p>


问:
System Communication: Avoiding Including a Large "HAS-A" Hierarchy Which Isn't Used
The situation:

System A

Huge, complicated system.  Uses an important Message object with many other Message objects attached, many of which have further Message objects attached.  In total, this is about twenty different objects.

Due to awkward timing with releases and introduction of code churn, System A cannot have its Message object hierarchy touched.

System B

Needs to use the same important Message object to communicate with System A to make use of one of its services.  However, since the messages it will send off are going to be invariable, it only uses a very small portion of the Message object hierarchy.

The Question:

How could I allow System B to make use of the important Message object without (a) touching System A, or (b) including a hierarchy of nearly twenty objects, almost none of which are used at all?  Is there a more advanced Design Pattern which could be put to use in this scenario?

答:
The way I ended up solving this was to go as "bare-bones" and REST-like as possible.

System A has a few functions that don't take in any message objects; rather they accept the minimum amount of data to create message objects of their own, then make use of those.  System A accepts this data as http.

System B has, as a result of this, a bit of hard-coding involved.  Each of the values for a particular call to System A are tossed into an anonymous object, which is then converted into a URL parameter to make a REST call.

Total code count is less overall, and System B doesn't have a massive, mostly useless object hierarchy copied from System A.


问:
Is a large increase in velocity realistic in a Scrum environment?
My manager has recently really been pushing to use velocity as a target and measure of productivity. We are currently working at an average velocity of 50 story points. My manager wants us to increase it by 40% to 70 story points (with no increase in team members). If we don't achieve this increase he wants us to deliver a full break down explaining why.

The whole idea of measuring team performance by velocity and using it as a target seems wrong to me, but I am finding it difficult to explain why. Any help? Why isn't this the right way to measure and incentivize productivity?

答:
The problem with velocity is that it is a dependent variable, a measured output of your development process. Demanding to increase velocity 40% is like trying to get to work sooner by yelling at the cars to go faster. Velocity increases by feeding more fuel and air into the engine or getting a faster car, plus finding a route with less traffic.

Working more hours doesn't increase velocity if you measure it properly, say in feature-points per developer-hour. It only works if you measure points per day and then redefine what a "day" is in mid-measurement. This provides only the illusion of speed.

An increase in velocity requires improving the independent variables in the dev process; faster computers and compilers, more efficient build system, better design process, more capable developers, better workspace, super-duper motivation. A 40% improvement would require very significant changes.

Ask if your manager would consider co-locating your team in enclosed offices around a common workroom, buying the team all-new dev hardware, or hiring a couple of really senior devs to mentor the team if that would get him his 40%. If there are no resources available to improve the inputs to your dev process, that pretty much rules out sincere interest in improving. This leaves reverse-engineering your manager to figure out what is really motivating him, which would be the subject of a whole 'nother thread.


问:
How can I re-use object from another project?
I have a first project has a feature to viewing, inserting and updating an employee record, with this possibly I will create a java class for the UI and another for the database connection with commands for viewing, inserting and updating a record.

Then I have a second project that will compute the salary of employee. How can I re-use object from the first project?

Should I get the Java or the class file or both of the first project and saved it to the project folder of the second project? How can add a feature of object from the first class?

答:
The artifacts (i.e. class files, resource files, etc.) from the first project should be on the classpath of the second project.

If your project is quite small, you can specify the location to project one's class files on the command line or with environment variables. See http://docs.oracle.com/javase/tutorial/essential/environment/paths.html.

Otherwise, you should look into some project management or build software, like maven or apache ant.


问:
Object Identity and Mutability
I was reading a proposal for value types in Java, and I came across this sentence: "Object identity serves only to support mutability, where an object’s state can be mutated but remains the same intrinsic object."

From what I understand (albeit tentatively), object identity is the idea of your variable acting as a pointer or reference to an object located elsewhere in memory (such as objects instantiated on the heap in Java or C#). So what would this have to do with object mutability? Does this imply that, for example, instantiated objects on the stack in C++ are immutable? I'm having trouble seeing the link here.

答:
Imagine you have two objects, for example two instances of the class List. Both lists have the same content. Now you are reading the lists and calculate and output something based on their content. Does it matter what list you use? It doesn't because they have the same content.

But what if one of the lists is changed? Now it does matter which one you choose for reading and outputing something. Therefore you need to be able to distinguish between them and you want even in some situations be able to check if two variables point to the same object (or here list).

If you however are not able to change the content of a list then you don't even need to have two list objects with the same content because you can't change them anyway. If you want to "change" the content you will instead create a new list object with different content - which is as i said a new object. So from this point of view the identity doesn't matter. Only the content does and only the content should be used for comparing two lists.

Also note that the compiler could point to the same list object even if you declare two objects because it only needs to store its content once as it cannot change.

Title: Object Identity and Mutability


问:
Does "write quality code" advice apply to companies of any scale?
I carefully followed the "always write quality code, unless you're writing a prototype" advice during my career as freelancer and software developer. I was convinced pretty early that avoiding to do code reviews, testing, QA or refactoring doesn't make the project faster, but only slower.

Books like The Mythical Man Month by Fred Brooks or Rapid Development by Steve McConnell confirmed my thoughts. Professional experience in medium-scale companies also showed me how much money and time is wasted by not even trying to do quality work.

At the same time, I often heard my colleagues complaining that constantly maintaining good code quality or simply achieving good code quality at all is too complicated for small scale companies and small teams:

It's just too expensive to get the people able to write and maintain quality code.

If the company can hire either two persons for $3 000 per month or one person for $6 000 per month, most managers would consider that two persons will be more productive than one: maybe not by a factor of two, but still. Or the small company can hire one person for $3 000 per month and spend the remaining 3 000 for something else.

There are too many aspects to take in account in order to be able to do it within a small team.

A single person can hardly take care of the style of code, readability, architecture, design, ease of testing, testing itself, reliability, security, ease of use, performance, etc.

And it doesn't worth it.

It's not like a piece of code will remain in the code base for the next fifteen years and will be read thousands of times by hundreds of developers. Chances are, the same person will maintain this piece of software for the next five years, then just throw it away and write a better one from scratch.

I usually reply that one should remember the productivity factor of 1:10 among developers and that most of the time is spent not writing code, but maintaining it. This means that low quality code is still ways more expensive.

But is it so?

Should every company, no matter its scale, try to hire the best possible developers they can afford, and encourage them to write quality code, or there is scale above which code quality becomes just a burden, a waste of time and money?

答:
The problem with many companies is that they are less interested in having people write quality code than having people write "good enough quality code," e.g. code that just barely does the job. In this context, having two people to check each other's work seems like a safer bet than hiring one.

In order to get people to choose you, you need to persuade clients that 1) only high quality code will do the job and 2) you are a provider of such high quality code. The second is perhaps an easier "sell" than the first. If you happen to be a subfield where "anyone" can write "adequate" code, that might be tough luck for you. Then you'd need to find a new area where the minimum standard is higher and demands your level of skill.


问:
Sqlite3 slow on standard queries, is it expected?
Using Python and sqlite3. This simple print loop takes a few seconds to execute. I don't know much about databases, so I'm guessing I'm not using these queries correctly. Surely sqlite should be faster? The entire db has 5k or so rows and just a few columns if that matters.</p>

```<code>con = lite.connect('gamelist.db')
with con:
    cur = con.cursor()
    cur.execute("SELECT * FROM GameList WHERE processed IS NULL LIMIT 4")
    for i in range(0, 4):
        print cur.fetchone()
</code>```

答:
Don't guess, measure

When you have an issue related to performance, don't guess. Grab a profiler, measure your code, and decide what to optimize based on the results, not your or somebody else's guesses.

Your first guess is that sqlite3 is slow. Your second guess is that you have memory leaks. Chances are, you'll find when profiling your app that neither of your two guesses is even close to the actual issue. It happens to every developer; that's why one shouldn't guess.

Python documentation lists a few profilers for Python. If you never used one, grab a profiler of your choice and see where it could get you. Bonus points for coming back and posting the results by editing your question.

Be precise

Also, when dealing with performance, be as precise as you can. Terms like "A few seconds", "slow", "standard queries" have nothing to do when it comes to performance, profiling and optimization.

There is no such a thing as a few seconds. There is a statistical data about the performance of a given piece of code ran in a very specific context. Something which takes five seconds on a Pentium IV we threw away yesterday may run in a few milliseconds on the new server we just purchased.

There is no such a thing as code too slow: there is a piece of code which performs under an average of 327 ms. on a given hardware under given stress, while a non-functional requirement (see also this answer, point 2 and 8) specifies that it should perform under 300 ms. in 95% of cases.

There is no such a thing as a standard query. For somebody, a standard query may include joins. For another person, it's a select, insert, update or delete with nothing else such as where.

You specified the number of rows in the database. That's the precision I'm talking about. Measuring a select on ten rows is not the same as on one billion rows.

Reduce the measured code to a minimum

When you can't use a real profiler, it can help to remove all the code you don't need, and then measure. In your particular case, this involves the conversion of an array to a string and the displaying of this string to a console.

Try actually measuring the performance of the same code without printing those results and see how it affects.


问:
Using different DB Connections for different user groups in a web framework
Database designers building enterprise systems usually assign different sets of privileges to different users of DBMS. They can be as granular as needed.

However, in my experience, web frameworks usually use a single connection to a DBMS, and the privileges are assigned and enforced at the framework level, through some sort of access control scheme. The database connection used by the framework has full privileges on the database, because it may need to create or delete tables, when extensions are installed or removed, for example.

Sometimes there are vulnerable extensions of a framework that may allow SQL Injection attacks. These extensions are often developed by third parties, and not by the framework developers.

My question is:

What is the efficacy of providing multiple DB connections with varying privileges for different user groups of a web framework - as a security measure? For example, the connection for a system administrator may allow for creating and deleting tables, but the connection for a public user may only allow for reading certain tables.

This would not be a replacement for the Access Control scheme in the framework, but as an added measure against SQL Injection.

Is this a good idea, or completely unnecessary? Please explain.

答:
I think the easiest way to prevent this is to use prepared statements of some sort. Rather than worry about SQL injection as a permission problem, worry about it as an input problem.

That being said, I don't know how effective different connection strings would be. If you do find you want to separate your controls, I wouldn't do it by it user. I'd do it by access necessary. That way, a system administrator viewing content would have the lowest permissions he needed to do that. The connection would "elevate" itself once he or she needed to do something requiring CREATE/DROP TABLE permissions. That's probably a more robust solution.


答:
Well, this is a big question that is perhaps too big for the site. But let's focus on some of the core points.

Is quality worth it?

This stackexchange question goes into some of the details about the cost of bugs depending on when they're found. Long story short, bugs tend to cost an order of magnitude more to fix each time they move from development to QA to customer validation to the field. Spending a dollar to fix a bug during programming saves you a thousand dollars that it would take to fix the bug in the field.

In that regard, it is always worth it. High quality code costs less to make than low quality code to make and then fix later.

Assuming you intend to fix the bugs. The level of quality needed for a nuclear reactor is different than the level of quality needed for your Angry Birds clone. Having too much quality here can be a burden and diminishing returns of course. But if you intend tho fix the bugs, they pretty much always cost less to fix during development.

Should we hire the best developers?

Probably not. The usual "cost savings" of good developers comes from two places:

Fewer bugs - see above. The fewer bugs produced by development is cost savings for the company.

Awesome Features - the top tier developers can do awesome things that "average" developers simply can't. Google wouldn't be google without making a search engine leaps ahead of others at the time.

The problem comes that most programming jobs aren't with technology companies. They're making vanilla websites or doing data plumbing from one point to another. Merely average developers are perfectly capable of implementing that.

Fewer bugs is a bit of a relative issue too. A 99th percentile developer may catch all the bugs, but if you're doing pretty simple work, then a 75th percentile developer may catch all the bugs at half the cost.

In that regard, it's not always worth it.

Small teams just can't make quality software.

Small teams can't make quality software only when you won't sacrifice scope or schedule. There's three levers for software management: cost, scope and schedule. If your costs need to be small and you want high quality, then you need more time or you need fewer features. If your company wants to sacrifice quality for more features or a quicker schedule... That's their choice, but there's nothing forcing small teams to make bad code.

Is that choice reasonable in some scenarios? Sure. I've seen scenarios in a startup environment where time to market is so important/valuable that it makes sense to cut corners now. In many startup cases, being the first to market is of almost infinite worth. The great idea gets associated with your company and the second entry to the market has no chance since everyone wants the sexy new thing - not the copy.

So in summary, it's probably not always worth it to hire top tier developers and make high quality software. Sometimes low quality software now is more valuable. And hiring average developers will be a more cost effective way to produce "good enough" software depending on the relative cost and productivity of those developers. But I would argue that for most scenarios, quality software (and by extension, good developers) are the most cost effective way to do business.

Title: Does "write quality code" advice apply to companies of any scale?

Body:
I carefully followed the "always write quality code, unless you're writing a prototype" advice during my career as freelancer and software developer. I was convinced pretty early that avoiding to do code reviews, testing, QA or refactoring doesn't make the project faster, but only slower.

Books like The Mythical Man Month by Fred Brooks or Rapid Development by Steve McConnell confirmed my thoughts. Professional experience in medium-scale companies also showed me how much money and time is wasted by not even trying to do quality work.

At the same time, I often heard my colleagues complaining that constantly maintaining good code quality or simply achieving good code quality at all is too complicated for small scale companies and small teams:

It's just too expensive to get the people able to write and maintain quality code.

If the company can hire either two persons for $3 000 per month or one person for $6 000 per month, most managers would consider that two persons will be more productive than one: maybe not by a factor of two, but still. Or the small company can hire one person for $3 000 per month and spend the remaining 3 000 for something else.

There are too many aspects to take in account in order to be able to do it within a small team.

A single person can hardly take care of the style of code, readability, architecture, design, ease of testing, testing itself, reliability, security, ease of use, performance, etc.

And it doesn't worth it.

It's not like a piece of code will remain in the code base for the next fifteen years and will be read thousands of times by hundreds of developers. Chances are, the same person will maintain this piece of software for the next five years, then just throw it away and write a better one from scratch.

I usually reply that one should remember the productivity factor of 1:10 among developers and that most of the time is spent not writing code, but maintaining it. This means that low quality code is still ways more expensive.

But is it so?

Should every company, no matter its scale, try to hire the best possible developers they can afford, and encourage them to write quality code, or there is scale above which code quality becomes just a burden, a waste of time and money?


问:
DRY code, DRY tests?
At some point I had to create some class "Class1" and that class needs a method "method". So I have the following:

```<code>Class1MethodTest: A total of N tests that check the behavior of Class1.method
Class1 method: A full implementation of the method
</code>```

But a bit later I need a different class "Class2" to have a completely similar method "method". Now I have several approaches:

Approach 1

```<code>Class1MethodTest: A total of N tests
Class1 method: Full implementation
Class2MethodTest: Another set of identical tests
Class2 method: Another full implementation
</code>```

Pros: Stupid simple

Cons: not DRY

At least that's the first attempt and I might even write this before doing any refactoring, right?

Approach 2:

```<code>_hidden_private_implementation_function: Full implementation of required method
Class1MethodTest: A total of N tests
Class1 method: Call hidden_private_whatever
Class2MethodTest: Another set of identical tests
Class2 method: Also call hidden_private_stuff
</code>```

Pros: DRY code, still stupid simple

Cons: Tests aren't DRY, "Test interface, not implementation"

Approach 3:

```<code>MethodTest: A total of N tests
TotallyPublicCommonMethod: Full implementation of required method
Class1MethodTest: Just one test to verify that Class1 method calls the Public one
Class1 method: Call public common method
Class2MethodTest: One more test
Class2 method: Also call common method
</code>```

Pros: DRY, stupid simple

Cons: .. any other than "You're testing implementation, not interface"?

Approach 4:

This is where it gets a bit exotic. Python allows me to DRY the "Approach 3" directly:

```<code>_hidden_private_implementation_function: Full implementation of required method
makeTestForClass(cls): return a total of N tests for class cls
Class1MethodTest = makeTestForClass(Class1)
Class1 method: Call hidden_private_whatever
Class2MethodTest = makeTestForClass(Class2)
Class2 method: Also call hidden_private_stuff
</code>```

Pros: DRY, "Don't test implementation"

Cons: Not that simple. Too hard to modify if I ever decide to change something in Class1.method, but not Class2.method

I can think of a couple more approaches but those are not very different from these above.

Right now I have some code looking something like "Approach 1" and I am thinking on which way I should go next to make it all cleaner and better.

答:
TL;DR: Extracting common functionality is fine as long as the stronger coupling is warranted by code cohesion.

Refactoring often occurs in areas which already have strong cohesion, and as a result should also have strong coupling.  When you extract common functionality into some shared structure you increase the coupling.  When code is duplicated it typically means the duplicated piece can be modified without impacting the other, ie. they are decoupled.  If 2 or more pieces of code now delegate to a shared piece of code they are now coupled to that shared code.  If the shared code changes, then all code that delegates to the shared code are affected, ie. they are strongly coupled.

This is all fine and dandy as long as the all the code that delegate to the shared code are all strongly cohesive.  If they aren't then you are creating bad strong coupling.

What's all this mean?  That it's fine to extract and refactor in tests as long as you aren't creating strong coupling that shouldn't be there.  To put it another way.  If you have to separate methods that are incidentally similar then they should not be refactored to use shared code because they shouldn't be coupled together.  If, on the other hand, the separate methods are similar because they are related in some meaningful way (cohesive) then extracting shared code is fine.

Title: DRY code, DRY tests?


问:
Why HTTP Servers send information about themselves in HTTP Headers?
Most of the HTTP Servers I know send their application name and version in response http headers as default behaviour. (Nginx, IIS, Apache etc.) Of course we can change the default behaviour but I wonder why they send these information? Does it matter which HTTP Servers we use to the requesters?

The only reason I can think of is to allow analytics services to keep track of which HTTP Servers are widely used by websites but otherwise these information are unnecessary for most of the requests and when an attacker figures out a specific version of a HTTP Server has a bug, he can easily find websites which uses that version and use that information against these websites.

答:
Back in the early days of the internet, server operators didn't have to worry about hordes of random attackers trying to break into their web site. The server name/version information was provided as a courtesy, and perhaps as a form of advertising as well.

Early versions of the Netscape web browser had an address bar with a label that read "Location:". However, when connecting to a server using software produced by the same company, the word "Location:" would change to "Netsite:"[1] (the server software was called Netsite). This was made possible by the server header field.

Happy Run Some Old Web Browsers Day!


答: The server header can also be handy when standing up and troubleshooting non-trivial setups and DNS issues. It can help tell you if a request is hitting the right at crucial junctures. We send a number of custom headers to help with this sort of issue as well but the out of the box ones can be handy too.

Title: Why HTTP Servers send information about themselves in HTTP Headers?

Body:
Most of the HTTP Servers I know send their application name and version in response http headers as default behaviour. (Nginx, IIS, Apache etc.) Of course we can change the default behaviour but I wonder why they send these information? Does it matter which HTTP Servers we use to the requesters?

The only reason I can think of is to allow analytics services to keep track of which HTTP Servers are widely used by websites but otherwise these information are unnecessary for most of the requests and when an attacker figures out a specific version of a HTTP Server has a bug, he can easily find websites which uses that version and use that information against these websites.


问:
Whats an Ideal way to pass rules/options to methods that build SQL
We're trying to come up with a way to handle code that builds dynamic SQL for our application, which is very database centric. Things like Linq to SQL and Entity Framework are out of the question, so please no suggestions of that sort, our path has been defined for us.

Our main goal is seperation of the SQL from the rest of the code (business logic etc).

Right now, we're thinking of using extension methods to house the SQL, and coming up with some sort of configuration object that developers can use to define how the query should be built (dictated by business logic, outside of the Extension class)

So for example, I have some prototype code below. The developers would setup the Configuration Struct (as per business rules), and pass that to GetSQL.

```<code>public static class LocationSql2Extension
{

    public enum SelectFields
    {
        Default,
        DefaultAnd_Description_LocationSize
    }

    public enum FilterBy
    {
        Default,
        DefaultAnd_Description
    }

    public enum OrderBy
    {
        Default,
        DefaultAnd_LocationType_LocationID_Description
    }

    public struct Configuration
    {
        public SelectFields SelectFields;
        public FilterBy FilterBy;
        public OrderBy OrderBy;
    }

    public static string GetSQL(this LocationService2 service, Configuration config)
    {

        string sqlSelectFields = string.Empty;
        string sqlWhere = string.Empty;
        string sqlOrderBy = string.Empty;

        if (config.SelectFields == SelectFields.DefaultAnd_Description_LocationSize)
        {
            sqlSelectFields = ", Description, LocationSize";
        }

        if (config.FilterBy == FilterBy.DefaultAnd_Description)
        {
            sqlWhere = "WHERE L.Description = ?";
        }

        if (config.OrderBy == OrderBy.DefaultAnd_LocationType_LocationID_Description)
        {
            sqlOrderBy = ", L.LocationDescription";
        }

        string sql = string.Format(@"
                                       SELECT L.LocationType, L.LocationId
                                              {0}
                                       FROM Location AS L
                                       INNER JOIN GroupLoc AS GL
                                       ON  L.LocationType = GL.LocationType
                                           AND L.LocationId = GL.LocationId
                                           AND GL.SecLocLevel >= 4
                                           AND GL.GroupId = ?
                                       {1}
                                       ORDER BY L.LocationType||L.LocationId
                                       {2}
                                      ", sqlSelectFields, sqlWhere, sqlOrderBy);

        return sql;

    }
}
</code>```

and to call the above code, we have this:

```<code>public class LocationService2
{
    public string BuildSql()
    {
        var config = new LocationSql2Extension.Configuration();

        //TODO: Add Business Logic to drive these values
        config.SelectFields = LocationSql2Extension.SelectFields.Default;
        config.OrderBy = LocationSql2Extension.OrderBy.DefaultAnd_LocationType_LocationID_Description;
        config.FilterBy = LocationSql2Extension.FilterBy.DefaultAnd_Description;

        return this.GetSQL(config);

    }
}
</code>```

Developers would be free to setup the Enum's any way they like, and this is just a simple example. We're not comfortable with this Enum/Struct approach, and are looking for something more generic thats easy for developers to work with, but isn't so generic that it won't catch any errors at design time. This is a simple example, and we have some very large and complex queries in our system. Any suggestions?

答:
What you are saying is that you can't use a well supported ORM so you are trying to invent your own limited ORM to compensate. That isn't going to go well. Performance-wise the modern ORMs stand up very well and they are fluent enough to let you do most operations you can do with a database server in raw SQL.

That said, if you want to go down this sort of path you would be more successful letting SQL be SQL and exposing a logical API to your codebase. What that means from a practical perspective is to not build an object like your example that exposes generic data methods but rather expose query builders that are a bit more meaningful. Internally you could build some helper classes and base classes to handle some of the grunt work of sql generation but in general if you are going to hand build the SQL you might as well take advantage of the fluency of SQL and hand build the SQL. This isn't particularly scalable but if the domain is well defined you can get away with it.

For what it's worth we often take this sort of query definition approach and wrap it around an ORM so our client code is relatively unaware of the database mechanics behind the curtain.


问:
Where should you put functions and variables that are only needed by one function in a class?
Say you have a Car class. Properties that make sense for a Car class might be:

```<code>var make;
var model;
var year;
var turnOn; // a function
</code>```

But the turnOn function is very complicated and ends up needing a static variable and a couple sub functions:

```<code>var isTurningOn; // too specific to be a class variable
function turnOn() {
    // 30 lines to start the engine
    // 30 lines to start the air conditioner
    // 30 lines to start the radio
}
</code>```

So now we have a function that maybe isn't really suitable to be made into its own class and it's polluting the Car class with a variable that only the turnOn function ever uses. Plus the function contains sections of code that should be made into their own functions. So what do you do in situations like this?

答:
120+ lines of code requiring sub-functions could easily become it's own vehicleStarter class rather than needing to be embedded. This is likely the approach I would take here.

If you are committed to directly embedding the function I would just put the function's variables within the body of the function which typically scopes them to just that function in most platforms and at least indicates that these are local variables to readers. As for sub-functions you can handle that in different ways depending upon platforms. If the platform supports functional programming concepts then you can usually find a way to declare a variable as a function and effectively treat them as variables. This certainly works in javascript which is what I'm guessing you are writing based on your example.


答:
If a variable is only needed by a single function, the variable should be in the function that uses it. This will help to keep the rest of the class clean. If the rest of the class doesnt use that variable, it shouldnt have to ever care about that variable or know it even exists.

As for the 30 lines each to start the various components, like engine, radio, etc., do you think those components should really instead be in their own class? That would mean the "turnOn" function is trimmed down to 3 lines of code (or 1 line per component to turn on).  The car class then also shouldnt be responsible for creating the components like engine, etc. Instead, a constructor of the Car class should be created to accept all of its components as parameters. When you think in the real world, car doesnt create its engine, a factory does. So you could create an "EngineFactory", "RadioFactory", etc. class to create the individual components. All of those components would then be passed to a "CarFactory", which just calls the Car constructor with all of its components.

Title: Where should you put functions and variables that are only needed by one function in a class?

Body:
Say you have a Car class. Properties that make sense for a Car class might be:

```<code>var make;
var model;
var year;
var turnOn; // a function
</code>```

But the turnOn function is very complicated and ends up needing a static variable and a couple sub functions:

```<code>var isTurningOn; // too specific to be a class variable
function turnOn() {
    // 30 lines to start the engine
    // 30 lines to start the air conditioner
    // 30 lines to start the radio
}
</code>```

So now we have a function that maybe isn't really suitable to be made into its own class and it's polluting the Car class with a variable that only the turnOn function ever uses. Plus the function contains sections of code that should be made into their own functions. So what do you do in situations like this?


答:
At least for the example you have given it seems approprioate to use the state-pattern to describe your Car class best.

When creating the car you not only pass the needed dependencies (like the engine, when it was created and so on) as arguments into the constructor but also the very first state implementing an Interface ICarState. You could call that for example NoActionState and save it into a private class member like the year or model.

Later when your car is started, you dont change an isTurningOn variable but replace the NoActionState instance with a new instance of EngineStartingState. The advantage is now that you don't have to use many conditions to check for private variables like isTurningOn to react proper to the given state but you can instead let your state classes implement the desired behaviour.

And when your car has the ability to start then i guess the next state after it will have started would be the DrivingState. Another advantage is that you can now also add new states when new functionality is needed without having the change the logics in the other state classes.

This way you solved your problem in a way that the state information you used your isTurningOn variable for is now saved in a state variable containg the current state of your car and the more detailled information for the current state is saved in its own class.


问:
Handling ignorable failure conditions in a method
I'm working on a coarse API for performing higher level business functions.  Under many conditions these functions may fail in a way that is expected (not exceptional), ie. the function may not be able to complete because of failing a validation condition of some kind.

In many cases, what I want to do in these "failure" scenarios is to alert the user and give them the option to "override" the failure.  ie, "Warning: transferring warp power to the shields will damage the emitter array, are you sure you want to proceed?"

Many of these functions may have a list of quite a few validation rules and I may want to override all of them.

What I'm envisioning right now is to create a custom MyResult class that is returned by the functions that includes whether or not the function succeeded and if it failed, perhaps a list of validation rules that failed for the function.  Then add a parameter to the function for "overrides" that allows these validation rules to be bypassed in a subsequent call.  I'd like feedback on this approach.  Is there a pattern for this?

The functions in the API may be called from multiple platforms and the API itself is in C#.

答: I wouldn't bother. I'd create a second API call that does no validation for any rule that you feel should be overridable by the user, and then have the client decide to call the validated logic first, and then if the user chooses, call the unvalidated method afterwards.  It greatly simplifies the problem so that you don't need to have a whole lot of if() statements wrapping everything.</p>


答:
With complex logic like that I would make the "business function" into separate object, quite similar to command pattern. Then, you can have interface like this:

```<code>interface IBusinessFunction
{
    Result Start();
    Result Continue();
    void Cancel();
}
</code>```

The Result might indicate, that the function finished or it can indicate it requires user to either override, in which case he executes Continue or Cancel the whole function. The major advantage of this it allows generic handling of those function in UI. The UI just needs to know about this interface to be able to correctly allow overriding or canceling the functions. Also, you don't have to restart the whole function every time it gets aborted and overriden, because it keeps the state in the instance.

Title: Handling ignorable failure conditions in a method

Body:
I'm working on a coarse API for performing higher level business functions.  Under many conditions these functions may fail in a way that is expected (not exceptional), ie. the function may not be able to complete because of failing a validation condition of some kind.

In many cases, what I want to do in these "failure" scenarios is to alert the user and give them the option to "override" the failure.  ie, "Warning: transferring warp power to the shields will damage the emitter array, are you sure you want to proceed?"

Many of these functions may have a list of quite a few validation rules and I may want to override all of them.

What I'm envisioning right now is to create a custom MyResult class that is returned by the functions that includes whether or not the function succeeded and if it failed, perhaps a list of validation rules that failed for the function.  Then add a parameter to the function for "overrides" that allows these validation rules to be bypassed in a subsequent call.  I'd like feedback on this approach.  Is there a pattern for this?

The functions in the API may be called from multiple platforms and the API itself is in C#.

Body:
With complex logic like that I would make the "business function" into separate object, quite similar to command pattern. Then, you can have interface like this:

interface IBusinessFunction
{
    Result Start();
    Result Continue();
    void Cancel();
}

The Result might indicate, that the function finished or it can indicate it requires user to either override, in which case he executes Continue or Cancel the whole function. The major advantage of this it allows generic handling of those function in UI. The UI just needs to know about this interface to be able to correctly allow overriding or canceling the functions. Also, you don't have to restart the whole function every time it gets aborted and overriden, because it keeps the state in the instance.


问:
How can I promote clean coding at my workplace?
I work with a lot of legacy Java and RPG code on an internal company application. As you might expect, a lot of the code is written in many different styles, and often is difficult to read because of poorly named variables, inconsistent formatting, and contradictory comments (if they're there at all).

Also, a good amount of code is not robust. Many times code is pushed to production quickly by the more experienced programmers, while code by newer programmers is held back by "code reviews" that IMO are unsatisfactory. (They usually take the form of, "It works, must be ok," than a serious critique of the code.) We have a fair number of production issues, which I feel could be lessened by giving more thought to the original design and testing.

I have been working for this company for about 4 months, and have been complimented on my coding style a couple of times. My manager is also a fan of cleaner coding than is the norm. Is it my place to try to push for better style and better defensive coding, or should I simply code in the best way I can, and hope that my example will help others see how cleaner, more robust code (as well as aggressive refactoring) will result in less debugging and change time?

答: You didn't mention your level of expertise on the subject. If you are not a senior programmer however, I think the best thing you can do is to do your own work well. You also mentioned that your manager likes clean work - that's great. If you can talk to him about it (maybe in a semi-professional environment) you should share your concerns about the issue with him. HE is in the position to change workflow.</p>


问:
High-Level Classes and Low-Level Classes
I've seen at SOLID there is a principle Dependency inversion principle.

Also I've seen that: High-level Classes should not depend on Low-level Classes but both of them should depend on abstractions.

What exactly means High-Level Classes and Low-Level Classes?

答:
I really like explanation in this article : DIP in the wild.

To sum it up the high-level and low-level are in relation do domain model. For example, creating report is high-level while getting data for that report and printing those data are low-level operations.


答:
Low level classes are the simple workers that perform actions, while high level classes are the management class that orchestrate the low level classes.

For example, if you have a class that reads bytes from a file and a class that calculates the CRC of bytes, they are low level classes because each performs an action. If you have a class that uses those two classes to calculate the CRC of a file it's a high level class, because it operates the other classes to accomplish a bigger task.

DiP says that the high level class should not depend directly on the low level classes, but rather get objects of those classes(or factory objects that create them) injected into it, and depend on more generic interfaces - for example, an interface for classes that read bytes and an interface for classes that aggregate bytes. That the higher level class, instead of just doing CRC on files, it could also do MD5 on URLs or any other type of aggregation on any other type of data source.

Keep in mind there are more than just two level. The high level class from the example can be a low level component for an even higher level class, that performs a more complex task.

Another thing to keep in mind is that like any other rule, DiP should not be followed blindly. I've explained in another answer that some low level classes are too small to be decouple-worthy. Also, at some point you'll have to refer low level classes directly from high level classes. High level classes that get low level objects injected into them - who does the injection? Even higher level classes! That means that in some points high level classes have to use low level classes directly. Your main method is the highest there is, and you can't inject anything into it. That doesn't mean you should do all the injection in the main method - deciding where to choose the concrete low level classes is part of the design process.

Body:
I've seen at SOLID there is a principle Dependency inversion principle.

Also I've seen that: High-level Classes should not depend on Low-level Classes but both of them should depend on abstractions.

What exactly means High-Level Classes and Low-Level Classes?


问:
When to use python function nesting?
I am writing a program that creates backup of directories.

Which of the following approach is better for code organization?

Create separate class for Backup and Zip logic -

```<code>class BackupUtil:
    def backup(self):
       None

class ZipUtil:
    def archive_dir(self):
       None
</code>```

Or use function nesting like this -

```<code>class BackupUtil:
    def backup(self):
        def archive_dir():
            None
        None
</code>```

答:
TL;DR: Use function nesting when you need the characteristics of function nesting

Function Nesting Use Cases (mostly functional idioms, almost certainly incomplete since it's off the top of my head):

closures

function factory (programmatic function creation based on parameters)

creating functions by calling functool.partial

creating functions by using lambda

any other reasons you need to create functions during call time

Trade-offs:

functions are strongly coupled

the code is always called (unless it's in an if block)

additional code complexity

additional runtime cost (potentially, because the inner function get's re-defined with every call to the outer function)

much harder to extend

much harder to introspect on the inner function defintion

Title: When to use python function nesting?


问:
Domain Services vs. Factories vs. Aggregate Roots
After dealing with DDD for months now, I'm still confused about the general purposes of domain services, factories and aggregate roots in relation to each other, e.g. where they overlap in their responsibility.

Example: I need to 1) create a complex domain entity in a saga (process manager) which is followed by 2) a certain domain event that needs to be handled elsewhere whereas 3) the entity is clearly an aggregate root that marks a bounded context to some other entities.

The factory IS be responsible for creation of the entity/aggregate root

The service CAN create the entity, since he also throws the domain event

The service CAN act as a aggregate root (create 'subentity' of 'entity' with ID 4)

The aggregate root can create and manage 'subentities'

When I introduce the concept of a aggregate root as well as a factory to my domain, a service seems no longer needed. However, if I'm not, the service can handle everything needed as well with the knowledge and dependencies he has.

Code Example
based on the ubiquitous language of a car repair shop

```<code>public class Car : AggregateRoot {

    private readonly IWheelRepository _wheels;
    private readonly IMessageBus _messageBus;

    public void AddWheel(Wheel wheel) {
        _wheels.Add(wheel);
        _messageBus.Raise(new WheelAddedEvent());
    }

}

public static class CarFactory {

    public static Car CreateCar(string model, int amountofWheels);

}
</code>```

..or...

```<code>public class Car {

    public ICollection<Wheel> Wheels { get; set; }

}

public interface ICarService {

    Car CreateCar(args);
    void DeleteCar(args);
    Car AddWheel(int carId, Wheel wheel);

}
</code>```

答:
DDD is in part a reaction to anaemic domain models, where your entities would only have state, but not behaviour.

It's true that in a sense you could put all the behaviour of Car in a separate service, but why would you want to? For that to work, you'd need to expose all sorts of state in Car, which you would normally like to keep private (like Wheels).

If you expose Wheels like that, any code could do all sorts of funky stuff to that collection, outside of any normal business flow. Keep in mind that the point of an aggregate is to have something that is transactionally consistant between business flow transactions. Exposing Wheels like that completely undermines that safety.

For example: say your business only wants to support cars with four wheels. If you encapsulate access to Wheels, you can enforce that. If you don't, it's completely possible to add a hundred wheels to a car, because Wheels would be exposed.

A service is generally used as a coordinator. A commandhandler (assuming something like CQRS) translates a command object to more strongly typed parameters, reducing primitive obsession. Then it can call a service with those more "domain-ish" parameters. The service retrieves entities from repositories and invokes behaviours on them. Depending on your architecture, it can then collect any changes (events) and pass them to a bus or whatever.

In more advanced scenarios, you'd use a unit of work that keeps track of all your entities and can collect the changes from all of them in one swoop.

As for a factory (as an aside), nothing's stopping you from adding a static factory method your aggregate class, instead of creating a separate factory.


问:
Does OOP fulfill the promise of code reuse? What alternatives are there to achieve code reuse?
Perhaps the greatest promise of using object-oriented paradigm is the code reuse. Some dispute that this was achieved. Why was it (not) achieved?

Does code reuse as OOP defines it, make projects more productive?

Or more manageable? Or easier to maintain? Or with more quality?

Probably we all agree that code reuse is a good thing, but there are several ways to achieve this goal. The question is about the method of code reuse offered by OOP. Was it a good thing? Are there better methods to achieved code reuse than object orientation, sub-classing, polymorphism, etc.? What ways are better? Why?

Tell us your experience with OOP reuse or other paradigms reuse.

答:
I'm going to risk ridicule and confess, I've only been using OOP very recently. It doesn't come to me automatically. Most of my experience involves relational databases, so I think in tables and joins. There are claims that it is better to learn it from the beginning which avoids having to rewire your thinking when it comes to programming. I don't have that luxury and refuse to scrap my career over some ivory tower theory. Like everything else, I'll figure it out.

At first I thought the whole concept didn't make sense. It just seemed unnecessary and too much trouble. I know, this is crazy talk. Obviously it takes a certain level of understanding before you can appreciate the benefits of anything or dismiss it for better methods.

Code reuse takes a willingness to not repeat code, an understanding of how to accomplish it, upfront planning. Should you avoid reusing code when you've decided you have a case where it's just not worth it? And no language is so strictly OO that it will throw an error when it thinks you should have inherited code from another class. At best they provide an environment conducive to implementing it.

I think the biggest benefit of OOP is the general acceptance of how code should be organized. Everything else is gravy. A team of programmers may not fully agree on how all the classes should be structured, but they should be able to find the code.

I've seen enough procedural code to know it could be anywhere, and sometimes it's everywhere.