问:
How can a beginner develop an algorithm for this problem?
Before I'm flamed, I'm just a beginner in programming. I have been learning Python for about 1 week by myself.

I have a real problem to solve:

Goal: The fastest route through a pathway.

Problem:

Walk forward to get to the goal. The pathway is 128 steps.

Walking 1 step increases the danger value by 113

If the danger value is over the limit then there is a fight. The fight takes 15 seconds to win.

The limit is randomly assigned on each step.

The danger value resets to 0 after a fight.

Here's the essence of the problem though:

There are two possible options if there is a fight:

The fight can be escaped. Escaping takes 2 seconds. But does NOT reset the danger value.

Accept the fight. Resets the danger value.

The higher the danger value, the higher the chance of getting a fight.

I've written the code to take one step. And I've written the code for the relevant randomness of the danger value, etc.

I've even made a graph that shows exactly the pathway and potential fights, with the respective limits. This graph shows what happens when you accept every fight (don't escape):

Being self-taught, I just don't know how to write a search algorithm for finding the quickest way through a particular route. I believe I need to write a backtracking algorithm; essentially a kind of brute force.

I just don't know how to translate it from english into code. It's been around 4 days of just thinking about this, and I cannot write anything that expresses the even attempts to solve the problem.

Any books or advice on how to even start solving this?

As I've said, I have all of the code for what happens on each step (here: http://pastebin.com/LnV4h9NV).

I just don't know how to even begin trying to brute force/search.

答:
This is the problem as far as I can see it:

Each field has a random, unknown “danger level” ℓi that is evenly distributed across a certain interval [ℓmin, ℓmax]. So on average, the level is ℓ = (ℓmin + ℓmax)/2.

Moving to the next field has a fixed cost Δcm.

Each move increases the “danger” d by Δd.

If d > ℓi after a move, then two options can be taken:

The total cost may increase by Δcr = 2 (running away), or

The total cost may increase by Δcf = 15 (fighting), in which case d is reset to zero.

The probability p(F) that d > ℓi, i.e. that a fight occurs, is 0 if d < ℓmin, else (d - ℓmin)/(ℓmax - ℓmin).

So our problem has the fixed parameters ℓmin, ℓmax, Δd, Δcm, Δcr, Δcf and the state variables c and d. We have the following possible state transitions:

No fight: With a probability of 1-p(F), nothing happens. then:

c ← c + Δcm

d ← d + Δd

A fight: With a probablity of p(F), we can choose the options

c ← c + Δcm + Δcr

d ← d + Δd

c ← c + Δcm + Δcf

d ← 0

Your questions seems to be how the total cost c can be minimized. In this statistical model, there is no definitive c. Instead, we will have to minimize the expected value for c. We can brute-force this by examining a decision tree. Each tree has can be assigned an expected cost, which can be calculated from the subtrees like

c = min(cF, f, cF, r) · p(F) + c¬F · (1-p(F))

where cF, f is the expected cost when fighting a fight at these conditions etc..

The following pseudocode gets the expected cost given a certain state:

```<code>function expected_cost(i, c, d) {
  return c if i == 0;

  p = probability_of_fight(d);

  c_no_fight      = (1-p) * expected_cost(i - 1, c + Δc_m,        d + Δd);

  c_fight_run, c_fight_fight = 0, 0;
  if (p > 0) {
    c_fight_run   =    p  * expected_cost(i - 1, c + Δc_m + Δc_r, d + Δd);
    c_fight_fight =    p  * expected_cost(i - 1, c + Δc_m + Δc_f, 0     );
  }

  return c_no_fight + min(c_fight_run, c_fight_fight);
}
</code>```

Now all that has to be added is keeping track of which decisions were made in the winning paths – note that there are multiple winning paths, because either a fight may occur, or may not at each field. The decision we keep track of is whether the fight is carried out, or fled. Interesting analyses might be how often a fight is fled or fought – in this case, returning further values with the respective counts seems like the thing to do. Otherwise, inspecting a tree with the decision histories might be interesting.

Care should be taken to run that with very small i, as the tree can get very large (up to 3i). Memoization will help prevent some unneccessary calculations.

Depending on how you code the above algorithm, runtime can vary extremely. Below is a Perl script I used, which uses extensive caching to achieve a runtime in the order of seconds (if the current cost is a key in the cache as well, runtime is in the order of minutes). It performs an example analysis of counting how often running away and fighting is more beneficial. With those parameters, commiting to a fight isn't a viable strategy before the game is 123 fields long.

use strict;
use warnings;
no warnings qw/recursion/;
use feature qw/state/;
use utf8;

use Math::BigInt;  # not neccessary. alternatively: no warnings 'imprecision'

# parameters as explained in answer
my ($ℓ_min, $ℓ_max, $Δd, $Δc_m, $Δc_r, $Δc_f) =
   (0xFF,   0xFF**2,113, 1,     2,     15   );

my ($steps) = @ARGV or die <<USAGE;
usage:
  $0 iterations

parameters:
  iterations -- the number of fields to traverse
USAGE

my ($cost, $fight, $run) = expected_cost($steps, 0);
printf "expected cost for i=%d steps is %g\n",
    $steps, $cost;
printf "fight won %.3e times\n",
    $fight;
printf "run   won %.3e times\n",
    $run;
printf "fight:run relation: %s\n",
    ($run > $fight) ? sprintf('1:%.3e', $run/$fight) : sprintf('%.3e:1', $fight/$run);

sub probability_of_fight {
    my ($d) = @_;
    return $d < $ℓ_min ? 0 : ($d - $ℓ_min)/($ℓ_max - $ℓ_min);
}

# Takes number $i of fields left and accumulated danger $d
# Return expected cost for that subtree, plus favourable fights and fleeings.
sub expected_cost {
    my ($i, $d) = @_;
    return 0, 0, 0 if $i == 0;

    state $cache = [];
    my $retval = $cache->[$i][$d] //= do {
        my $p = probability_of_fight($d);

        # variable prefixes:
        # nf -- no fight
        # f  -- fight
        # fr -- fight, but run away
        # ff -- fight, and carry out the fight

        my ($nf_c, $nf_fight, $nf_run)     = expected_cost($i - 1, $d + $Δd);

        my $f_c = 0;
        my ($f_fight, $f_run) = (Math::BigInt->new, Math::BigInt->new);
        if ($p > 0) {
            my ($fr_c, $fr_fight, $fr_run) = expected_cost($i - 1, $d + $Δd);
            $fr_c += $Δc_r;

            my ($ff_c, $ff_fight, $ff_run) = expected_cost($i - 1, 0       );
            $ff_c += $Δc_f;

            if ($ff_c < $fr_c) {
                # fighting is cheaper
                $f_c     = $ff_c;
                $f_fight = $ff_fight + 1;
                $f_run   = $ff_run;
            }
            elsif ($ff_c > $fr_c) {
                # running away is cheaper
                $f_c     = $fr_c;
                $f_fight = $fr_fight;
                $f_run   = $fr_run + 1;
            }
            else {
                # both are equivalent
                $f_c     = $ff_c;
                $f_fight = $ff_fight + $fr_fight;
                $f_run   = $ff_run   + $fr_run;
            }
        }

        my $expected_cost = $Δc_m + (1-$p) * $nf_c + $p * $f_c;
        [$expected_cost, $nf_fight + $f_fight, $nf_run + $f_run];
    };

    return @$retval;
}
```

<p>Example session:</p>

```$ perl decide.pl 128
expected cost for i=128 steps is 154.27
fight won 2.432e+17 times
run   won 5.317e+36 times
fight:run relation: 1:2.186e+19
```

… where “won” means “occurs this often in the best decision tree”. This roughly translates to a probability of which decision is likely to be cheaper.

I had some time for further analysis. For each field, we can calculate if, when a fight occurs at this position, we should rather flee or fight. I plotted the result below:

… which uses the parameters from the above script.

How to read this graph: The x-axis is the distance from the end of the field, i.e. the number of steps (and thus fights) that can still occur. The y-axis is the danger level you have accumulated. If a player has to fight, he can find his distance-danger coordinate. If that coordinate is red, fighting will have the least cost. If the coordinate is colored blue, then fleeing is probably cheaper.

We can see that for example, during the last 7 steps fighting is never the best choice (the graph is already maxed out). Otherwise, the preference varies periodically. Fighting is most likely to be interesting at around 70–60 steps away from the end.

Body:
This is the problem as far as I can see it:

Each field has a random, unknown “danger level” ℓi that is evenly distributed across a certain interval [ℓmin, ℓmax]. So on average, the level is ℓ = (ℓmin + ℓmax)/2.

Moving to the next field has a fixed cost Δcm.

Each move increases the “danger” d by Δd.

If d > ℓi after a move, then two options can be taken:

The total cost may increase by Δcr = 2 (running away), or

The total cost may increase by Δcf = 15 (fighting), in which case d is reset to zero.

The probability p(F) that d > ℓi, i.e. that a fight occurs, is 0 if d < ℓmin, else (d - ℓmin)/(ℓmax - ℓmin).

So our problem has the fixed parameters ℓmin, ℓmax, Δd, Δcm, Δcr, Δcf and the state variables c and d. We have the following possible state transitions:

No fight: With a probability of 1-p(F), nothing happens. then:

c ← c + Δcm

d ← d + Δd

A fight: With a probablity of p(F), we can choose the options

c ← c + Δcm + Δcr

d ← d + Δd

c ← c + Δcm + Δcf

d ← 0

Your questions seems to be how the total cost c can be minimized. In this statistical model, there is no definitive c. Instead, we will have to minimize the expected value for c. We can brute-force this by examining a decision tree. Each tree has can be assigned an expected cost, which can be calculated from the subtrees like

c = min(cF, f, cF, r) · p(F) + c¬F · (1-p(F))

where cF, f is the expected cost when fighting a fight at these conditions etc..

The following pseudocode gets the expected cost given a certain state:

function expected_cost(i, c, d) {
  return c if i == 0;

  p = probability_of_fight(d);

  c_no_fight      = (1-p) * expected_cost(i - 1, c + Δc_m,        d + Δd);

  c_fight_run, c_fight_fight = 0, 0;
  if (p > 0) {
    c_fight_run   =    p  * expected_cost(i - 1, c + Δc_m + Δc_r, d + Δd);
    c_fight_fight =    p  * expected_cost(i - 1, c + Δc_m + Δc_f, 0     );
  }

  return c_no_fight + min(c_fight_run, c_fight_fight);
}

Now all that has to be added is keeping track of which decisions were made in the winning paths – note that there are multiple winning paths, because either a fight may occur, or may not at each field. The decision we keep track of is whether the fight is carried out, or fled. Interesting analyses might be how often a fight is fled or fought – in this case, returning further values with the respective counts seems like the thing to do. Otherwise, inspecting a tree with the decision histories might be interesting.

Care should be taken to run that with very small i, as the tree can get very large (up to 3i). Memoization will help prevent some unneccessary calculations.

Depending on how you code the above algorithm, runtime can vary extremely. Below is a Perl script I used, which uses extensive caching to achieve a runtime in the order of seconds (if the current cost is a key in the cache as well, runtime is in the order of minutes). It performs an example analysis of counting how often running away and fighting is more beneficial. With those parameters, commiting to a fight isn't a viable strategy before the game is 123 fields long.

use strict;
use warnings;
no warnings qw/recursion/;
use feature qw/state/;
use utf8;

use Math::BigInt;  # not neccessary. alternatively: no warnings 'imprecision'

# parameters as explained in answer
my ($ℓ_min, $ℓ_max, $Δd, $Δc_m, $Δc_r, $Δc_f) =
   (0xFF,   0xFF**2,113, 1,     2,     15   );

my ($steps) = @ARGV or die <<USAGE;
usage:
  $0 iterations

parameters:
  iterations -- the number of fields to traverse
USAGE

my ($cost, $fight, $run) = expected_cost($steps, 0);
printf "expected cost for i=%d steps is %g\n",
    $steps, $cost;
printf "fight won %.3e times\n",
    $fight;
printf "run   won %.3e times\n",
    $run;
printf "fight:run relation: %s\n",
    ($run > $fight) ? sprintf('1:%.3e', $run/$fight) : sprintf('%.3e:1', $fight/$run);

sub probability_of_fight {
    my ($d) = @_;
    return $d < $ℓ_min ? 0 : ($d - $ℓ_min)/($ℓ_max - $ℓ_min);
}

# Takes number $i of fields left and accumulated danger $d
# Return expected cost for that subtree, plus favourable fights and fleeings.
sub expected_cost {
    my ($i, $d) = @_;
    return 0, 0, 0 if $i == 0;

    state $cache = [];
    my $retval = $cache->[$i][$d] //= do {
        my $p = probability_of_fight($d);

        # variable prefixes:
        # nf -- no fight
        # f  -- fight
        # fr -- fight, but run away
        # ff -- fight, and carry out the fight

        my ($nf_c, $nf_fight, $nf_run)     = expected_cost($i - 1, $d + $Δd);

        my $f_c = 0;
        my ($f_fight, $f_run) = (Math::BigInt->new, Math::BigInt->new);
        if ($p > 0) {
            my ($fr_c, $fr_fight, $fr_run) = expected_cost($i - 1, $d + $Δd);
            $fr_c += $Δc_r;

            my ($ff_c, $ff_fight, $ff_run) = expected_cost($i - 1, 0       );
            $ff_c += $Δc_f;

            if ($ff_c < $fr_c) {
                # fighting is cheaper
                $f_c     = $ff_c;
                $f_fight = $ff_fight + 1;
                $f_run   = $ff_run;
            }
            elsif ($ff_c > $fr_c) {
                # running away is cheaper
                $f_c     = $fr_c;
                $f_fight = $fr_fight;
                $f_run   = $fr_run + 1;
            }
            else {
                # both are equivalent
                $f_c     = $ff_c;
                $f_fight = $ff_fight + $fr_fight;
                $f_run   = $ff_run   + $fr_run;
            }
        }

        my $expected_cost = $Δc_m + (1-$p) * $nf_c + $p * $f_c;
        [$expected_cost, $nf_fight + $f_fight, $nf_run + $f_run];
    };

    return @$retval;
}

Example session:

$ perl decide.pl 128
expected cost for i=128 steps is 154.27
fight won 2.432e+17 times
run   won 5.317e+36 times
fight:run relation: 1:2.186e+19

… where “won” means “occurs this often in the best decision tree”. This roughly translates to a probability of which decision is likely to be cheaper.

I had some time for further analysis. For each field, we can calculate if, when a fight occurs at this position, we should rather flee or fight. I plotted the result below:

… which uses the parameters from the above script.

How to read this graph: The x-axis is the distance from the end of the field, i.e. the number of steps (and thus fights) that can still occur. The y-axis is the danger level you have accumulated. If a player has to fight, he can find his distance-danger coordinate. If that coordinate is red, fighting will have the least cost. If the coordinate is colored blue, then fleeing is probably cheaper.

We can see that for example, during the last 7 steps fighting is never the best choice (the graph is already maxed out). Otherwise, the preference varies periodically. Fighting is most likely to be interesting at around 70–60 steps away from the end.


问:
Is open source development considered "commercial use" of software?

The Software Setup:

I am currently planning on creating a new software product. I have never commercially launched an application, nor am I doing this for a company. It's more for fun than anything, but it may bring in some cash too. :P Anyway, there are going to be two "core parts" of the software:

Part Number One: This one I am going to release open source. It's basically an installer/launcher/patcher that automatically checks for updates, it can handle error reporting, etc. Blah, blah, blah.

Part Number Two: This is going to be the actual software. Closed source, but freeware. It's linked to an account, which can be either free or paid.

The Problem:

So that's all fine above... until I realise my development computer has a lot of "freeware for non-businesses and paid for businesses" software. (Office, antivirus, and who knows what else?) I know I will definitely have to do something about the software for the for-profit part, but how about the open source part? It is free, but the whole intention of developing it is for adding it to a bigger, paid software.

答:
Arguably you have a moral obligation to pay for the software. It is being used to develop the open source component used to support a commercial product. You may be able to legally establish a case that its not commercial, but that is likely against the spirit and intent of the licenses. </p>

<p>Paying for the software is almost certainly cheaper than hiring a lawyer to find out if you need to pay. If the vendor approaches you after the fact, it could get messy and expensive. If you cannot afford the software, the easiest thing would be to ask the vendor(s) and put your case for using under the free use license. Most likely this will receive favorable response. </p>

ContentLicense: CC BY-SA 3.0

Body:
Arguably you have a moral obligation to pay for the software. It is being used to develop the open source component used to support a commercial product. You may be able to legally establish a case that its not commercial, but that is likely against the spirit and intent of the licenses.

Paying for the software is almost certainly cheaper than hiring a lawyer to find out if you need to pay. If the vendor approaches you after the fact, it could get messy and expensive. If you cannot afford the software, the easiest thing would be to ask the vendor(s) and put your case for using under the free use license. Most likely this will receive favorable response.


问:
Does setting a function public affect the C# compiler's ability to inline the function as an optimization?
This could be either for the .NET or Mono compilers.

I know that under certain conditions the compiler can inline functions (e.g. small, single call site, etc.) as an optimization.  However, if the function is public, then it needs to have an external entry point.

In these cases, is duplicated code generated (public entry point which isn't used by the internal code since the internal code uses the inlined version), or does marking it as public prevent the compiler from doing such an optimization?

答:
I found this interesting article on C# inline methods.

Scope of a method doesn't appear to change when a function becomes an inline candidate. Here is a summary of that article.

How to determine what get’s inlined? The short answer is that you can’t. The MSDN article “Writing High-Performance Managed Applications : A Primer” gives the following guidance:

Methods that are greater than 32 bytes of IL will not be inlined.

Virtual functions are not inlined.

Methods that have complex flow control will not be in-lined. Complex flow control is any flow control other than if/then/else; in this case, switch or while.

Methods that contain exception-handling blocks are not inlined, though methods that throw exceptions are still candidates for inlining.

If any of the method’s formal arguments are structs, the method will not be inlined.

There is no inline keyword in C#, but there is an inline compiler directive that was introduced in .NET 4.5 called MethodImplOptions.AggressiveInlining

It can be used like this.

```<code>[MethodImpl(MethodImplOptions.AggressiveInlining)]
static int Method2()
{
// ... Aggressive inlining.
return "one".Length + "two".Length + "three".Length +
    "four".Length + "five".Length + "six".Length +
    "seven".Length + "eight".Length + "nine".Length +
    "ten".Length;
}
</code>```

You can't know for sure if the compiler will inline a function. This isn't feature C# developers have control over.

Body:
I found this interesting article on C# inline methods.

Scope of a method doesn't appear to change when a function becomes an inline candidate. Here is a summary of that article.

How to determine what get’s inlined? The short answer is that you can’t. The MSDN article “Writing High-Performance Managed Applications : A Primer” gives the following guidance:

Methods that are greater than 32 bytes of IL will not be inlined.

Virtual functions are not inlined.

Methods that have complex flow control will not be in-lined. Complex flow control is any flow control other than if/then/else; in this case, switch or while.

Methods that contain exception-handling blocks are not inlined, though methods that throw exceptions are still candidates for inlining.

If any of the method’s formal arguments are structs, the method will not be inlined.

There is no inline keyword in C#, but there is an inline compiler directive that was introduced in .NET 4.5 called MethodImplOptions.AggressiveInlining

It can be used like this.

[MethodImpl(MethodImplOptions.AggressiveInlining)]
static int Method2()
{
// ... Aggressive inlining.
return "one".Length + "two".Length + "three".Length +
    "four".Length + "five".Length + "six".Length +
    "seven".Length + "eight".Length + "nine".Length +
    "ten".Length;
}

You can't know for sure if the compiler will inline a function. This isn't feature C# developers have control over.


答:
"Commercial use" is a nebulous term that is of little use when it comes to activity that is not actually commerce -- that is, buying and selling goods or services.

You should examine the EULA's of each software package with a "no commercial use" clause for a definition of what exactly "commercial use" means.  If you don't find one or if the definition is not clear to you, go to the company's web site and search there.  An email or telephone call to their sales or support area would not be inappropriate.  A targeted web search would also be appropriate.

If after examining the EULA and searching the company's interpretation thereof you still do not have a clear answer, you should seek the counsel of a legal professional in your jurisdiction.  (Bring the details of the prior steps.)

(All that said, if you're using a "home and student" version of Microsoft office suite and Avast antivirus on your PC, I would be astonished if either expected you to pay for "full" versions before you start hiring employees.)

Title: Is open source development considered "commercial use" of software?

Body:
The Software Setup:

I am currently planning on creating a new software product. I have never commercially launched an application, nor am I doing this for a company. It's more for fun than anything, but it may bring in some cash too. :P Anyway, there are going to be two "core parts" of the software:

Part Number One: This one I am going to release open source. It's basically an installer/launcher/patcher that automatically checks for updates, it can handle error reporting, etc. Blah, blah, blah.

Part Number Two: This is going to be the actual software. Closed source, but freeware. It's linked to an account, which can be either free or paid.

The Problem:

So that's all fine above... until I realise my development computer has a lot of "freeware for non-businesses and paid for businesses" software. (Office, antivirus, and who knows what else?) I know I will definitely have to do something about the software for the for-profit part, but how about the open source part? It is free, but the whole intention of developing it is for adding it to a bigger, paid software.


问:
Is The Free Lunch Over?
In his famous The Free Lunch Is Over article from 2005, Herb Sutter predicted a Concurrent Programming Revolution as big as Object-Oriented Revolution. Has this revolution really happend in years 2005 - 2013?

Key points in the article:

Processor manufacturers have run out of room with most of their traditional approaches to boosting CPU performance. Instead of driving clock speeds ever higher, they are instead turning to hyperthreading and multicore architectures.

Applications will increasingly need to be concurrent if they want to fully exploit CPU throughput gains.

“Oh, performance doesn’t matter so much, computers just keep getting faster” statement will be wrong.

Efficiency and performance optimization will get more, not less, important. Those languages that already lend themselves to heavy optimization will find new life; those that don’t will need to find ways to compete and become more efficient and optimizable. Expect long-term increased demand for performance-oriented languages and systems.

Programming languages and systems will increasingly be forced to deal well with concurrency. We desperately need a higher-level programming model for concurrency than languages offer today.

答:
Yes, but it depends.

You can’t expect to write nontrivial, high-performance software without both taking advantage of parallel hardware and using concurrency as a program structuring technique. But most software is both trivial and non–performance-critical. A web app isn’t doing much number crunching, and CRUD apps have nothing like the hard timing limits of some simulation and medical software.

Game developers in particular need to care about this, because games are the most common type of application with soft realtime requirements. The problem is salient on a mobile phone, where you want to squeeze as much computing and rendering power as possible out of an integrated chip with two CPU cores and a low-power GPU. That’s another reason that so many developers are looking at Haskell and waiting for languages like Rust to mature—we want safety and performance on modern hardware.

Since 2005 we have gained new and improved tools such as OpenCL, CUDA, OpenMP, and vector instruction sets for working with concurrency and data parallelism in established languages. However, the relative newcomers are designed from early on to do many more interesting things with concurrency.

Haskell’s concurrent runtime allows the language to provide rich support for lightweight parallelism (sparks) and concurrency abstractions (threads, channels, and shared mutable references). Go and Rust also offer lightweight tasks, Go using channels and Rust using message passing.

These systems offer memory safety, performant runtimes, and static protection against certain kinds of races. The by-default immutability of Haskell and Rust make concurrency much easier for humans to manage. Erlang was doing this already in the 80s, but the needs of software and our knowledge about how to design programming systems have also improved since—thank goodness.

Finally, many existing languages—I won’t name names—are ready to decline as credible choices for writing new software. Their burdens of complexity and poor concurrency abstractions make them unsuitable for the considerations of modern applications. We are simply waiting for mature alternatives.

Title: Is The Free Lunch Over?


问:
Larger Code is Still Faster
When compiling C code with gcc, there are compiler optimizations, some that limit code size and others create fast code.

From the -S flag, I see that the -O2/03 generates more assembly than the -Os code. How is more assembly still faster than less assembly?

答:
On a modern processor, there are usually several ways to achieve the result specified in a higher level language (such as C). These solutions can have different trade-offs between code size and speed due to several factors.

Not all assembly instructions take the same amount of time to execute. For example, it is possible that a particular result can be achieved with 2 instructions that take 10 clock-cycles each to execute, or with 6 instructions that take 3 clock-cycles each. The difference here can be because those two long instructions duplicate some of the work that the compiler avoided by using the 6 short instructions.

On a modern processor, it makes a huge difference in execution speed if the next instruction is already present in the cache or if it has to come from main memory. This effect is most visible with branching instructions, because they make it harder to tell what the next instruction will be. Often, compilers will try to offset these effects by unrolling (part of) a loop into a repeated  block of instructions to reduce the costs of branching/jumping.

Title: Larger Code is Still Faster


答:
Well, most of the time the complier generates more instructions so that fewer of them are executed in a given run. Usually by generating specific code for different cases:

Loop unrolling. The jump is only done in every n (usually 8) iterations.

Function inlining. It saves the call, return, copying arguments and stack manipulation.

The other thing is that some instructions take more time than other. Especially conditions that are difficult to predict can be significantly slower. However both calls and loops are common and the predictor handles them well.

The other thing is memory cache, but here things are not so clear cut. The caches work better when the code is read linearly (functions are inlined), but it also has limited size, so larger portion of small code will be cached.

Title: Larger Code is Still Faster

Body:
When compiling C code with gcc, there are compiler optimizations, some that limit code size and others create fast code.

From the -S flag, I see that the -O2/03 generates more assembly than the -Os code. How is more assembly still faster than less assembly?


问:
Issue with scrum adaptation by team
I have been playing with Scrum methodology since year and half. I am using VersionOne as scrum tool. I have tried to follow most of the scrum principles. Sometimes, I feel like there is an issue with transparency of the stories. As of now, the whole team can get an access to all stories defined for the project. This creates issues with different levels of developers like junior and senior level developer.

People's complains are about the work distribution or type of work they are assigned to. There is an issue of comparison among the developers. I don't know if I am following scrum properly or not.

In scrum, should we give access of the all stories to everyone? or only assigned person can view his/her story?

答: It's highly important the team agree as a whole on which team member is working on what. If not yo'll having people standing on each others toes and also at some point, you'll run into the type of team member who to coin a phrase, "Cherry picks" strories that are easier than the rest or simply are trying to make themselves noticed as a "Sprint Hero".</p>

Title: Issue with scrum adaptation by team


问:
Do we need a weekly project status meeting in Agile?
I am working in a small company with around 15 people (dev and qa).  We are trying to practice Agile in our company. We are doing daily stand-up meetings. We are also doing a weekly project status meeting with our CTO. There we report our CTO regarding last week task and overall project status. My question is whether doing this weekly status meeting  with our CTO supported in Agile or not?</p>

答:
Agile is most definitely not a series of things that you do. It's a set of principles which your organization can choose to adopt.

Individuals and interactions over processes and tools

In this light, is your meeting useful to your team? Does it improve communication, is it an effective way of exchanging information? If it works for you, then keep it. If it's a CTO-mandated burden, ask him to cancel it or make it optional to attend.

My suggestion is to do a retrospective meeting. Bring this up within the 15 people in the team and CTO, and see:

how they perceive the meeting

what do they take home from it, is it useful?

is it possible to achieve the same objectives more effectively?

In other words: what is the purpose of the meeting and is it an effective way of achieving that purpose?

There is nothing agile or non-agile in meetings, but it's certainly not agile to follow a process instead of focusing on people.


问:
Is Java (still) the cross platform language of choice?
When I started using Java in the nineties, it was all "Write once, run anywhere!" from day one. That was probably all true then and I was a part of the choir as well.

I am not sure what to think about that anymore, considering all the other languages using multi platform runtimes (python, flash, perl, html, php...). But I am still seeing lots of arguments that says you should use Java because it is supposedly better for cross platform development.

So, Is that still true today? Is Java still the language of choice for multi platform development?

Please be specific with focus on cross platform aspects.

I am not asking for general language feature comparisons.

Update: Great responses so far! Most answers seems to be favoring Java or web. Any input from the script crowd?

答:
I'll say no. python and ruby are used a lot and so is javascript for both client and server side. I personally use .NET and have no problems getting it to run on mac and linux (while developing on windows)

-edit- i hear LLVM is becoming popular but is still extremely small. That will allow you to use cross platform C++ in a single binary. Apparently it will be executed on browser but i havent seen an example where it allows you to modify the dom or call javascript.

ContentLicense: CC BY-SA 2.5


问:
User Story vs Requirement
User Story captures what the user wants to do with the system at a high level. I understand that the user story would further drive a number low level requirements. Is user story same as high level requirement for the system?</p>

答:
User stories and requirements are very different beasts.

Requirements

Requirements presuppose that the design of the application is done beforehand, and that development is the implementation of that design. Requirements therefore focus on how to implement a functionality.

Example of requirement:

Build a user contact form with the following fields: name, surname, email, free text and a submit button. When the submit button is pressed, an email is sent to our support team.

User stories

User stories focus on what to achieve, and insist that the design of the product is done at the last minute and it is a collaboration between a product person and a developer person. The details are decided during implementation based on opportunity.

Example of a story:

As Jimmy the user I want to contact your support team when I can't use the site properly so they can help me.

What is the difference?

As you can see, there is certainly a difference in the amount of details provided, but there is also a lot of information that is only available in the story, namely the purpose what it is that we are trying to achieve with this feature.

While it may appear that the purpose is relatively unimportant, this is a wrong assumption in agile development. There are typically two cases in which knowing the purpose is very important: reducing the cost of opportunity and enabling agility.

Cost of opportunity

If there are hidden assumptions in the requirement, it could be very hard to achieve. For example: is there a mail server available? If not, the requirement might take a much longer time to be developed. In some other cases a simpler way of achieving the same goal might be missed because of the design.

In contrast, the user story is about a user contacting our support department. If sending a mail is unfeasible or too expensive, we can devise a different solution on the spot: write to a database, for example, or use a form via Google docs, or simply put an email address instead of the form. This can't be easily done with a requirement, but it's easily done with a story and a product person present.

Agility

For this reason, with requirements we generally tend to think of these hidden assumptions beforehand and make sure there are no hitches. So in this case there might be a different requirement, scheduled before hand, which made sure a mail server was present.

This leads us to another huge difference between stories and requirements which is hierarchy. As I've exemplified above, requirements must, by their own nature, be ordered in some natural hierarchy so that dependencies are met. Stories, on the other hand, focus on purpose and have no such constraints.

This is by design, as in agile it is of fundamental importance to add, remove, reschedule and modify stories as needed during the execution of the project. Requirements can generally be added, sometimes modified or removed, but it's generally very painful to move them around because of all the dependencies. It is simply not done very often. If you are working with requirements, your agile implementation will suffer, or will probably not be very agile at all, in the sense of being able to embrace change.

Title: User Story vs Requirement


问:
Structure of a Git repository
Sorry if this is a duplicate, I looked.

We're moving to Git. In Subversion, I'm used to having \trunk, \branches and \tags folders.

With Git, switching between branches will replace the contents of the working directory, so am I right to assume that the way we used to work just doesn't apply with Git?

My guess is that I'd have a repo folder with maybe a gitignore and readme.txt, then the folders for the projects that make up the repo, and that's it.

答:
Just think of Git as a 3D view of the same data that you see in 2D in SVN - ie with SVN you branch your root and it appears as a copy shown as a new folder in the tree. With Git, when you branch it appears as a copy shown as a "layer" ontop of your existing tree. Once you realise that its pretty easy to conceptualise the difference.

With SVN you can still work the same way as Git - switch between branches will replace the single view of the codebase with the branched view, this applies whether you use svn switch or git checkout.

Obviously you can get a copy of a branch in SVN by checking out the branch to its folder location, which is the same as cloning a git repo to a different location on your disk.

Same applies to tags - you can label a git revision, or you can make a branch for a release. SVN tags are the same as branches, its only convention that they're called 'tags'. You could label (well, record the revision number) of a SVN repo to get a snapshot of a release too.

The differences between git and svn are more to do with how checkin and checkouts happen, not with the fundamentals of source control. The view of the code can be different (you'll never see a single view of the code tree that includes branches in git, and you can branch a partial repository in SVN, but these are ultimately minor differences)

Title: Structure of a Git repository


问:
Increase speed of a VB.net Application to SQL server 2008 and Hamachi VPN
Our current Information System (complete with path for pictures for records stored in db) has the following specifications:

A desktop application was developed in vb.net

We use SQL server 2008 r2 as the database

Server specs: Intel xeon processor clocking in at 2.40 ghz, 2 GB RAM and Operating system

of 2008 R2

Hamachi VPN for our offshore offices (within country).

Office has 6mb dedicated internet connection. Offshore offices have varied ranging from 2mbps to 1mbps

The application made in vb.net is connected to the server via IPaddress(locally) and hamachi public IP (for offshore)(we made sure that the tunnel is direct, not relayed)

We found some weird things while users used the application. There are times where there are 5 users (local and offshore) simultaneously using it, and it went great.
Then there would be times where even just three active users (still local or offshore) would suddenly experience extreme slowdown (even for something as simple as a select query to database for verification of log-In).

For offshore clients we tried to ping them in hamachi and found out that each has speed averaging at 500 bytes per reply. Also, loading records that have pictures in them takes a REALLY long time. Wasn't it supposed to be that if you put image path instead of using BLOB, imaging would be faster? (The applications images is stored in a shared folder on the server, then we map that folder to the client unit).

The questions are:
based on the given above, how can we exactly speed up the system? Should
we improve the server specs? is the internet provider the problem? must we redesign how we manage pictures in the system?

What are the bottlenecks and how do we remedy it?

Are there any other things that I should be aware of?

答:
I can give you only one general advice: when trying to make relational DB access over VPN, check your latency. Even when your band width is great, the latency caused by VPN internals might kill the performance in such a scenario. To my experience is often better to make use of a terminal server solution and run the application only locally - RDP is greatly optimized for VPN access, while relational DB access typically does lots of roundtrips with small sets of data, which does not work well when your latency is high.

If that does not work, the best thing to do is IMHO: measure, measure, measure! The bottleneck can be everywhere and it is almost impossible to solve it at the drawing table.


问:
What's better either pass a class instance to the method or just primitives?
Let's say I have a model of some data:

```<code>public class User {

    public String name;
    public String password;

}
</code>```

And some other class to work with this User:

```<code>public class ClassB {

    public static void saveUser(User user) {
        // Something
    }

    public static void saveUser(String username, String password) {
        // Something
    }

}
</code>```

What is the better way to go? Would you better choose second method so not to couple these two classes or choose the first way just passing a User instance?

答:
It is rarely a good idea to use multiple parameters to represent a single "object" (here used as a logically cohesive set of variables) in a function, when you can it is advisable to only pass a single parameter for each such "object".

Consider that when you change the permission framework to use a authentication token then you'd need to change all calls that use username/password plus the implementation of those functions, compared to only passing user where you just need to change the implementation.

Or take a third option and create a sub object like an authentication token (to continue the analogy) which you can pass around, this is higher level than username/password strings but still decouples user from ClassB.


答:
I would go for an object. First of all, its object-oriented but also because of readability:

```<code>User user = new User("aString", "anotherString")
saveUser(user);
</code>```

is better readable than:

```<code>saveUser("aString", "anotherString");
</code>```

and it's more safe, e.g.:

```<code>saveUser(password, username) //oops
</code>```

Title: What's better either pass a class instance to the method or just primitives?

Body:
Let's say I have a model of some data:

```<code>public class User {

    public String name;
    public String password;

}
</code>```

And some other class to work with this User:

```<code>public class ClassB {

    public static void saveUser(User user) {
        // Something
    }

    public static void saveUser(String username, String password) {
        // Something
    }

}
</code>```

What is the better way to go? Would you better choose second method so not to couple these two classes or choose the first way just passing a User instance?

Body:
I would go for an object. First of all, its object-oriented but also because of readability:

User user = new User("aString", "anotherString")
saveUser(user);

is better readable than:

saveUser("aString", "anotherString");

and it's more safe, e.g.:

saveUser(password, username) //oops


答:
As you've identified, saveUser(User user) couples the two classes. This is not always bad. If the sole purpose of class B is to save a User then it's fair enough for it to expect a User object to save. However, it does potentially lead to extensibility issues, if the model is complex enough.

It also gives the saveUser method access to any logic you add to your User class. A low risk, but a risk nontheless.

On the other hand, saveUser(String username, String password) carries its own problems. it is very easy, especially when you have 10 or more parameters, to get them mixed up. If someone accidentally types saveUser(user.Password, user.Username) then you're not going to get a compile-time error, or even a runtime error, it's going to happily save those strings in the wrong fields.

Also, a very long list of parameters can make your code unreadable.

A better option is probably to use an interface saveUser(IUserDetails user) which doesn't couple the classes to each other, but rather couples the saveUser method to any class that contains the data it requires to perform the task it has been given to do -- save a username and password.


答:
Consider the following (some of it is from the excellent Clean Code by Uncle Bob):

If there are direct connection between the parameters, you should encapsulate it to a class. (something like that from the book)

Example: if you have a UserCredential class, you can easily add SSO or one-time-ticket based authentication. If you had a method or property called AreValid, you won't ever need to modify your code, even if you are adding those two new functionalities.

See?

```<code>public static void saveUser(UserCredentials credentials)
{
    if (credentials.AreValid)
    {
        // Something - won't ever change
    }
}
</code>```

Note: It is not even a User class, just the credentials.

The additional benefit of creating smaller classes (UserCredentials instead of User) is: you can add logic into that small class - so finding out if the user has valid credentials won't pollute your code where you are focusing on saving something: you are separating the responsibilities (check: Single Responsibility Principle).

Body:
Consider the following (some of it is from the excellent Clean Code by Uncle Bob):

If there are direct connection between the parameters, you should encapsulate it to a class. (something like that from the book)

Example: if you have a UserCredential class, you can easily add SSO or one-time-ticket based authentication. If you had a method or property called AreValid, you won't ever need to modify your code, even if you are adding those two new functionalities.

See?

public static void saveUser(UserCredentials credentials)
{
    if (credentials.AreValid)
    {
        // Something - won't ever change
    }
}

Note: It is not even a User class, just the credentials.

The additional benefit of creating smaller classes (UserCredentials instead of User) is: you can add logic into that small class - so finding out if the user has valid credentials won't pollute your code where you are focusing on saving something: you are separating the responsibilities (check: Single Responsibility Principle).


答:
Here are few data points; decide for yourself if it counts as a revolution.

Parallelized Hardware

Around 2005, both Intel and AMD start mass-producing 2-core desktop x86 CPUs (Pentium D and Athlon 64), with clock speeds around 3 GHz.

In 2006, PlayStation 3 is released, featuring the Cell processor with 8+1 cores at 3.2 GHz.

In 2006, GeForce 8 series is released. It consists of large numbers (~100) of general-purpose 'stream processors', as opposed to graphics-specific units. Around 2007, CUDA 1.0 spec is released, allowing some general-purpose computation run on massively-parallel NVidia hardware.

Since then, the tendencies continued.

Say, now, in 2013,  both Intel and AMD offer 4, 8, and 16-core CPUs, with clock speeds slightly above mere 4 GHz. Dual-core and quad-core designs are common for lower-power devices, such as laptops and smartphones.

All this is mass-produced, consumer-grade everyday computer hardware.

Software

CUDA is released in 2007, then OpenCL in 2008, allowing to use massively-parallel GPUs in general (non-graphical) computation. The model becomes popular; many hosting companies (e.g. Amazon) offer GPUs for general computing tasks.

Go is released in 2009, featuring very cheap preemptive threads ("goroutines") and allowing to efficiently express highly concurrent algorithms.

Akka toolkit is released for Java and Scala in 2009, allowing for actor-based concurrency.

Erlang (a highly concurrent language) sees some increase in usage.

Concurrency vs Parallelism

Note that to utilize parallel hardware, one does not necessarily need software concurrency, that is, juggling with threads of execution within a computation. Many problems are solved by parallel, non-interacting processes, where each process is a traditional sequential program.

Parallel processing may utilize more traditional languages and parallel frameworks, like map-reduce or MPC or OpenMP. For such frameworks, presence of multiple cores on the same CPU crystal is not conceptually very different from just having more CPUs in the cluster; the difference is mainly speed.

No free lunch so far

CPU speeds still linger at around 5 GHz at the high end. With better technologies in sight, like graphene transistors, frequencies may again rise in the future, but not very soon probably.

Title: Is The Free Lunch Over?

Body:
In his famous The Free Lunch Is Over article from 2005, Herb Sutter predicted a Concurrent Programming Revolution as big as Object-Oriented Revolution. Has this revolution really happend in years 2005 - 2013?

Key points in the article:

Processor manufacturers have run out of room with most of their traditional approaches to boosting CPU performance. Instead of driving clock speeds ever higher, they are instead turning to hyperthreading and multicore architectures.

Applications will increasingly need to be concurrent if they want to fully exploit CPU throughput gains.

“Oh, performance doesn’t matter so much, computers just keep getting faster” statement will be wrong.

Efficiency and performance optimization will get more, not less, important. Those languages that already lend themselves to heavy optimization will find new life; those that don’t will need to find ways to compete and become more efficient and optimizable. Expect long-term increased demand for performance-oriented languages and systems.

Programming languages and systems will increasingly be forced to deal well with concurrency. We desperately need a higher-level programming model for concurrency than languages offer today.


问:
OOP Objects, nested objects, and DAO's
Here's something I keep struggling to figure out the best solution to. I've had this problem while working with PHP and Java so it's a fundamental understanding of OOP issue. Examples are in PHP.

Let's say I have a few object's here. Song, Artist, ArtistProfile, User.

So in some instances I want the ArtistProfile and an array of User objects (subscribers) when I call the Artist (e.g. the artist's profile page), in other instances I only want the Artist info, like when viewing a page of the song.

Should I be nesting one object as part of another or should I be creating more specific objects for different usages.

Option 1: Nested

```<code>Class Song {
   private $songId;
   private $songName;
   private $year;
   private $Artist; //Artist object
}

Class Artist {
   private $artistId;
   private $name;
   private $age;
   private $subscriberArr; //Array of User objects which then have more nested objects such as a Role object, Profile object
   private $profile; //Profile object which could also have more nested objects
}

Class User {
   private $userId;
   private $name;
   private $age;
   private $role; //Role object
   private $profile; //UserProfile object
}
</code>```

Option 2: Build more objects

```<code>Class Song {
   private $songId;
   private $songName;
   private $year;
   private $artistId;
}

Class Artist {
   private $artistId;
   private $age;
   private $name;
}

Class User {
   private $userId;
   private $name;
   private $age;
   private $roleId;
}

Class SongWithArtist {
   private $song; //Basic Song object
   private $artist; //Basic Artist object
}

Class ArtistWithProfile {
   private $artist; //Basic artist object
   private $profile; //Profile object
   private $subscriberArr; //UserDisplay object containing basic User object
}

 Class UserWithProfile {}
</code>```

Option 1 means wasting a lot of time/resources grabbing information I may not need for that page but easier to manage. Option 2 is messy and requires keeping track of which object is what but faster and far less db calls. Which is the 'correct' option and/or is there a 3rd correct option?

答:
I believe that what you want to do when programming in general is to avoid duplicating data.

When designing a relational database, there are 4 types of relationships:

one-to-one

one-to-many

many-to-one

many-to-many

For a many-to-many relationship, you have a "link table" in a database where usually just has the two IDs of the two records being linked to each other.

In addition to the two linked record IDs, a link table can have any other data associated between the two database tables with the many-to-many link table.

For example,

```<code>class DBRecord {
    private $recordID; // a BIGINT, auto-incrementing field, the primary key
}

class Product extends DBRecord {
    private $productID; // an ID that the user can set
    private $productName;
    private $suggestedRetail;
    ...
}

class Vendor extends DBRecord {
   private $vendorID; // an ID that the user can set
   private $vendorName;
   private $contactID;
   ...
}

class ProductVendors extends DBRecord {
   private $productRecordID; // this ID never changes
   private $vendorRecordID;  // this ID never changes
   private $wholesaleCost;   // the cost of a product can be different by vendor
}
</code>```

In this example, objects of the classes: Product, Vendor, and ProductVenders are much like the records that are in the database.  You could possibly read an entire database table into an array.

```<code>$products = readAll();
$vendors = readAll();
$productVendors = readAll();
</code>```

Depending upon the size of your dataset in the number of records, you may not want to read them all into RAM.

When you have too many records to read them all into RAM, you can setup your relations between your objects to mirror the relations between your database tables in your relational database:

```<code>// database code is encapsulated in this class
class DB {
   ...
}

// this class implements functionality common to all subclasses
abstract class DBTable {
   private $db;
   private $internalName; // the SQL name for this database table
   private $displayName;  // the name that the user sees for this db table
   public lookup($productID) {
       ...
   }
}

class Products extends DBTable {
   ...
}

class Vendors extends DBTable {
    ...
}

class ProductVendors extends DBTable {
   ...
}
</code>```

That's how I've done many-to-many relationships, and it works even for very large datasets such as maybe having 100,000 product record.

One-to-many and many-to-one are just the flip-side of each other

```<code>class PurchaseOrderLineItem extends DBRecord {
}

class PurchaseOrder extends DBRecord {
    private $lineItems;
    public loadLineItems() {
       ...
    }
    public saveLineItems() {
       ...
    }
}
</code>```

A line-item of a purchase order can only be on one purchase order document, but a purchase order document can have many line items on it.  This generally isn't a huge number of line-items, so I just load them all into RAM, into an array.

One-to-one relationships

```<code>class Product extends DBRecord {
    private $itemRecordID;
    private $inventoryOnHand;
    ...
}

class InventoryCount extends DBRecord {
    private $itemRecordID;
    private $inventoryCounted;
}
</code>```

These two records are a one-to-one relationship.  When counting all of the inventory in a store, for each product there is only one count, and for each count, there is only one product.

So, those are the four types of relationships.  I think that the most general solution is to mirror your relational database, but I don't always do that such as in the case of purchase orders which "contain" their line-items.

Watch out for multi-user problems
The famous lost-update problem.

Don't duplicate data
See "Normal forms".

Store date-of-birth -- not age
Generally it's best to not store an age, but a date-of-birth and have an accessor called "getAge()" to calculate and return an age.

Title: OOP Objects, nested objects, and DAO's

Body:
I believe that what you want to do when programming in general is to avoid duplicating data.

When designing a relational database, there are 4 types of relationships:

one-to-one

one-to-many

many-to-one

many-to-many

For a many-to-many relationship, you have a "link table" in a database where usually just has the two IDs of the two records being linked to each other.

In addition to the two linked record IDs, a link table can have any other data associated between the two database tables with the many-to-many link table.

For example,

class DBRecord {
    private $recordID; // a BIGINT, auto-incrementing field, the primary key
}

class Product extends DBRecord {
    private $productID; // an ID that the user can set
    private $productName;
    private $suggestedRetail;
    ...
}

class Vendor extends DBRecord {
   private $vendorID; // an ID that the user can set
   private $vendorName;
   private $contactID;
   ...
}

class ProductVendors extends DBRecord {
   private $productRecordID; // this ID never changes
   private $vendorRecordID;  // this ID never changes
   private $wholesaleCost;   // the cost of a product can be different by vendor
}

In this example, objects of the classes: Product, Vendor, and ProductVenders are much like the records that are in the database.  You could possibly read an entire database table into an array.

$products = readAll();
$vendors = readAll();
$productVendors = readAll();

Depending upon the size of your dataset in the number of records, you may not want to read them all into RAM.

When you have too many records to read them all into RAM, you can setup your relations between your objects to mirror the relations between your database tables in your relational database:

// database code is encapsulated in this class
class DB {
   ...
}

// this class implements functionality common to all subclasses
abstract class DBTable {
   private $db;
   private $internalName; // the SQL name for this database table
   private $displayName;  // the name that the user sees for this db table
   public lookup($productID) {
       ...
   }
}

class Products extends DBTable {
   ...
}

class Vendors extends DBTable {
    ...
}

class ProductVendors extends DBTable {
   ...
}

That's how I've done many-to-many relationships, and it works even for very large datasets such as maybe having 100,000 product record.

One-to-many and many-to-one are just the flip-side of each other

class PurchaseOrderLineItem extends DBRecord {
}

class PurchaseOrder extends DBRecord {
    private $lineItems;
    public loadLineItems() {
       ...
    }
    public saveLineItems() {
       ...
    }
}

A line-item of a purchase order can only be on one purchase order document, but a purchase order document can have many line items on it.  This generally isn't a huge number of line-items, so I just load them all into RAM, into an array.

One-to-one relationships

class Product extends DBRecord {
    private $itemRecordID;
    private $inventoryOnHand;
    ...
}

class InventoryCount extends DBRecord {
    private $itemRecordID;
    private $inventoryCounted;
}

These two records are a one-to-one relationship.  When counting all of the inventory in a store, for each product there is only one count, and for each count, there is only one product.

So, those are the four types of relationships.  I think that the most general solution is to mirror your relational database, but I don't always do that such as in the case of purchase orders which "contain" their line-items.

Watch out for multi-user problems
The famous lost-update problem.

Don't duplicate data
See "Normal forms".

Store date-of-birth -- not age
Generally it's best to not store an age, but a date-of-birth and have an accessor called "getAge()" to calculate and return an age.


问:
Why is cleverness considered harmful in programming by some people?
I've noticed a lot of questions lately relating to different abstraction techniques, and answers saying basically that the techniques in question are "too clever." I would think that part of our jobs as programmers is to determine the best solutions to the problems we are given to solve, and cleverness is helpful in doing that.

So my question is: are the people who think certain abstraction techniques are too clever opposed to cleverness per se, or is there some other reason for the objection?

EDIT: This parser combinator is an example of what I would consider to be clever code. I downloaded this and looked it over for about half an hour. Then I stepped through the macro expansion on paper and saw the light. Now that I understand it, it seems much more elegant than the Haskell parser combinator.

答:
Re-quoting for context and and easier comprehension:

"Debugging is twice as hard as writing the code in the first place.
  Therefore, if you write the code as cleverly as possible, you are, by
  definition, not smart enough to debug it."

What Brian Kernighan wrote here obviously refers to convolution, and he mistakenly used the word clever.

"Debugging is twice as hard as writing the code in the first place.
  Therefore, if you write the code as [convoluted] as possible, you are, by
  definition, not smart enough to debug it."

Convolution:

```<code>A thing that is complex and difficult to follow.
</code>```

Clever:

```<code>Showing intelligence or skill; ingenious
</code>```

Educated programmers know that simple code is ingenious. Code that is as clever as possible should be simple by definition. Educated programmers will also avoid working with and writing convoluted code like the plague.  They will also turn convoluted code into clever code whenever they have the chance.  Code usually starts out convoluted and approaches cleverness as knowledge about the domain and understanding of human cognitive ability in programming is better understood through experience and shared knowledge.

Because of the popularity of this quote and Brian Kernighan being quite popular in the industry this misuse of the word has a negative social impact and I'd honestly like to see that addressed by the man himself.  Before writing this article I tried to see if I could simply e-mail him, but, I was unable to find any email contact information that I understood :(.

The negative social impact I have seen is other programmers ostracizing their more clever peers, because they now see cleverness as a problem.  The real problem is the stupid peers who think they are being clever by doing things in a new unidiomatic way, and constantly inventing new things when there is no advantage instead of gaining and understanding of the greater community and reusing clever ideas as much as possible.

I do need to clarify though that often gaining an understanding is more difficult than inventing your own.  Because of the common problem in industry for unrealistic deadlines inventing your own for your smaller niche problem will be used to save time. This is based on the observation that useful, reusable things usually target a larger niche, or provide a useful abstraction for invention.  It is also based on the fact that people target large niches to make more money, when often this makes the tool extremely hard to use because of the complexity involved in making something usable for a wide area of applications.

The other negative social impact is this prevents progress and the desire to comprehend because in our egocentric world we will immediately be in denial of our own lack of understanding and write off the code of as being convoluted even if, once understood, the idea is actually quite clever.

TODO I'd like to cite some references but I'd also like the lack of references to not impede my ability to share information so I will quickly cite what I remember as the sources of my information and maybe I will find the actual info some day (or you can find it for me! :)

Guido Van Rossum's talk about event loops and how he came to understand them

A GitHub employee who stated that they avoid hiring clever people on Y-Combinator

Much of the discussion and learning that goes on in the Python community.  The Python community is especially critical of new ideas, but does not dismiss new ideas they do not understand out of hand, and you can typically see features that were at first seen as convoluted see the light of day as a core language feature/package.

My own experience and professional opinion based on my 10000 foot observations.  I can't really see the specifics to enlighten from all the way up there though :( Hopefully your experience and observation will tell you the same thing and someone else can comment below to give this answer some merit.

Feel free to add your own citations!  Also, feel free to add commas to my text. I have not refreshed my knowledge of comma usage in English in quite some time...

Body:
Re-quoting for context and and easier comprehension:

"Debugging is twice as hard as writing the code in the first place.
  Therefore, if you write the code as cleverly as possible, you are, by
  definition, not smart enough to debug it."

What Brian Kernighan wrote here obviously refers to convolution, and he mistakenly used the word clever.

"Debugging is twice as hard as writing the code in the first place.
  Therefore, if you write the code as [convoluted] as possible, you are, by
  definition, not smart enough to debug it."

Convolution:

A thing that is complex and difficult to follow.

Clever:

Showing intelligence or skill; ingenious

Educated programmers know that simple code is ingenious. Code that is as clever as possible should be simple by definition. Educated programmers will also avoid working with and writing convoluted code like the plague.  They will also turn convoluted code into clever code whenever they have the chance.  Code usually starts out convoluted and approaches cleverness as knowledge about the domain and understanding of human cognitive ability in programming is better understood through experience and shared knowledge.

Because of the popularity of this quote and Brian Kernighan being quite popular in the industry this misuse of the word has a negative social impact and I'd honestly like to see that addressed by the man himself.  Before writing this article I tried to see if I could simply e-mail him, but, I was unable to find any email contact information that I understood :(.

The negative social impact I have seen is other programmers ostracizing their more clever peers, because they now see cleverness as a problem.  The real problem is the stupid peers who think they are being clever by doing things in a new unidiomatic way, and constantly inventing new things when there is no advantage instead of gaining and understanding of the greater community and reusing clever ideas as much as possible.

I do need to clarify though that often gaining an understanding is more difficult than inventing your own.  Because of the common problem in industry for unrealistic deadlines inventing your own for your smaller niche problem will be used to save time. This is based on the observation that useful, reusable things usually target a larger niche, or provide a useful abstraction for invention.  It is also based on the fact that people target large niches to make more money, when often this makes the tool extremely hard to use because of the complexity involved in making something usable for a wide area of applications.

The other negative social impact is this prevents progress and the desire to comprehend because in our egocentric world we will immediately be in denial of our own lack of understanding and write off the code of as being convoluted even if, once understood, the idea is actually quite clever.

TODO I'd like to cite some references but I'd also like the lack of references to not impede my ability to share information so I will quickly cite what I remember as the sources of my information and maybe I will find the actual info some day (or you can find it for me! :)

Guido Van Rossum's talk about event loops and how he came to understand them

A GitHub employee who stated that they avoid hiring clever people on Y-Combinator

Much of the discussion and learning that goes on in the Python community.  The Python community is especially critical of new ideas, but does not dismiss new ideas they do not understand out of hand, and you can typically see features that were at first seen as convoluted see the light of day as a core language feature/package.

My own experience and professional opinion based on my 10000 foot observations.  I can't really see the specifics to enlighten from all the way up there though :( Hopefully your experience and observation will tell you the same thing and someone else can comment below to give this answer some merit.

Feel free to add your own citations!  Also, feel free to add commas to my text. I have not refreshed my knowledge of comma usage in English in quite some time...


问:
Shall I separate the admin part from the rest of the war
I built a web-applicationg using struts2. Then I built a small admin interface in the same war.

With time the webapp grew and so the admin-interface. Now, I'm thinking to separate the admin interface from the rest of the app in a separate war

Is it a good idea ? Is there any performance benefit that I can get due to separation of the admin war and the rest of the webapp.

The admin part is mostly about making changes/updations/settings in the database, so it's not affecting the UI of the rest of the app directly. Separating it also ensures that I can make updations to both parts without affecting the other.

[UPDATE]

I cannot put admin part on local machine. It's a web-app.

Do they use the same classes?
Nope, the entire package is different for admin actions and view is also separate.

How do you update them?
upload war

Do you use application session?
yes of course, although different sessions are used for admin & normal-user.

答:
Separating out different parts of a web application from each other as separate wars means that one can stop and restart individual applications at the application server and possibly simplifies the access control on each application.  The separate applications means that, in theory one can deploy changes to the admin (take it off line, redeploy it) while the main application is still running (note that theory is emphasized - more on this later).

Thats really about it for benefits.  One might see some very slight performance increase on the admin pages because of a reduced number of sessions there.  It is unlikely one would see any improved performance on the main application.

Now the implications that make this much more challenging and take away some of the possible gains.

Consider if you have a user object. This has methods on it like changePassword that can be done by the admin or the user.

Consider these two options:

you're using hibernate or some other orm to annotate the user table to the user object

you've got a data access layer running native queries against the database

You again have two options for these:

two copies of the user object / data layer - one in each war

one external jar that both wars load

Whenever you make a schema change (anything that necessitates updating the user or the data layer) you will either have at least twice as much work (reload both applications and make sure they stay in sync), or you will have to reload the shared jar and restart both applications (and if the app server is being fussy, restart it).

At the end of the day, you are going to find that you have copied the entire set of data objects (and data layer).  The admin may have a few more, but likely everything that is in the main app will be in the admin.

There is a real damager of bugs if the two duplicate the data/model.  Furthermore, you'll find yourself duplicating views (the admin view of a user update page vs the main app view of a user update page).

Ultimately, you'll likely find that there are only minor differences in the authorization between the two applications - you want to share the same authentication, the same data, and likely the same views.  They are just different controllers for admin and normal user.

From this, its likely best to just keep it all as one application.  Don't Repeat Yourself.  Don't duplicate the views and don't duplicate the models.


问:
use areFoo or isFoo?
I have never seen the use of "are" for boolean methods, but the use of "is" is very common.

When I want to use "are" is usually because I am passing multiple variables, or a list of objects.

I suppose I could rationalize my list of objects or multiple variables as one thing, such as "isSetupParametersValid", but that would still be plural.

Is the lack of use of "are" in boolean methods, simply an arbitrary convention or a side-effect of using best practices. If it's a side-effect of best-practices, which ones?

Note: for non-native English speakers "is" refers to a singular object, "are" refers to plural/multiple objects

答:
If you are talking about Java, you could run into problems because JavaBeans are defined with is<PropertyName> (see Spec Chapter 8.3.2)

I think, some frameworks are very rigid and use is<name> for setting booleans by reflection, so they won't find are<name>.

Title: use areFoo or isFoo?


答:
Functional requirements are usually a formal specification that allow you to know exactly if your software work or not. User story are usually a much more informal way to describe a need of one your user story. It does not specify a rigid specification to determine if the software is "valid" or "invalid". While you can test some part of it, the real completion of a user story (if you do them right) is when your user say "yep, that solve my problem!". Remember the agile manifesto :

```<code>Individuals and interactions over processes and tools
Working software over comprehensive documentation
Customer collaboration over contract negotiation
Responding to change over following a plan
</code>```

In his book "User Story Applied", Mike Cohn say specifically that some things don't map to user story and you don't have to use only that.

In my own team, we use the following :

User story : a business need of some kind of user. Emphasis here is on the need, and why does he need it. As other have said, the important here is not to specify how it's done, and to go deep in the real need of the user (ex : he does not need to view data in a table, he need to see the exact value of the data, and he is familiar with table to do just that).

Bug : An unexpected behaviour of the software that impair normal usage. Usually come with an "Importance" (independant of the priority of development) that rate how much it affect the user workflow.

Technical debt. Something that does not prevent usage the usage of the software but will impair us, the developers, in the future. Example : some class is hard to read, the build is slow, some code is not unit tested, the IDE show weird warnings...

Improvement : a change to the software that does not allow new scenarios, but make for a nicer experience. Example : changing the fonts, redesigning a form to make it clearer, adding sensible default to the application, etc.

Functional requirements would not allow us to realize that a feature we implemented don't solve the need of a user, even though our cucumber test pass and we implemented every written word. A story is a discussion, and it's informal. The point is for the implementation guys to understand what is the problematic. They are not a contract tool. If you do "scrum but..." and your story are simply a funny way to write the requirements of the software, then yes, there is no difference.

The point is not the user story, the point is the huge shift in paradigm in the way you approach the work to be done. You are not doing a contract, you are helping some of your user solving a problem. If you don't see your user stories as discussion tool with a real user, then you are not using user stories, you are using a funky requirements syntax.

The rest here is my opinion : user story can never succeed in a unilateral way. You need your customer to work with it. Water-scrum-fall is doomed to be a weird requirement-but-not-requirements mess. If you have a fixed bid contract with specific requirements, don't use iterations and user story, there is no point. Use the rest of the agile toolkit : Automated unit/functional test, code review, continuous integration, refactoring, etc. Ensure that your software is continuously working and that you can ship it at a moment notice. Make it available in its unfinished form to the customer so he can give as much feedback as possible. If you do that my friend, even if you didn't do "User story" and "Scrum", you would have been more agile than many so called "Agile" shop.

Title: User Story vs Requirement

Body: User Story captures what the user wants to do with the system at a high level. I understand that the user story would further drive a number low level requirements. Is user story same as high level requirement for the system?</p>

Body:
Functional requirements are usually a formal specification that allow you to know exactly if your software work or not. User story are usually a much more informal way to describe a need of one your user story. It does not specify a rigid specification to determine if the software is "valid" or "invalid". While you can test some part of it, the real completion of a user story (if you do them right) is when your user say "yep, that solve my problem!". Remember the agile manifesto :

Individuals and interactions over processes and tools
Working software over comprehensive documentation
Customer collaboration over contract negotiation
Responding to change over following a plan

In his book "User Story Applied", Mike Cohn say specifically that some things don't map to user story and you don't have to use only that.

In my own team, we use the following :

User story : a business need of some kind of user. Emphasis here is on the need, and why does he need it. As other have said, the important here is not to specify how it's done, and to go deep in the real need of the user (ex : he does not need to view data in a table, he need to see the exact value of the data, and he is familiar with table to do just that).

Bug : An unexpected behaviour of the software that impair normal usage. Usually come with an "Importance" (independant of the priority of development) that rate how much it affect the user workflow.

Technical debt. Something that does not prevent usage the usage of the software but will impair us, the developers, in the future. Example : some class is hard to read, the build is slow, some code is not unit tested, the IDE show weird warnings...

Improvement : a change to the software that does not allow new scenarios, but make for a nicer experience. Example : changing the fonts, redesigning a form to make it clearer, adding sensible default to the application, etc.

Functional requirements would not allow us to realize that a feature we implemented don't solve the need of a user, even though our cucumber test pass and we implemented every written word. A story is a discussion, and it's informal. The point is for the implementation guys to understand what is the problematic. They are not a contract tool. If you do "scrum but..." and your story are simply a funny way to write the requirements of the software, then yes, there is no difference.

The point is not the user story, the point is the huge shift in paradigm in the way you approach the work to be done. You are not doing a contract, you are helping some of your user solving a problem. If you don't see your user stories as discussion tool with a real user, then you are not using user stories, you are using a funky requirements syntax.

The rest here is my opinion : user story can never succeed in a unilateral way. You need your customer to work with it. Water-scrum-fall is doomed to be a weird requirement-but-not-requirements mess. If you have a fixed bid contract with specific requirements, don't use iterations and user story, there is no point. Use the rest of the agile toolkit : Automated unit/functional test, code review, continuous integration, refactoring, etc. Ensure that your software is continuously working and that you can ship it at a moment notice. Make it available in its unfinished form to the customer so he can give as much feedback as possible. If you do that my friend, even if you didn't do "User story" and "Scrum", you would have been more agile than many so called "Agile" shop.


问:
In DOM, why is childNodes defined in the Node interface if only some node types can have childNodes?
In DOM, why is childNodes defined in the Node interface if only some node types such as Element, Document and DocumentFragement,  can have childNodes?

Is this considered a good design? In what cases this is admissible? I mean, isn't this like defining a radius on an interface Shape even though we know that not every Shape has a radius?

答:
The Composite Pattern has two variations:

The abstract Component (parent class of leafs and composites) only includes methods that make sense on a single item.

The abstract Component also includes the methods of the Composite, i.e. of a collection of items.

Remember that the purpose of the composite pattern is to treat single items and collections of such items in an uniform way. Given an appropriate structure, the composite methods can be implemented in a way that have some meaning even on leafs. E.g. in the context of the DOM, a text node has no childs, and can return an empty NodeList.

This 2nd variation of the Composite pattern isn't always applicable, but it can increase the elegance of the design in some cases (I would still have designed the DOM without this quirk).


问:
What is the role of a Software Architect in the Test-Driven Development process?
As I understand it, Test-Driven Development is about writing tests to define the program specifications (you can correct me if I'm wrong).

If there is someone responsible for writing the specifications (including a public API) for the software (let's call him the Software Architect), does that mean that the Software Architect must write all of the tests?

Or does the Software Architect write the specifications, and then hand them over to the developers to write tests against?

Or do you allow the specifications to grow organically by allowing all of the developers to write their own tests, and forget about having a Software Architect?

答:
The Software Architect isn't writing all the tests.  That would be putting too much onto one person's shoulders to my mind.

The Software Architect should be able to sketch out an initial form for the API that developers then write tests for that and then build the API.  However, the Software Architect may have various code standards that aren't necessarily testable,e.g. documentation or naming conventions.  There is also the potential for the initial API to be missing some calls that as an implementation is done new calls are added to the API.  Thus, there will be some organic growth to the API as the code base grows but the Architect's role is in providing high-level guidelines and trying to make sure they are followed.

There can certainly be cases where a team may decide to not have a Software Architect but depending on the scale of the API and company involved this may or may not be a good idea.


问:
How to prevent fat views in MVC?
I'm just curious. If I'm a lead dev in a company of a dozens of developers is there any way I can prevent a newbie developer from creating a fat view?

By fat view I mean to have an empty controller, empty model and having all database and business logic in the view along with the html/js.

答: Require them to create a second view, possibly as part of unit testing (the unit test suite for the controller and model could, itself, be implemented as a view).</p>

Title: How to prevent fat views in MVC?


答:
This isn't something particular to just MVC - it can affect any part of your system where a junior developer isn't following your team's standards and guidelines.  The way to catch issues like what you describe is to have procedures in place for junior developers to learn and expand their craft while not hurting your project at the same time.  This includes, as Dan mentioned in the above comment, regular code reviews of their work, but can also include ongoing learning sessions for your entire team where, say, someone can present work their recently did on a new technology that shows how or how not to use it, etc.

So that the junior developers don't feel that they are being unfairly scrutinized, the code reviews should be presented to them in a way that shows how they are for everyone's benefit:

The junior developer will learn coding practices they may not have been aware of.

The junior developer may bring new, clever ideas to the team that no one thought of before, as people often develop coding habits over time that tend to make them close-minded to new ways of thinking.

The team in general benefits from better communication, knowledge sharing, etc.  While some may view code reviews as an impediment to getting work done, in the long run, they should save more time than they take up.

Title: How to prevent fat views in MVC?

Body:
I'm just curious. If I'm a lead dev in a company of a dozens of developers is there any way I can prevent a newbie developer from creating a fat view?

By fat view I mean to have an empty controller, empty model and having all database and business logic in the view along with the html/js.


答:
If you have an existing code base, make sure you have a few views that are "thin enough", and properly connected to their respective models and controllers. Use these as learning examples whenever a "newbie developer" joins the team. You can even write it up as a tutorial/article in a corporate standards document and put it on a wiki or something.

If they are unfamiliar with MVC, give them a link to an article that explains how you feel MVC works in your project and then show them your example code for them to see how it really works on your system. And as Dan Pichelman commented, don't let them check in anything without a code review. If someone's never coded like this, it might take them a couple of tries to get the hang of it.

Title: How to prevent fat views in MVC?


答:
You should use "is" or "are" as appropriate for the number of objects in question. You're still maintaining "good form" of asking a question with the boolean variable.  ie. "is it ... ?" or "are they ... ?"

So I don't see anything wrong with using "are" with a plural object.

In cases where the answer isn't immediate, then the primary questions your should ask yourself are:

Does it make the code more readable and expressive regarding intent?

Is it likely that a future change will invalidate how you phrase the boolean question?

Does the answer invalidate the boolean nature of the question?

That third question is a bit odd, so let me give a concrete example.  IsPointValid? is answered pretty clearly with "yes, it is" or "no, it is not."  When asking ArePointsValid? we potentially have a third case of "partially valid: some are, some aren't."  If you have that third case, then use a different variable type than a boolean.

Also keep in mind that the boolean question is an aid to the expressiveness of the code.  It's not an attempt to create grammatical correctness within the code.  So long as you don't get too hung up on is vs. are then your code will be fine and others will understand the intent.

Title: use areFoo or isFoo?

Body:
I have never seen the use of "are" for boolean methods, but the use of "is" is very common.

When I want to use "are" is usually because I am passing multiple variables, or a list of objects.

I suppose I could rationalize my list of objects or multiple variables as one thing, such as "isSetupParametersValid", but that would still be plural.

Is the lack of use of "are" in boolean methods, simply an arbitrary convention or a side-effect of using best practices. If it's a side-effect of best-practices, which ones?

Note: for non-native English speakers "is" refers to a singular object, "are" refers to plural/multiple objects


问:
Is Haskell's type system formally equivalent to Java's?
I realize some things are easier/harder in one language than the other, but I'm only interested in type-related features that are possible in one and impossible/irrelevant in the other.  To make it more specific, let's ignore Haskell type extensions since there's so many out there that do all kinds of crazy/cool stuff.</p>

答:
One thing nobody's mentioned so far is type inference: a Haskell compiler can usually infer the type of expressions but you have to tell the Java compiler your types in detail. Strictly, this is a feature of the compiler but the design of the language and type system determines whether type inference is feasible. In particular, type inference interacts badly with Java's subtype polymorphism and ad hoc overloading. In contrast, the designers of Haskell try hard not to introduce features that impact type inference.

Another thing people don't seem to have mentioned so far is algebraic data types. That is, the ability to construct types from sums ('or') and products ('and') of other types. Java classes do products (field a and field b, say) fine. But they don't really do sums (field a OR field b, say). Scala has to encode this as multiple case classes, which isn't quite the same. And while it works for Scala it's a bit of a stretch to say Java has it.

Haskell can also construct function types using the function constructor, ->. While Java's methods do have type signatures, you can't combine them.

Java's type system does enable a type of modularity that Haskell hasn't got. It will be a while before there's an OSGi for Haskell.


问:
How to approach scrum task burn down when tasks have multiple peoples involvement?
In my company, a single task can never be completed by one individual. There is going to be a separate person to QA and Code Review each task. What this means is that each individual will give their estimates, per task, as to how much time it will take to complete.

The problem is, how should I approach burn down? If I aggregate the hours together, assume the following estimate:

10 hrs - Dev time

4  hrs - QA

4  hrs - Code Review.

Task Estimate = 18hrs

At the end of each day I ask that the task be updated with "how much time is left until it is done". However, each person generally just thinks about their part of it. Should they mark the effort remaining, and then ADD the effort estimates to that? How are you guys doing this?

UPDATE

To help clarify a few things, at my organization each Task within a story requires 3 people.

Someone to develop the task. (do unit tests, ect...)

A QA specialist to review task (they primarily do integration and regression tests)

A Tech lead to do code review.

I don't think there is a wrong way or a right way, but this is our way ... and that won't be changing. We work as a team to complete even the smallest level of a story whenever possible. You cannot actually test if something works until it is dev complete, and you cannot review the quality of the code either ... so the best you can do is split things up into small logical slices so that the bare minimum functionality can be tested and reviewed as early into the process as possible.

My question to those that work this way would be how to burn down a "task" when they are setup this way. Unless a Task has it's own sub-tasks (which JIRA doesn't allow) ... I'm not sure the best way to accomplish tracking "what's left" on a daily basis.

答:
TL;DR

You are using the burn-down incorrectly in several ways. Tasks and stories are either done or not-done; by trying to track deviations from time-based planning estimates in your burn-down, you are actually re-estimating your schedule rather than estimating work-product remaining.

In Scrum, you should be measuring progress towards a Sprint Goal rather than measuring the Sprint's time-box. This keeps the focus on team capacity and feature delivery rather than on continuous scheduling adjustments.

Tasks vs. Stories

You are conflating tasks and stories. Stories comprise all the tasks required to complete the story per your team's "definition of done." The story is considered 100% incomplete unless all its tasks are complete. In Scrum, stories are always estimated in some way; most frequently, they are estimated in story points.

The tasks are the steps or milestones needed to complete the story. While each task may have dependencies and prerequisites, you can certainly say that the code review is complete or not, independently of the other tasks.

Burn-Down

In Scrum, your burn-down chart shows the amount of work remaining for the sprint or project. Real burn-down charts often have plateaus; in some cases, the graph can even rise. For example, on a one-week sprint with two stories worth 3 and 5 points, your data points may look something like this:

```<code>Mon | Tue | Wed | Thu | Fri
--- | --- | --- | --- | ---
 8  |  5  |  5  |  5  |  0
</code>```

In this idealistic scenario, you start with 8 story points. The 3-point story was completed Tuesday afternoon, while the 5-point story wasn't completed until Friday. The story points aren't deducted from the burn-down until the story has met the definition of done. If you're using ideal hours instead of story points, the only thing that changes is your scale.

Time-Boxing

The generally-accepted practice is to ensure that your tasks are decomposed into bite-sized chunks between 1/2 day and 2 days. Variance of more than one day should be self-evident from the daily stand-ups or the Sprint Backlog; there should be no need to perform a formal status pull.

You can also perform statistical analysis on the burn-down chart to determine if your sprint is trending correctly. Small deviations or plateaus are normal, but if no one is raising any blockers in the daily stand-ups but your burn-down seems stuck, that's generally a sign that the Sprint Backlog has been mis-estimated or there is "invisible work" that needs to be made explicit in your process.

Body:
TL;DR

You are using the burn-down incorrectly in several ways. Tasks and stories are either done or not-done; by trying to track deviations from time-based planning estimates in your burn-down, you are actually re-estimating your schedule rather than estimating work-product remaining.

In Scrum, you should be measuring progress towards a Sprint Goal rather than measuring the Sprint's time-box. This keeps the focus on team capacity and feature delivery rather than on continuous scheduling adjustments.

Tasks vs. Stories

You are conflating tasks and stories. Stories comprise all the tasks required to complete the story per your team's "definition of done." The story is considered 100% incomplete unless all its tasks are complete. In Scrum, stories are always estimated in some way; most frequently, they are estimated in story points.

The tasks are the steps or milestones needed to complete the story. While each task may have dependencies and prerequisites, you can certainly say that the code review is complete or not, independently of the other tasks.

Burn-Down

In Scrum, your burn-down chart shows the amount of work remaining for the sprint or project. Real burn-down charts often have plateaus; in some cases, the graph can even rise. For example, on a one-week sprint with two stories worth 3 and 5 points, your data points may look something like this:

Mon | Tue | Wed | Thu | Fri
--- | --- | --- | --- | ---
 8  |  5  |  5  |  5  |  0

In this idealistic scenario, you start with 8 story points. The 3-point story was completed Tuesday afternoon, while the 5-point story wasn't completed until Friday. The story points aren't deducted from the burn-down until the story has met the definition of done. If you're using ideal hours instead of story points, the only thing that changes is your scale.

Time-Boxing

The generally-accepted practice is to ensure that your tasks are decomposed into bite-sized chunks between 1/2 day and 2 days. Variance of more than one day should be self-evident from the daily stand-ups or the Sprint Backlog; there should be no need to perform a formal status pull.

You can also perform statistical analysis on the burn-down chart to determine if your sprint is trending correctly. Small deviations or plateaus are normal, but if no one is raising any blockers in the daily stand-ups but your burn-down seems stuck, that's generally a sign that the Sprint Backlog has been mis-estimated or there is "invisible work" that needs to be made explicit in your process.


答:
The simple reason why this is part of the spec is that it makes it much easier to traverse a DOM tree. You can always iterate over a Node's childNodes, even if there aren't any. Otherwise, you'd need to determine the Node's type at each point in the traversal.

The reason why this is okay is that childNodes has a logical and meaningful value for non-Elements: an empty collection. On the other hand, in your radius example, whatever value it might have for non-ellipses is completely meaningless.

Title: In DOM, why is childNodes defined in the Node interface if only some node types can have childNodes?

Body:
In DOM, why is childNodes defined in the Node interface if only some node types such as Element, Document and DocumentFragement,  can have childNodes?

Is this considered a good design? In what cases this is admissible? I mean, isn't this like defining a radius on an interface Shape even though we know that not every Shape has a radius?