问:
Is it a basic principle, or highly desirable, to have class methods that return "$this" rather than a value?
I've really just begun to learn OOP. I started about a year ago and have written probably 15,000 lines of it. But I wrote it all with hardly any experience looking at other people's OOP.

Most of my class functions return a value or make a change to the class properties and return true/false. Some of the ones that return a value also save that value into a class property (after first checking if the class property is already set, which can avoid a database call).

Now I'm doing a lot of digging in Magento/Zend and I notice a lot of their class methods return "$this". As I understand it, unlike in regular functions, class methods that return $this act by reference not by value, so that you get back the same object you started with rather than a copy.

Is returning $this something that I should be doing much more of? Does it make the code easier to maintain and use? Is returning $this necessary in order to chain class methods?

答:
This is a technique employed to create Fluent Interfaces. If a Fluent Interface is not your goal, then you don't need to return $this.

Fluent interfaces allow you to write code that looks like this (pseudocode):

```<code>private void makeFluent(Customer customer) {
    customer.newOrder()
            .with(6, "TAL")
            .with(5, "HPK").skippable()
            .with(3, "LGV")
            .priorityRush();
}
</code>```

It works, because each method call has access to the original object, by virtue of the previous method call returning this.  The above code is more or less equivalent to:

```<code>private void makeFluent(Customer customer) {
    var newOrder = customer.newOrder()
    newOrder.with(6, "TAL");
    newOrder.with(5, "HPK", skippable := true);
    newOrder.with(3, "LGV");
    newOrder.priorityRush();
    ...
}
</code>```

this is not always returned.  Sometimes a different object is returned.  Linq works like this, returning an IEnumerable (a lazy representation of a collection, a modified state engine, basically) from each Linq method in the chain.

It requires more effort and forethought to create a fluent interface than it does to simply set all of the parameters in a constructor.  You have to figure out whether the object has everything it needs to be fully functional, and it's not always clear exactly what a given method does, or in what order you need to call the methods.  For example:

```<code>20.minutes.ago
</code>```

looks clean, but how does it work, exactly?

http://en.wikipedia.org/wiki/Fluent_interface

http://www.martinfowler.com/bliki/FluentInterface.html

Body:
This is a technique employed to create Fluent Interfaces. If a Fluent Interface is not your goal, then you don't need to return $this.

Fluent interfaces allow you to write code that looks like this (pseudocode):

private void makeFluent(Customer customer) {
    customer.newOrder()
            .with(6, "TAL")
            .with(5, "HPK").skippable()
            .with(3, "LGV")
            .priorityRush();
}

It works, because each method call has access to the original object, by virtue of the previous method call returning this.  The above code is more or less equivalent to:

private void makeFluent(Customer customer) {
    var newOrder = customer.newOrder()
    newOrder.with(6, "TAL");
    newOrder.with(5, "HPK", skippable := true);
    newOrder.with(3, "LGV");
    newOrder.priorityRush();
    ...
}

this is not always returned.  Sometimes a different object is returned.  Linq works like this, returning an IEnumerable (a lazy representation of a collection, a modified state engine, basically) from each Linq method in the chain.

It requires more effort and forethought to create a fluent interface than it does to simply set all of the parameters in a constructor.  You have to figure out whether the object has everything it needs to be fully functional, and it's not always clear exactly what a given method does, or in what order you need to call the methods.  For example:

20.minutes.ago

looks clean, but how does it work, exactly?

http://en.wikipedia.org/wiki/Fluent_interface

http://www.martinfowler.com/bliki/FluentInterface.html


问:
What defines "software developer" role
I am a junior software developer and I have been working for a company less than a year.

While I always thought being a software developer means to develop software and CODE something, my tasks are more in administration type of work, such as setting up Jenkins, SQL Replication and etc.

Are these type of jobs included in a Developer role, or a developer only develops software? Should I be talking to my manager about this? Is this a common way for companies to evaluate "developing" skills?

答:
Sounds to me like they hired a junior because they couldn't afford a senior, rather than because they actually wanted a junior (someone they can invest in and mentor until they become a senior). I have managed a team who had that decision forced upon them by managers who didn't know better.

He ended up with all sorts of unfortunate jobs like creating training videos for users and such and I still feel guilty about it now, but I was under pressure to deliver and the expectation was that adding a head to the development room would only speed things up.

It's unfortunate, because it puts you and your boss in tricky positions.

He probably doesn't have any work he can trust to a junior, and any seniors he might have can't be distracted from their day-to-day. The easy way out is to give the junior lots of non-development tasks, which he also doesn't really want to waste senior developers' time with.

But a few problems arise from this.

First, the kind of devops jobs he's giving you really require a senior developer. Particularly, a build server should be set up by someone who is building the software and knows where the pain-points are.

Second, the junior isn't becoming more useful. After five years of this, you'd still be doing the same tasks, because you still couldn't be trusted with actual development work.

Third, the junior will eventually (as you have) realise that they're not helping their own career. The assumption that juniors are low-quality, rather than low on (and looking for) experience is a terrible, but very common, mistake in this industry.

So, yes, sit down with your boss. But understand the predicament he's in. See if you can come to some arrangement which solves everybody's problems. You are going to need a senior mentor and some of your current tasks are going to need to be passed on to a senior. This will slow the project down but, in the long run, it will pay off. That's the point you need to get through to your boss, and possibly to their bosses. Also, see if you can find something you can offer in return to mitigate the costs.

If you can't then you might want to look elsewhere.

ContentLicense: CC BY-SA 3.0

Title: What defines "software developer" role


问:
dechex(4000) - Why is it not signed?
Why does PHP's dechex(4000) not return a signed hexadecimal value?

It returns:

```<code>fa0
</code>```

As opposed to:

```<code>0xfa0
</code>```

And is signed the correct term to use in describing this problem?  Or is there a better term to describe the 0x portion?  Is that called a prefix?

答:
I can see how you might refer to the 0x prefix as a "sign". It signifies that the following digits are hexadecimal. But in programming, we almost universally use the word "sign" to refer to something that indicates whether a number is positive or negative. In a stored numeric value, there's usually one bit that indicates whether a number is negative. In program text, we can write +42 to denote a positive integer and -42 to denote a negative integer; the + or - character is the sign. (I'm glossing over some details regarding 2's-complement and other representations, and issues regarding 0; also + and - are really operators, not part of the integer constants. Don't worry about that for now.)

So referring to anything other than a positive-or-negative indicator as a "sign" is bound to cause confusion. The 0x in a hexadecimal literal like 0xfa0 can sensibly be referred to as a prefix, not as a "sign".

The name of PHP's dechex function, documented here, is actually a bit misleading. It takes an unsigned integer argument and returns a string containing the human-readable hexadecimal representation of that argument. The argument is not decimal; it's almost certainly stored in binary. We think of integers as decimal because we usually write them that way, but in fact integer values can be written in decimal, octal, hexadecimal, or as complicated expressions -- all of which result in a binary stored value. It doesn't convert decimal to hexadecimal; it converts a number to hexadecimal -- a number that may have resulted from the conversion of a decimal literal in the PHP source code to a stored binary integer.

As for why the result of dechex() doesn't include the 0x prefix, the documentation doesn't say, but it's probably just because it's more convenient that way. If you want a string with a 0x prefix, it's trivially easy to add it yourself (and to decide whether you want 0x or 0X). If dechex() returned a string with the prefix, and you didn't want it, you'd have to remove it.

This small program demonstrates these points:

```<code>#!/usr/bin/php
<?php
    // Various arguments to dechex (decimal, octal, hexadecimal):
    echo "dechex(12345678)   = \"", dechex(12345678),   "\"\n";
    echo "dechex(012345678)  = \"", dechex(012345678),  "\"\n";
    echo "dechex(0xDEADBEEF) = \"", dechex(0xdeadbeef), "\"\n";
    echo "dechex(4*5)        = \"", dechex(4*5),        "\"\n";
    echo "With a prefix:       \"0x", dechex(4*5), "\"\n";
    // Another approach using sprintf():
    echo sprintf("0x%x", 1234), "\n";
    // ... or printf:
    printf("0X%X\n", 1234);
?>
</code>```

Here's the output:

```<code>dechex(12345678)   = "bc614e"
dechex(012345678)  = "53977"
dechex(0xDEADBEEF) = "deadbeef"
dechex(4*5)        = "14"
With a prefix:       "0x14"
0x4d2
0X4D2
</code>```

Title: dechex(4000) - Why is it not signed?

Body:
I can see how you might refer to the 0x prefix as a "sign". It signifies that the following digits are hexadecimal. But in programming, we almost universally use the word "sign" to refer to something that indicates whether a number is positive or negative. In a stored numeric value, there's usually one bit that indicates whether a number is negative. In program text, we can write +42 to denote a positive integer and -42 to denote a negative integer; the + or - character is the sign. (I'm glossing over some details regarding 2's-complement and other representations, and issues regarding 0; also + and - are really operators, not part of the integer constants. Don't worry about that for now.)

So referring to anything other than a positive-or-negative indicator as a "sign" is bound to cause confusion. The 0x in a hexadecimal literal like 0xfa0 can sensibly be referred to as a prefix, not as a "sign".

The name of PHP's dechex function, documented here, is actually a bit misleading. It takes an unsigned integer argument and returns a string containing the human-readable hexadecimal representation of that argument. The argument is not decimal; it's almost certainly stored in binary. We think of integers as decimal because we usually write them that way, but in fact integer values can be written in decimal, octal, hexadecimal, or as complicated expressions -- all of which result in a binary stored value. It doesn't convert decimal to hexadecimal; it converts a number to hexadecimal -- a number that may have resulted from the conversion of a decimal literal in the PHP source code to a stored binary integer.

As for why the result of dechex() doesn't include the 0x prefix, the documentation doesn't say, but it's probably just because it's more convenient that way. If you want a string with a 0x prefix, it's trivially easy to add it yourself (and to decide whether you want 0x or 0X). If dechex() returned a string with the prefix, and you didn't want it, you'd have to remove it.

This small program demonstrates these points:

#!/usr/bin/php
<?php
    // Various arguments to dechex (decimal, octal, hexadecimal):
    echo "dechex(12345678)   = \"", dechex(12345678),   "\"\n";
    echo "dechex(012345678)  = \"", dechex(012345678),  "\"\n";
    echo "dechex(0xDEADBEEF) = \"", dechex(0xdeadbeef), "\"\n";
    echo "dechex(4*5)        = \"", dechex(4*5),        "\"\n";
    echo "With a prefix:       \"0x", dechex(4*5), "\"\n";
    // Another approach using sprintf():
    echo sprintf("0x%x", 1234), "\n";
    // ... or printf:
    printf("0X%X\n", 1234);
?>

Here's the output:

dechex(12345678)   = "bc614e"
dechex(012345678)  = "53977"
dechex(0xDEADBEEF) = "deadbeef"
dechex(4*5)        = "14"
With a prefix:       "0x14"
0x4d2
0X4D2


问:
How have you made unit testing more enjoyable?
If you've always loved unit testing, good for you! But for the unfortunate ones who weren't born with a liking for it, how have you managed to make this task more enjoyable ?

This is not a "what is the right way to unit test" question. I simply want to know little personal tricks that reduce the boredom (dare I say) of writing unit tests.

答:
Smug superiority.

I'm only half-joking.  "Look at me, cultivating good programming habits!  This 'unit testing' stuff is something Me From Ten Years Ago never would have done -- what a fool!  And just think of all the bugs I'm going to catch as a result of this boring, tedious work I'm doing right now -- my code will be awesome!  I'll get a raise for sure!*"

* -- No, I won't.

I find it's like working out or eating healthy; until the tangible benefits actually kick in ("Holy balls, I really AM catching a crap-ton of regression errors that would have snuck into production!"), the moral pride of knowing that you're doing The Right Thing can help carry you through.

ContentLicense: CC BY-SA 2.5


问:
Is unconditional code considered a branch?
Having simple code like this:

```<code>int A=5;
object X=Console.ReadLine()
if(Condition)
   DoSomething();
else
   DoStuff();
DoSomethingElse();
</code>```

Some sources say there are actually 4 branches: First unconditional, two for the IF and another unconditional after the IF statement.
Some say there are only two branches.
What would be correct?
E.g. here:
http://www.ruleworks.co.uk/testguide/BS7925-2-Annex-B7.asp

答:
I think branch here is meant to represent a block of code with a single linear path (no jumps starts or ends in the block) better known as a basic block.

This concept is handy for compilers and other analysis tools to decide how a piece of code might behave (in the absence of exceptions) as each basic block is then an atomic operation in terms of the code around it.

For example, optimising compilers can look at each such block and decide how the dependencies for each individual instruction lies and possibly reorder them to make more efficient use of registers and the stack. Or, when only one exit path exists to a another block with only one entry, you can concatenate the blocks and eliminate the jump.


问:
Formal term to web-ify a piece of existing software or program or a module?
There is a software we run as a windows service. Its currently not designed to take a huge load. So we kind of need this service to be hosted over http so that multiple clients can make use of it. Its not the whole windows service as such, but some modules it uses. Those modules are currenly not designed to work as "web service" (generic sense).

What would be the formal word for this?

答:
"Webify" is the closest you're likely to get

After consulting English StackExchange the consensus appears to be that an "-ify" suffix is perfectly acceptable in everyday English. Consequently, when you get into conversations with other web developers working on the project they will be more likely to understand you when you use the technojargon.


答:
It depends on your context. For some analysis, such as what compilers do - you have 4 branches, since the post-if block can vary its behavior depending on which path the if goes (and if either conditional branch returns early). For some analysis like you might see in code coverage will vary to perhaps consider that somewhere between 2 and 4 branches depending on what is being done and if priority is given to the choice or to the path.

Neither view is particularly "correct" or not. They're human inventions to try and gain information and insight. Whichever metric does that better for the problem at hand is the "correct" one.

Title: Is unconditional code considered a branch?

Body:
Having simple code like this:

```<code>int A=5;
object X=Console.ReadLine()
if(Condition)
   DoSomething();
else
   DoStuff();
DoSomethingElse();
</code>```

Some sources say there are actually 4 branches: First unconditional, two for the IF and another unconditional after the IF statement.
Some say there are only two branches.
What would be correct?
E.g. here:
http://www.ruleworks.co.uk/testguide/BS7925-2-Annex-B7.asp


问:
Formatting SQL Based on an AST
I am working on my .NET open source project for generating SQL...

Initially, I wrote the project so it spit out exactly one SQL format... ugly. I started using this project in the real world and decided it would be nice if I could generate pretty SQL in debug mode and ugly SQL in release mode.

My first go involved a lot of if/else loops within my command generation code. It quickly got to be too much to handle. So, I started looking for another approach that would allow me to plug-in different formatting strategies. I also looked at other SQL formatting libraries but most were specific to one dialect.

Right now, I am playing with the idea of generating a tree of tokens, similar to an abstract syntax tree (AST) that a compiler works with. I was hoping to navigate the tree and generate text based on where I am in the tree. Now that I've built these trees, I'm not sure how to write the code to visit these nodes.

I feel like I'm going backwards. Instead of parsing SQL, generating an AST and spitting out SQL objects, I am allowing someone to build SQL objects, then generate an AST and spitting out SQL. When someone uses my library to build a SELECT statement, they specify the values to select, the tables to select from, filters, ordering, etc. But once I have generated an AST... I have less information than I originally started with! Only by asking "Is the next token the keyword FROM?" can I get a picture of where I'm at. I have to write a bunch of if/elif/else statements to figure out what comes next. At least when I had the SQL objects I could use polymorphism to avoid nasty branching.

So, perhaps I missed a day in compiler theory or perhaps it's because I'm trying to go backwards. But, for whatever reason, my next step is really unclear to me. I think the AST route was in the right direction even if it does mean losing information. I was able to write a really stupid formatter that puts spaces between every token for now. It's really when it comes to getting fancy that I'm overwhelmed.

If anyone has some good resources for going backwards, it would probably be really helpful.

答: Have you considered having a separate formatter for each expression type?  You could have a select-statement-formatter, a column-list-formatter, a from-clause-formatter, etc.  I don't know specifically how your AST is structured, but you should be able to identify the various clauses and expressions and pass them to specific formatters.

Title: Formatting SQL Based on an AST


答:
I had a chance to look at your actual code. It looks like you're most of the way there but this "tree of tokens" concept is getting in the way. It turns out you probably don't need it at all (specifically, I'm referring to the stuff in the Expressions/ folder).

For example, in Join, you have a method called GetDeclarationExpression that returns an IExpressionItem that is a tree of tokens. What I'm suggesting is that you can simplify this and instead directly return a String which is the actual SQL generated from the join. In concrete terms, something like the following:

```<code>    String IJoinItem.GetDeclarationExpression(CommandOptions options)
    {
        // [ "(" ] <Left> <Combiner> <Right> [ "ON" <Filter> ] [ ")" ]
        StringBuilder expression = new StringBuilder();
        if (WrapInParentheses ?? options.WrapJoinsInParentheses)
        {
            expression.Append("(");
        }
        expression.Append(_leftHand.GetDeclarationExpression(options));
        expression.Append(" ")
        expression.Append(GetJoinNameExpression(options));
        expression.Append(" ")
        expression.Append(_rightHand.GetDeclarationExpression(options));
        expression.Append(" ")
        expression.Append(GetOnExpression(options));
        if (WrapInParentheses ?? options.WrapJoinsInParentheses)
        {
            expression.Append(")");
        }
        return expression.ToString();
    }
</code>```

Of course, all other methods used during the AST traversal would also need to be modified to return String instead of IExpressionItem as needed. Each method that is called during the tree traversal would be responsible for generating the actual SQL string, which will all eventually get concatenated together.

Title: Formatting SQL Based on an AST

Body:
I am working on my .NET open source project for generating SQL...

Initially, I wrote the project so it spit out exactly one SQL format... ugly. I started using this project in the real world and decided it would be nice if I could generate pretty SQL in debug mode and ugly SQL in release mode.

My first go involved a lot of if/else loops within my command generation code. It quickly got to be too much to handle. So, I started looking for another approach that would allow me to plug-in different formatting strategies. I also looked at other SQL formatting libraries but most were specific to one dialect.

Right now, I am playing with the idea of generating a tree of tokens, similar to an abstract syntax tree (AST) that a compiler works with. I was hoping to navigate the tree and generate text based on where I am in the tree. Now that I've built these trees, I'm not sure how to write the code to visit these nodes.

I feel like I'm going backwards. Instead of parsing SQL, generating an AST and spitting out SQL objects, I am allowing someone to build SQL objects, then generate an AST and spitting out SQL. When someone uses my library to build a SELECT statement, they specify the values to select, the tables to select from, filters, ordering, etc. But once I have generated an AST... I have less information than I originally started with! Only by asking "Is the next token the keyword FROM?" can I get a picture of where I'm at. I have to write a bunch of if/elif/else statements to figure out what comes next. At least when I had the SQL objects I could use polymorphism to avoid nasty branching.

So, perhaps I missed a day in compiler theory or perhaps it's because I'm trying to go backwards. But, for whatever reason, my next step is really unclear to me. I think the AST route was in the right direction even if it does mean losing information. I was able to write a really stupid formatter that puts spaces between every token for now. It's really when it comes to getting fancy that I'm overwhelmed.

If anyone has some good resources for going backwards, it would probably be really helpful.

Body:
I had a chance to look at your actual code. It looks like you're most of the way there but this "tree of tokens" concept is getting in the way. It turns out you probably don't need it at all (specifically, I'm referring to the stuff in the Expressions/ folder).

For example, in Join, you have a method called GetDeclarationExpression that returns an IExpressionItem that is a tree of tokens. What I'm suggesting is that you can simplify this and instead directly return a String which is the actual SQL generated from the join. In concrete terms, something like the following:

    String IJoinItem.GetDeclarationExpression(CommandOptions options)
    {
        // [ "(" ] <Left> <Combiner> <Right> [ "ON" <Filter> ] [ ")" ]
        StringBuilder expression = new StringBuilder();
        if (WrapInParentheses ?? options.WrapJoinsInParentheses)
        {
            expression.Append("(");
        }
        expression.Append(_leftHand.GetDeclarationExpression(options));
        expression.Append(" ")
        expression.Append(GetJoinNameExpression(options));
        expression.Append(" ")
        expression.Append(_rightHand.GetDeclarationExpression(options));
        expression.Append(" ")
        expression.Append(GetOnExpression(options));
        if (WrapInParentheses ?? options.WrapJoinsInParentheses)
        {
            expression.Append(")");
        }
        return expression.ToString();
    }

Of course, all other methods used during the AST traversal would also need to be modified to return String instead of IExpressionItem as needed. Each method that is called during the tree traversal would be responsible for generating the actual SQL string, which will all eventually get concatenated together.


问:
Why is it so difficult to know where to use interfaces,generics in program design?
I am attempting to learn c# from the head first series, in addition i also consult other books such as Pro C# by Andrew Tolson.

Now the thing is that i perfectly understand the interface,generics syntax and can also use it for the programs given in the exercises.

What i find difficult is using these concepts into my own programs. For example the other day i was making a twitter account managing client and despite my best efforts i was unable to use any of the aforementioned concepts in code. I was even having difficulty in making useful classes.

What are some guidelines I can use to decide what classes I need to create for my program, assuming I know the syntax of how to create a class, but not the idea of when to do so?

答:
Think of the English meaning of interface. Both C#-interfaces and generics provide the English meaning of interface. The concept of interface goes beyond it's typical use in OOP style code.

Generics are used to acheived polymorphic behavior on the syntax of the language. For example

```<code>void foo<T>(T bar)
{
    //type T must implement the "+" interface
    bar + baz;
}
</code>```

The "+" operation is built into the syntax of the language. Type T implements the "+" interface (the English meaning). In effect polymorphic behavior is achieved. Internally the "+" operation is very different for integers and decimals, but the foo method handles both! You don't need to care how "+" is implemented. You just care if the type implements the "+" interface.

C# interfaces are used to achieve polymorphic behavior on defined methods (rather than source code level syntax).

```<code>void foo(IBar bar)
{
    bar.doSomething();
}
</code>```

There may be several types which implement IBar. They each doSomething() very differently. Much the same as with generics you dont' care how they doSomething(). You only care that they implement the interface. The difference is the "interface" is a contract of defined methods rather than source code syntax.

Body:
Think of the English meaning of interface. Both C#-interfaces and generics provide the English meaning of interface. The concept of interface goes beyond it's typical use in OOP style code.

Generics are used to acheived polymorphic behavior on the syntax of the language. For example

void foo<T>(T bar)
{
    //type T must implement the "+" interface
    bar + baz;
}

The "+" operation is built into the syntax of the language. Type T implements the "+" interface (the English meaning). In effect polymorphic behavior is achieved. Internally the "+" operation is very different for integers and decimals, but the foo method handles both! You don't need to care how "+" is implemented. You just care if the type implements the "+" interface.

C# interfaces are used to achieve polymorphic behavior on defined methods (rather than source code level syntax).

void foo(IBar bar)
{
    bar.doSomething();
}

There may be several types which implement IBar. They each doSomething() very differently. Much the same as with generics you dont' care how they doSomething(). You only care that they implement the interface. The difference is the "interface" is a contract of defined methods rather than source code syntax.


答:
The origins of the word 'branch' in code comes from assembly.  An example of this can be seen in MIPS assembly.  A branch is a conditional statement.

Before anyone jumps on me for point out that MIPS has a b instruction which has the description of "branch unconditionally" the key to the difference between b (branch unconditionally) and j (jump) is that the branch statements work off of relative addresses and the jump statements work off of absolute addresses.

There is also some terminology of unconditional branch in the realm of branch prediction.  A CPU with a pipeline will try to guess which way a branch statement goes and where it will end up after the branch.  It is possible to analize the assembly to see that a given branch will always execute given a certain set of conditions at the start of the pipline.  For example, the branch is based on if register 1 is greater than 0 or not.  If register 1 is 0, and no instructions in the pipeline change that, it is in essence an unconditional branch which can be executed safely (and not having to worry about flush the pipeline after speculative execution or stall until the branch can be decided).

All of the above was for very low level code.  In higher level code (as demonstrated in the question) the terminology of a branch is where code may follow two (or more in the case of a switch (pun not intended)) different paths.  From wikipedia

A branch is sequence of code in a computer program which is conditionally executed depending on how the flow of control is altered at the branching point.

Unconditional code is not conditionally executed and thus is not a branch.


问:
Unit Test Friendly Domain Driven Design
Many of the readings I've done on DDD, both in books and online, seem to represent code that, often times, is difficult or impossible to unit test. For example, there are numerous samples with static factories, calls to concrete domain classes and static extension methods (in C# samples only). I find it frustrating and taxing to have to constantly re-evaluate the code to make it testable in my mind.

Can anyone suggest material that demonstrates DDD code with 100% testability in mind (preferably in C#)?

Also, to meander a bit:

Is the fact that many of the code samples are not test-friendly a sign (smell) that DDD is becoming antiquated?

答:
Is the fact that many of the code samples are not test-friendly a sign
  (smell) that DDD is becoming antiquated?

I don't believe that. I would say that it's a sign that whoever has given the smelly DDD code samples was focused on that and not unit testing. It's not difficult to morph that code into that which is crafted with those ends in mind.

Now I don't mean to toot my own horn too much, but feel free take a look at this question and my answer over at Code Review. I think I took some fairly common DDD code and whipped it into at least a more testable state (maybe not 100% testability, but definitely more so).

I've also attended a couple DDD presentations from from Stephen A. Bohlen and here's a blog entry with a link to some of his code and slides. I've taken that code and did some refactoring much like I did on the CR answer.

Title: Unit Test Friendly Domain Driven Design


答: I've most commonly heard the term "modernization" used to describe this process, but have also heard it called "web migration" and "web-enabling." Here's a quick definition of modernization from wikipedia, and while it's not a perfect match, it seems pretty close to what you're looking for.</p>

Title: Formal term to web-ify a piece of existing software or program or a module?

Body:
There is a software we run as a windows service. Its currently not designed to take a huge load. So we kind of need this service to be hosted over http so that multiple clients can make use of it. Its not the whole windows service as such, but some modules it uses. Those modules are currenly not designed to work as "web service" (generic sense).

What would be the formal word for this?


问:
How would Functional Programming proponents answer this statement in Code Complete?
On page 839 of the second edition, Steve McConnell is discussing all the ways that programmers can "conquer complexity" in big programs. His tips culminate with this statement:

"Object-oriented programming provides a level of abstraction that applies to algorithms and data at the same time, a kind of abstraction that functional decomposition alone didn't provide."

Coupled with his conclusion that "reducing complexity is arguably the most important key to being an effective programmer" (same page), this seems to pretty much a challenge to functional programming.

The debate between FP and OO is often framed by FP proponents around the issues of complexity that derives specifically from the challenges of concurrency or parallelization. But concurrency is certainly not the only kind of complexity software programmers need to conquer. Perhaps focusing on reducing one sort of complexity increases it greatly in other dimensions, such that for many cases, the gain is not worth the cost.

If we shifted the terms of the comparison between FP and OO from particular issues like concurrency or reusability to the management of global complexity, how would that debate look?

EDIT

The contrast I wanted to highlight is that OO seems to encapsulate and abstract away from the complexity of both data and algorithms, whereas functional programming seems encourage leaving the implementation details of data structures more "exposed" throughout the program.

See, e.g., Stuart Halloway (a Clojure FP proponent) here saying that "the over-specification of data types" is "negative consequence of idiomatic OO style" and favoring conceptualizing an AddressBook as a simple vector or map instead of a richer OO object with additional (non-vectorish & non-maplike) properties and methods. (Also, OO and Domain-Driven Design proponents may say that exposing an AddressBook as a vector or map overexposes the encapsulated data to methods that are irrelevant or even dangerous from the standpoint of the domain).

答:
Anyone who ever programmed in dBase would know how useful single line macros were to making reusable code.  Although I haven't programmed in Lisp, I have read from many others who swear by compile time macros. The idea of injecting code into your code at compile time is used in a simple form in every C program with the "include" directive. Because Lisp can do this with a Lisp program and because Lisp is highly reflective, you get much more flexible includes.

Any programmer that would just take an arbitrary text string from the web and pass it on to their database isn't a programmer. Likewise, anybody that would allow "user" data to automatically become executable code is obviously stupid. That doesn't mean that allowing programs to manipulate data at execution time and then execute it as code is a bad idea. I believe that this technique will be indispensable in the future which will have "smart" code actually writing most programs. The whole "data/code problem" or not is a matter of security in the language.

One of the problems with most languages is that they were made for a single off line person to execute some functions for themselves. Real world programs require that many people have access at all times and at the same time from multiple Cores and multiple computer clusters. Security should be a part of the language rather than the operating system and in the not too distant future it will be.


问:
Name for a bug that disappears when someone else looks at it
Does anyone know of an existing name for a bug that disappears the moment you call someone over to look at it?  It's a funny phenomenon, but it has happened from time to time that I'm working on a bug that consistently appears, but as soon as I call over a colleague to look at it with me, the buggy behavior stops and doesn't reappear.

This is distinct from any of the other oddball bug names I've found, such as heisenbug or mandelbug, in that it's definitely there, even when attempting to study it, until it's shown to someone else.

My coworker proposed the name "Calvinbug" for this phenomenon, after Calvin & Hobbes. Thoughts?

And no, I'm not crazy. :)

答:
I know of no formal term for such a bug, but I would propose the following options:

Schrödinger's Bug - you changed the outcome by measuring it!

Snuffleupabugs -- After Mr. Snuffleupagus, back when only Big Bird could see it.

Unfortunately this one will be lost on the younger coders


问:
RESTful Design: Multiple Relationships Between the Same 2 Entities
I am in the process of designing RESTful web services and got stuck at one point. The design is very simple with 3 entities:

```<code>- Project
- Status
- Employee
</code>```

The part I am having trouble with is capturing the relationships:

```<code>- A project has a current status (1 to 1 between Project and Status).
- A project has multiple 'possible subsequent status' (1 to many between Project and Status).
</code>```

The Visual Studio designer does not allow these two different relationships to be defined between these two entities. I am aware that it is just a modelling tool but at the same time, I am willing to know if this is the right approach.

Also, with this design, I am not sure how to access the Status entities using these two relationships.

```<code>http://serviceRootURL/Project(2)?$expand=Status // For current status
http://serviceRootURL/Project(2)?$expand=SubsequentStatus // For subsequent status
</code>```

Is it possible to use arbitrary relationship names with the expand keyword?

(The question probably touches OData a little bit as well since I am trying to make my library OData-compliant.)

答:
In VS 2012 Express, I was able to model two relationships between the same entities separately in an EDMX model. By selecting the relationship in the canvas, you can use the property pane on the right to give them different names and cardinalities. Also pay attention to the parent property name (in the pane, it's the "End2 Navigation Property").

Having modeled the relationships and exposed the model through OData, you can use the OData $expand option with the name of the relationship (like what you showed) to embed the related entities in the response to parent entities.


问:
Requirement specifications with annotations?
I'm curious if there are any templates using annotations such as ambiguous, needs update and so on. Industrial or Academic does not matter.

If there are, are there any way tools available that use these annotations to show that "22% of the requirements are tagged ambiguous" and so on?

Bonus points for Academic papers on this topic (or a nearly related topic)

答:
For mobile software specification, we were using plain word documents to formalize requirements. We just used color conventions to annotate requirement status, like:

dark for validated

grey for new (not reviewed)

red for requirement with issue discovered during review (before fix)

green for requirement fixed after review (before change acceptance review)

purple for requirement where client and subcontractor cannot agree on the requirement (these need special attention)

There was also a tracking of requirement status progress, updated by counting colored requirements when the document is edited.

For airborne software requirements, before formal review, we were using a yellow underfill whenever the content is known to be incomplete (like a 'todo'). It's more like a reminder for the document writer. There shall not be any yellow underfill before a formal review.

I found these color conventions quite efficient (agile?) to reduce the workload, compared to bug tracking or DOORS tools. Moreover it's very easy to define your own standard.


问:
Revenue sharing with customer who is unable to pay development fee
I have a potential customer who has an idea for an ipad application but is unable to find sufficient fundings for this.

One idea that came up is that I do the work either for free or for a minor fee and then receive a percentage of the income from appstore.

How do I decide what percentage is realistic?

How is this affected by the price in appstore and how do I protect myself from the scenario where the customer suddenly decides to offer the app for free?

答:
It's obvious that the execution is the money maker, but execution on a bad idea is usually just as worthless as an unexecuted good idea. So the quality of the idea is worth something. The way I see it, if a client wants to pay my full development fee, then the app is theirs. Conversely, if I do ALL the work, the app is pretty much mine. To give them options on striking a shared-risk deal, I think the profit (not revenue) split should be an inverse of the fee split. So if they want to pay 70% of the upfront cost, you split the profits 70/30 in their favor (70% of the risk = 70% of the return). If they only want to pay 25% of the cost (or do 25% of the work), then you take 75% of the profits... and so on.

Let me know what you guys think of that. Only do this if you think the app will make money over time, though. Otherwise, recoup your time & materials costs as quickly as possible and move on.


答:
Isn't DDD essentially 'top down' you design and refine a model based on domain knowledge/experience.

Whereas TDD is 'bottom up' program design is influenced by the refactoring process and encouraging decoupling to enhance test-ability.

So as these are at odd's with each other... I believe it's hard to demonstrate DDD code with 100% test-ability.

I believe that it's impossible to reach a 100% test-ability, so i always pursuit a 70-90%.

Title: Unit Test Friendly Domain Driven Design

Body:
Many of the readings I've done on DDD, both in books and online, seem to represent code that, often times, is difficult or impossible to unit test. For example, there are numerous samples with static factories, calls to concrete domain classes and static extension methods (in C# samples only). I find it frustrating and taxing to have to constantly re-evaluate the code to make it testable in my mind.

Can anyone suggest material that demonstrates DDD code with 100% testability in mind (preferably in C#)?

Also, to meander a bit:

Is the fact that many of the code samples are not test-friendly a sign (smell) that DDD is becoming antiquated?


问:
Why do I need unit tests for testing repository methods?
I need to play devils advocate on this question a bit because I cannot defend it well because of lack of experience. Here is the deal, I get conceptually the differences between unit testing and integration testing. When specifically focusing in on persistence methods and the repository, a unit test would use a mock possibly via a framework like Moq to assert that say an order searched for was returned as expected.

Let's say I have built the following unit test:

```<code>[TestMethod]
public void GetOrderByIDTest()
{
   //Uses Moq for dependency for getting order to make sure
   //ID I set up in 'Arrange' is same one returned to test in 'Assertion'
}
</code>```

So if I set up OrderIdExpected = 5 and my mock object returns 5 as the ID my test will pass. I get it. I unit tested the code to make sure what my code preforms returns the expected object and ID and not something else.

The argument I will get is this:

"Why not just skip the unit tests and do integration tests? It's
  testing the database stored procedure and your code together that's
  important. It seems like too much extra work to have unit tests and
  integration tests when ultimately I want to know if the database calls
  and the code work. I know the tests take longer, but they have to be run and tested regardless so it seems pointless to me to have both. Just test against what matters."

I could defend it with a text book definition like: "Well that's an integration test and we need to test the code separately as a unit test and, yada, yada, yada..." This is a case where a purist explanation of practices vs. reality is loosing out. I run into this sometimes and if I can't defend the reasoning behind unit testing code that ultimately relies on external dependencies, than I can't make a case for it.

Any help on this question is greatly appreciated, thanks!

答:
Unit tests and integration tests have different purposes.

Unit tests verify the functionality of your code... that you get what you expect back from the method when you call it.  Integration tests test how the code behaves when combined together as a system.  You wouldn't expect unit tests to evaluate system behavior, nor would you expect integration tests to verify specific outputs of a particular method.

Unit tests, when done correctly, are easier to set up than integration tests.  If you rely solely on integration tests, your testing is going to:

Be more difficult to write, overall,

Be more brittle, due to all of the required dependencies, and

Offer less code coverage.

Bottom line:  Use integration testing to verify that the connections between objects are working properly, but lean on unit testing first to verify functional requirements.

All that said, you may not need unit testing for certain repository methods.  Unit testing should not be done on trivial methods; if all you're doing is passing through a request for an object to ORM generated code and returning a result, you don't need to unit test that, in most cases; an integration test is adequate.


问:
What's a nice explanation for pointers?
In your own studies (on your own, or for a class) did you have an "ah ha" moment when you finally, really understood pointers? Do you have an explanation you use for beginner programmers that seems particularly effective?

For example, when beginners first encounter pointers in C, they might just add &s and *s until it compiles (as I myself once did). Maybe it was a picture, or a really well motivated example, that made pointers "click" for you or your student. What was it, and what did you try before that didn't seem to work? Were any topics prerequisites (e.g. structs, or arrays)?

In other words, what was necessary to understand the meaning of &s and *, when you could use them with confidence? Learning the syntax and terminology or the use cases isn't enough, at some point the idea needs to be internalized.

Update: I really like the answers so far; please keep them coming. There are a lot of great perspectives here, but I think many are good explanations/slogans for ourselves after we've internalized the concept. I'm looking for the detailed contexts and circumstances when it dawned on you.

For example:

I only somewhat understood pointers
  syntactically in C. I heard two of my
  friends explaining pointers to another
  friend, who asked why a struct was
  passed with a pointer. The first
  friend talked about how it needed to
  be referenced and modified, but it was
  just a short comment from the other
  friend where it hit me: "It's also
  more efficient." Passing 4 bytes
  instead of 16 bytes was the final
  conceptual shift I needed.

答:
The explanation that i really grocked was:

Consider a city grid with different houses built on pieces of land.
In your hand you hold a piece of paper. On the paper you have written:

David's house,

112 So and so street.

The piece of paper (pointer variable) contains an address that points to David's house. When you want to tell a friend to have a look at David's cool house it is much easier to use the pice of paper as a reference to the house than to send the actual two story building in the mail.

As with real pointers you can get into some trouble when you follow the address on your piece of paper. David could have moved and when you get there you just find a big hole in the ground. In this case it would have been better to erase the address on the paper when David moved or at least change it to the new one. You could also find that you go to the address and enter what you think is your friend David's living room but this time you end up in a complete strangers swimming pool. Someone else has used the space at the address you had for something completely different.

Title: What's a nice explanation for pointers?


答:
Unit tests provide a level of modularity that integration tests (by design) cannot.  When a system is refactored or recomposed, (and this will happen) unit tests can often be reused, whereas integration tests must often be re-written.  Integration tests that try to do the work of something that should be in a unit test are often doing too much, which makes them hard to maintain.

Additionally, including unit testing has the following benefits:

Unit tests allow you to quickly decompose a failing integration test (possibly due to a regression bug) and identify the cause.  Moreover, this will communicate the problem to the entire team more quickly than diagrams or other documentation.

Unit tests can serve as examples and documentation (a type of documentation that actually compiles) along with your code.  Unlike other documentation you'll know instantly when it's out of date.

Unit tests can serve as baseline performance indicators when trying to decompose larger performance issues, whereas integration tests tend to require lots of instrumentation to find the problem.

It is possible to split your work (and enforce a DRY approach) while using both Unit and Integration tests.  Simply rely on unit tests for small units of functionality, and don't repeat any logic that is already in a unit test in an integration test.  This will often lead to less work (and therefore less re-work).

Title: Why do I need unit tests for testing repository methods?

Body:
I need to play devils advocate on this question a bit because I cannot defend it well because of lack of experience. Here is the deal, I get conceptually the differences between unit testing and integration testing. When specifically focusing in on persistence methods and the repository, a unit test would use a mock possibly via a framework like Moq to assert that say an order searched for was returned as expected.

Let's say I have built the following unit test:

```<code>[TestMethod]
public void GetOrderByIDTest()
{
   //Uses Moq for dependency for getting order to make sure
   //ID I set up in 'Arrange' is same one returned to test in 'Assertion'
}
</code>```

So if I set up OrderIdExpected = 5 and my mock object returns 5 as the ID my test will pass. I get it. I unit tested the code to make sure what my code preforms returns the expected object and ID and not something else.

The argument I will get is this:

"Why not just skip the unit tests and do integration tests? It's
  testing the database stored procedure and your code together that's
  important. It seems like too much extra work to have unit tests and
  integration tests when ultimately I want to know if the database calls
  and the code work. I know the tests take longer, but they have to be run and tested regardless so it seems pointless to me to have both. Just test against what matters."

I could defend it with a text book definition like: "Well that's an integration test and we need to test the code separately as a unit test and, yada, yada, yada..." This is a case where a purist explanation of practices vs. reality is loosing out. I run into this sometimes and if I can't defend the reasoning behind unit testing code that ultimately relies on external dependencies, than I can't make a case for it.

Any help on this question is greatly appreciated, thanks!


问:
How do I know if I have enough unit test coverage to remove an integration test?
I'm working on a legacy system (by that I mean it was written without tests).  We've tried to test some of the system by writing integration tests that test functionality from the outside.

This gives me some confidence to refactor parts of the code without worry about breaking it. But the problem is these integration tests require a deploy (2+ minutes) and many minutes to run.  Also, they are a pain to maintain.  They each cover thousands of lines of code and when one of them breaks it can take hour(s) to debug why.

I've been writing lots of unit tests for these functional changes I've been making lately, but before I commit I always do a new deploy and run all integration tests, just to make sure I didn't miss anything.  At this point I know my unit tests and some of the integration tests are overlapping what they test.

How do I know when my good unit tests are adequately covering a bad integration test so that I can delete that integration test?

答:
The easiest metric is to ask, "when was the last time this integration test legitimately failed?" If it has been a long time (there have been a lot of changes) since the integration test failed, then the unit tests are probably doing a good enough job. If the integration test has failed recently, then there was a defect that was not caught by the unit tests.

My preference would generally be to increase the robustness of the integration tests, to the point where they can be reliably run unattended. If they take a long time to run, then run them overnight. They are still valuable even if they are only run occasionally. If these tests are too fragile or require manual intervention, then it may not be worth the time spent in keeping them running, and you may consider discarding those that succeed most often.


答:
There are 3 separate things that need testing: the stored procedure, the code that calls the stored procedure (i.e. your repository class), and the consumer.  The repository's job is to generate a query and convert the returned data set into a domain object.  There's enough code to support unit testing that separate from the actual execution of the query and the creation of the data set.

So (this is a very very simplified example):

```<code>interface IOrderRepository
{
    Order GetOrderByID(Guid id);
}

class OrderRepository : IOrderRepository
{
    private readonly ISqlExecutor sqlExecutor;
    public OrderRepository(ISqlExecutor sqlExecutor)
    {
        this.sqlExecutor = sqlExecutor;
    }

    public Order GetOrderByID(Guid id)
    {
        var sql = "SELECT blah, blah FROM Order WHERE OrderId = @p0";
        var dataset = this.sqlExecutor.Execute(sql, p0 = id);
        var result = this.orderFromDataset(dataset);
        return result;
    }
}
</code>```

Then when testing OrderRepository, pass in a mocked ISqlExecutor and check that the object under test passes in the correct SQL (that's its job) and returns a proper Order object given some result dataset (also mocked).  Likely the only way to test the concrete SqlExecutor class is with integration tests, fair enough, but that's a thin wrapper class and will rarely ever change, so big deal.

You still have to unit test your stored procedures too.

Body:
There are 3 separate things that need testing: the stored procedure, the code that calls the stored procedure (i.e. your repository class), and the consumer.  The repository's job is to generate a query and convert the returned data set into a domain object.  There's enough code to support unit testing that separate from the actual execution of the query and the creation of the data set.

So (this is a very very simplified example):

interface IOrderRepository
{
    Order GetOrderByID(Guid id);
}

class OrderRepository : IOrderRepository
{
    private readonly ISqlExecutor sqlExecutor;
    public OrderRepository(ISqlExecutor sqlExecutor)
    {
        this.sqlExecutor = sqlExecutor;
    }

    public Order GetOrderByID(Guid id)
    {
        var sql = "SELECT blah, blah FROM Order WHERE OrderId = @p0";
        var dataset = this.sqlExecutor.Execute(sql, p0 = id);
        var result = this.orderFromDataset(dataset);
        return result;
    }
}

Then when testing OrderRepository, pass in a mocked ISqlExecutor and check that the object under test passes in the correct SQL (that's its job) and returns a proper Order object given some result dataset (also mocked).  Likely the only way to test the concrete SqlExecutor class is with integration tests, fair enough, but that's a thin wrapper class and will rarely ever change, so big deal.

You still have to unit test your stored procedures too.


答: Units tests are not the holy grail of testing, they are only one tool of many than should be used to test a code base. Therefore no amount of unit tests should ever be considered safe to replace other tests. If you have a bad integration test you should work to make it a good integration test, not replace it with something else, that is like replacing your front door with a perimeter fence and a gate.</p>

Title: How do I know if I have enough unit test coverage to remove an integration test?

Body:
I'm working on a legacy system (by that I mean it was written without tests).  We've tried to test some of the system by writing integration tests that test functionality from the outside.

This gives me some confidence to refactor parts of the code without worry about breaking it. But the problem is these integration tests require a deploy (2+ minutes) and many minutes to run.  Also, they are a pain to maintain.  They each cover thousands of lines of code and when one of them breaks it can take hour(s) to debug why.

I've been writing lots of unit tests for these functional changes I've been making lately, but before I commit I always do a new deploy and run all integration tests, just to make sure I didn't miss anything.  At this point I know my unit tests and some of the integration tests are overlapping what they test.

How do I know when my good unit tests are adequately covering a bad integration test so that I can delete that integration test?


答:
Keep in mind that the book was written over 20 years go.  To professional programmers of the day, FP didn't exist - it was entirely in the realm of academics & researchers.

We need to frame "functional decomposition" in the proper context of the work.  The author is not referring to functional programming.  We need to tie this back to "structured programming" and the GOTO filled mess that came before it.  If your point of reference is an old FORTRAN/COBOL/BASIC that didn't have functions (maybe, if you were lucky you'd get a single level of GOSUB) and all your variables are global, being able to break your program down into layers of functions is a major boon.

OOP is a further refinement on this sort of 'functional decomposition'.  Not only can you bundle instructions together in functions but you can group related functions with the data they're working on.  The result is a clearly defined piece of code that you can look at and understand (ideally) without having to chase all around your codebase to find what else might operate on your data.

Title: How would Functional Programming proponents answer this statement in Code Complete?

Body:
On page 839 of the second edition, Steve McConnell is discussing all the ways that programmers can "conquer complexity" in big programs. His tips culminate with this statement:

"Object-oriented programming provides a level of abstraction that applies to algorithms and data at the same time, a kind of abstraction that functional decomposition alone didn't provide."

Coupled with his conclusion that "reducing complexity is arguably the most important key to being an effective programmer" (same page), this seems to pretty much a challenge to functional programming.

The debate between FP and OO is often framed by FP proponents around the issues of complexity that derives specifically from the challenges of concurrency or parallelization. But concurrency is certainly not the only kind of complexity software programmers need to conquer. Perhaps focusing on reducing one sort of complexity increases it greatly in other dimensions, such that for many cases, the gain is not worth the cost.

If we shifted the terms of the comparison between FP and OO from particular issues like concurrency or reusability to the management of global complexity, how would that debate look?

EDIT

The contrast I wanted to highlight is that OO seems to encapsulate and abstract away from the complexity of both data and algorithms, whereas functional programming seems encourage leaving the implementation details of data structures more "exposed" throughout the program.

See, e.g., Stuart Halloway (a Clojure FP proponent) here saying that "the over-specification of data types" is "negative consequence of idiomatic OO style" and favoring conceptualizing an AddressBook as a simple vector or map instead of a richer OO object with additional (non-vectorish & non-maplike) properties and methods. (Also, OO and Domain-Driven Design proponents may say that exposing an AddressBook as a vector or map overexposes the encapsulated data to methods that are irrelevant or even dangerous from the standpoint of the domain).


答:
I am on the pragmatists' side. Don't test your code twice.

We only write integration tests for our repositories. These tests are only dependent on a simple test setup that run against an in-memory database. I think they provide everything a unit test does, and more.

They can substitute for unit tests when doing TDD. While there is some more test code boilerplate to write before you can start with the real code, it works very well with the red/green/refactor approach once everything is in place.

They test the real code of the repository - the code contained in SQL strings or ORM commands. It is more important to verify that the query is correct than it is to verify that you actually sent some string to a StatementExecutor.

They are excellent as regression tests. If they fail, it's always due to a real problem, such as a change in the schema that has not been accounted for.

They are indispensible when changing the database schema. You can be confident that you have not changed the schema in a way that breaks your application as long as the test pass. (The unit test is useless in this case, because when the stored procedure no longer exists, the unit test will still pass.)


答:
The quoted sentence does not have any validity anymore, as far as I can see.

Contemporary OO languages can not abstract over types whose kind is not *, i.e. higher kinded types are unknown. Their type system does not allow to express the idea of "some container with Int elements, that allows to map a function over the elements".

Hence, this basic function like Haskells

```<code>fmap :: Functor f => (a -> b) -> f a -> f b
</code>```

cannot be written easily in Java*), for example, at least not in a type safe way.
Hence, to obtain basic functionality, you have to write lots of boilerplate, because you need

a method to apply a simple function to elements of a list

a method to apply the same simple function to elements of an array

a method to apply the same simple function to values of a hash,

.... set

.... tree

... 10. unit tests for the same

And yet, those five methods are basically the same code, give or take some.
In contrast, in Haskell, I'd need:

A Functor instance for list, array, map, set and tree (mostly predefined, or can be derived automatically by the compiler)

the simple function

Note that this is not going to change with Java 8 (just that one can apply functions more easily, but then, exactly, will the problem above materialize. As long as you do not even have higher order functions, you are most likely not even able to understand what higher kinded types are good for.)

Even new OO languages like Ceylon do not have higher kinded types. (I have asked Gavin King lately, and he told me, it was not important at this time.)
Don't know about Kotlin, though.

*) To be fair, you can have an interface Functor that has a method fmap. Bad thing is, you can't say: Hey, I know how to implement fmap for library class SuperConcurrentBlockedDoublyLinkedDequeHasMap, dear compiler, please accept that from now on, all SuperConcurrentBlockedDoublyLinkedDequeHasMaps are Functors.

Body:
The quoted sentence does not have any validity anymore, as far as I can see.

Contemporary OO languages can not abstract over types whose kind is not *, i.e. higher kinded types are unknown. Their type system does not allow to express the idea of "some container with Int elements, that allows to map a function over the elements".

Hence, this basic function like Haskells

fmap :: Functor f => (a -> b) -> f a -> f b

cannot be written easily in Java*), for example, at least not in a type safe way.
Hence, to obtain basic functionality, you have to write lots of boilerplate, because you need

a method to apply a simple function to elements of a list

a method to apply the same simple function to elements of an array

a method to apply the same simple function to values of a hash,

.... set

.... tree

... 10. unit tests for the same

And yet, those five methods are basically the same code, give or take some.
In contrast, in Haskell, I'd need:

A Functor instance for list, array, map, set and tree (mostly predefined, or can be derived automatically by the compiler)

the simple function

Note that this is not going to change with Java 8 (just that one can apply functions more easily, but then, exactly, will the problem above materialize. As long as you do not even have higher order functions, you are most likely not even able to understand what higher kinded types are good for.)

Even new OO languages like Ceylon do not have higher kinded types. (I have asked Gavin King lately, and he told me, it was not important at this time.)
Don't know about Kotlin, though.

*) To be fair, you can have an interface Functor that has a method fmap. Bad thing is, you can't say: Hey, I know how to implement fmap for library class SuperConcurrentBlockedDoublyLinkedDequeHasMap, dear compiler, please accept that from now on, all SuperConcurrentBlockedDoublyLinkedDequeHasMaps are Functors.


问:
Design pattern for object conversion (java)
I don't use design patterns very often, besides an occasional factory and MVC, and I want to start using them more.

I have a concrete case at hand that I would like your opinion on the use of design patterns in this case.

In my application I have to convert objects pretty often in different situations. I might have to convert a Hibernate POJO to a DTO, because I use GWT and Hibernate POJO's aren't serializable and can't be sent over the line.

In another situation I might need to convert Java objects to SolrInputDocument's for indexing by Solr.

I would like to know if I should use a design pattern for this. It seems that "object conversion" is a generic task that could be handled in a flexible/abstract way by a pattern, but I don't really see how.

Without patterns I would just create a separate class for each type of conversion, for example CourseToSolrInputDocument (Course is a Hibernate entity in my application). Or CourseToCourseDTO. Each of these conversion classes might have a single static method called convert() that takes the source object as input and returns the output object.

But that is not really a pattern, is it? So I started of on something with generics and created this class that implements the Converter interface. But is somehow feels silly tgo create a generic interface and I don't really see the advantage other than being able to congratulate myself on the use of generics.

```<code>public class CourseToSolrInputDocument implements Converter<Course, SolrInputDocument>         {
    @Override
    public void convert(Course source, SolrInputDocument destination) {
        //To change body of implemented methods use File | Settings | File Templates.
    }
}
</code>```

So, the real question here is: is there a pattern that applies to generic object conversion and, what would be your approach and what are the advantages over using just a class-per-conversion type approach?

答:
The Translator Pattern is what you're asking for.

But I suspect what you're looking for is a framework, more than a pattern. I believe Dozer is popular in the Java world.


问:
When to use weak references in .Net?
I have not personally come across a situation where I've needed to use WeakReference type in .Net, but the popular belief seems to be that it should be used in caches. Dr Jon Harrop gave a very good case against the use of WeakReferences in caches in his answer to this question.

I've also often heard AS3 developers talk about using weak references to save on memory footprint but based on the conversations I've had it seems to add complexity without necessarily accomplishing the intended goal, and the runtime behaviour is rather unpredictable. So much so that many simply give up on it and instead manage the memory usage more carefully/optimize their code to be less memory intensive (or making the trade-off of more CPU-cycles and smaller memory footprint).

Dr Jon Harrop also pointed out in his answer that the .Net weak references are not soft, and there's an aggressive collection of weak references at gen0. According to MSDN, long weak references gives you the potential to recreate an object, but the state of the object remains unpredictable.!

Given these characteristics, I can't think of a situation where weak references would be useful, perhaps someone could enlighten me?

答:
If you have cache layer implemented with C# it's much better too put your data in cache as weak references, it could help to improve your cache layer performance.

Think that approach also could be applied to session implementation. Because session is long living object most of the time, it could be some case when you have no memory for new user. In that case it will be much better to delete some else user session object then throwing OutOfMemoryException.

Also, if you have a large object in your application (some big lookup table, etc), that should be used quite seldom and recreating of such an object isn't a very expensive procedure. Then better have it like a week reference to have a way to free your memory when you really need that.

OwnerDisplayName: theburningmonk

Title: When to use weak references in .Net?


答:
Given these characteristics, I can't think of a situation where weak references would be useful, perhaps someone could enlighten me?

Microsoft document Weak Event Patterns.

In applications, it is possible that handlers that are attached to event sources will not be destroyed in coordination with the listener object that attached the handler to the source. This situation can lead to memory leaks. Windows Presentation Foundation (WPF) introduces a design pattern that can be used to address this issue, by providing a dedicated manager class for particular events and implementing an interface on listeners for that event. This design pattern is known as the weak event pattern.

...

The weak event pattern is designed to solve this memory leak problem. The weak event pattern can be used whenever a listener needs to register for an event, but the listener does not explicitly know when to unregister. The weak event pattern can also be used whenever the object lifetime of the source exceeds the useful object lifetime of the listener. (In this case, useful is determined by you.) The weak event pattern allows the listener to register for and receive the event without affecting the object lifetime characteristics of the listener in any way. In effect, the implied reference from the source does not determine whether the listener is eligible for garbage collection. The reference is a weak reference, thus the naming of the weak event pattern and the related APIs. The listener can be garbage collected or otherwise destroyed, and the source can continue without retaining noncollectible handler references to a now destroyed object.

Title: When to use weak references in .Net?

Body:
I have not personally come across a situation where I've needed to use WeakReference type in .Net, but the popular belief seems to be that it should be used in caches. Dr Jon Harrop gave a very good case against the use of WeakReferences in caches in his answer to this question.

I've also often heard AS3 developers talk about using weak references to save on memory footprint but based on the conversations I've had it seems to add complexity without necessarily accomplishing the intended goal, and the runtime behaviour is rather unpredictable. So much so that many simply give up on it and instead manage the memory usage more carefully/optimize their code to be less memory intensive (or making the trade-off of more CPU-cycles and smaller memory footprint).

Dr Jon Harrop also pointed out in his answer that the .Net weak references are not soft, and there's an aggressive collection of weak references at gen0. According to MSDN, long weak references gives you the potential to recreate an object, but the state of the object remains unpredictable.!

Given these characteristics, I can't think of a situation where weak references would be useful, perhaps someone could enlighten me?


问:
Learning a new language and framework, should I spike a project, or first ground myself in the language fundamentals?
I've got substantial J2EE experience, have worked with Grails, and am comfortable with several languages (Perl, PHP, Smalltalk). I've decided to try a new project using Ruby on Rails. For those who've decided to migrate to a new technology stack, how do you make the transition? Do you learn the details of Ruby first (I've done a few tutorials, and feel like I've got a decent enough grasp of the language to start doing some basic work) or do you do a full Ruby on Rails tutorial, and expand your knowledge from there. I'm leaning towards the latter approach because I feel like I can delve into details of the language as I encounter them. For those who work in Ruby on Rails, how did you learn, and which resources do you recommend?</p>

答: The best way to learn a new language is simply to use it (reading tutorials won't make it 'click') and one way that I've been assured is fantastic is through writing tests.  I'm yet to try this myself (and will do so this weekend) but give Ruby Koans a go and let me know how you get on :)</p>


答:
Let me put this out first and come back to it:

A WeakReference is useful when you want to keep tabs on an object, but you DO NOT want your observations to prevent that object from being collected

So let's start from the beginning:

--apologies in advance for any unintentional offense, but I'm gonna back up to "Dick and Jane" level for a moment since one can never tell ones audience.

So when you've got an object X - let's specify it as an instance of class Foo - it CANNOT live on it's own (mostly true); In the same way that "No man is an island", there are only a few ways that an object can promoted to Islandhood - although it's called being a GC root in CLR speak. Being a GC Root, or having an established chain of connections/references to a GC root, is basically what determines whether or not Foo x = new Foo() gets garbage collected.

If you cannot walk your way back to some GC root either by heap or stack walking, you are effectively orphaned, and will likely be marked/collected next cycle.

At this point, let's look at some horrible-contrived examples:

First, our Foo:

```<code>public class Foo
{
    private static volatile int _ref = 0;
    public event EventHandler FooEvent;
    public Foo()
    {
        _ref++;
        Console.WriteLine("I am #{0}", _ref);
    }
    ~Foo()
    {
        Console.WriteLine("#{0} dying!", _ref--);
    }
}
</code>```

Fairly simple - it's not thread safe, so don't try that, but keeps a rough "reference count" of active instances and decrements when they are finalized.

Now let's look at a FooConsumer:

```<code>public class NastySingleton
{
    // Static member status is one way to "get promoted" to a GC root...
    private static NastySingleton _instance = new NastySingleton();
    public static NastySingleton Instance { get { return _instance;} }

    // testing out "Hard references"
    private Dictionary<Foo, int> _counter = new Dictionary<Foo,int>();
    // testing out "Weak references"
    private Dictionary<WeakReference, int> _weakCounter = new Dictionary<WeakReference,int>();

    // Creates a strong link to Foo instance
    public void ListenToThisFoo(Foo foo)
    {
        _counter[foo] = 0;
        foo.FooEvent += (o, e) => _counter[foo]++;
    }

    // Creates a weak link to Foo instance
    public void ListenToThisFooWeakly(Foo foo)
    {
        WeakReference fooRef = new WeakReference(foo);
        _weakCounter[fooRef] = 0;
        foo.FooEvent += (o, e) => _weakCounter[fooRef]++;
    }

    private void HandleEvent(object sender, EventArgs args, Foo originalfoo)
    {
        Console.WriteLine("Derp");
    }
}
</code>```

So we've got an object that's already a GC root of it's own (well...to be specific, it'll be rooted via a chain straight to the app domain running this application, but that's another topic) that has two methods of latching on to a Foo instance - let's test it out:

```<code>// Our foo
var f = new Foo();

// Create a "hard reference"
NastySingleton.Instance.ListenToThisFoo(f);

// Ok, we're done with this foo
f = null;

// Force collection of all orphaned objects
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
</code>```

Now, from the above, would you expect the object-that-was-once-referred-to by f to be "collectable"?

No, because there is another object now holding a reference to it - the Dictionary in that Singleton static instance.

Ok, let's try the weak approach:

```<code>f = new Foo();
NastySingleton.Instance.ListenToThisFooWeakly(f);

// Ok, we're done with this foo
f = null;

// Force collection of all orphaned objects
// This should collect # 2 - you'll see a "#2 dying"
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
</code>```

Now, when we whack our reference to the-Foo-that-was-once-f, there are no more "hard" references to the object, so it is collectable - the WeakReference created by the weak listener won't prevent that.

Good use cases:

Event handlers (Although read this first: Weak Events in C#)

You've got a situation where you would cause a "recursive reference" (i.e., object A refers to object B, which refers to object A, also referred to as a "Memory Leak") (edit: derp, of course this isn't true)

You want to "broadcast" something to a collection of objects, but you don't want to be the thing keeping them alive; a List<WeakReference> can be maintained easily, and even pruned by removing where ref.Target == null

Title: When to use weak references in .Net?

Body:
Let me put this out first and come back to it:

A WeakReference is useful when you want to keep tabs on an object, but you DO NOT want your observations to prevent that object from being collected

So let's start from the beginning:

--apologies in advance for any unintentional offense, but I'm gonna back up to "Dick and Jane" level for a moment since one can never tell ones audience.

So when you've got an object X - let's specify it as an instance of class Foo - it CANNOT live on it's own (mostly true); In the same way that "No man is an island", there are only a few ways that an object can promoted to Islandhood - although it's called being a GC root in CLR speak. Being a GC Root, or having an established chain of connections/references to a GC root, is basically what determines whether or not Foo x = new Foo() gets garbage collected.

If you cannot walk your way back to some GC root either by heap or stack walking, you are effectively orphaned, and will likely be marked/collected next cycle.

At this point, let's look at some horrible-contrived examples:

First, our Foo:

public class Foo
{
    private static volatile int _ref = 0;
    public event EventHandler FooEvent;
    public Foo()
    {
        _ref++;
        Console.WriteLine("I am #{0}", _ref);
    }
    ~Foo()
    {
        Console.WriteLine("#{0} dying!", _ref--);
    }
}

Fairly simple - it's not thread safe, so don't try that, but keeps a rough "reference count" of active instances and decrements when they are finalized.

Now let's look at a FooConsumer:

public class NastySingleton
{
    // Static member status is one way to "get promoted" to a GC root...
    private static NastySingleton _instance = new NastySingleton();
    public static NastySingleton Instance { get { return _instance;} }

    // testing out "Hard references"
    private Dictionary<Foo, int> _counter = new Dictionary<Foo,int>();
    // testing out "Weak references"
    private Dictionary<WeakReference, int> _weakCounter = new Dictionary<WeakReference,int>();

    // Creates a strong link to Foo instance
    public void ListenToThisFoo(Foo foo)
    {
        _counter[foo] = 0;
        foo.FooEvent += (o, e) => _counter[foo]++;
    }

    // Creates a weak link to Foo instance
    public void ListenToThisFooWeakly(Foo foo)
    {
        WeakReference fooRef = new WeakReference(foo);
        _weakCounter[fooRef] = 0;
        foo.FooEvent += (o, e) => _weakCounter[fooRef]++;
    }

    private void HandleEvent(object sender, EventArgs args, Foo originalfoo)
    {
        Console.WriteLine("Derp");
    }
}

So we've got an object that's already a GC root of it's own (well...to be specific, it'll be rooted via a chain straight to the app domain running this application, but that's another topic) that has two methods of latching on to a Foo instance - let's test it out:

// Our foo
var f = new Foo();

// Create a "hard reference"
NastySingleton.Instance.ListenToThisFoo(f);

// Ok, we're done with this foo
f = null;

// Force collection of all orphaned objects
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();

Now, from the above, would you expect the object-that-was-once-referred-to by f to be "collectable"?

No, because there is another object now holding a reference to it - the Dictionary in that Singleton static instance.

Ok, let's try the weak approach:

f = new Foo();
NastySingleton.Instance.ListenToThisFooWeakly(f);

// Ok, we're done with this foo
f = null;

// Force collection of all orphaned objects
// This should collect # 2 - you'll see a "#2 dying"
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();

Now, when we whack our reference to the-Foo-that-was-once-f, there are no more "hard" references to the object, so it is collectable - the WeakReference created by the weak listener won't prevent that.

Good use cases:

Event handlers (Although read this first: Weak Events in C#)

You've got a situation where you would cause a "recursive reference" (i.e., object A refers to object B, which refers to object A, also referred to as a "Memory Leak") (edit: derp, of course this isn't true)

You want to "broadcast" something to a collection of objects, but you don't want to be the thing keeping them alive; a List<WeakReference> can be maintained easily, and even pruned by removing where ref.Target == null


问:
Should I return from a function early or use an if statement?
I've often written this sort of function in both formats, and I was wondering if one format is preferred over another, and why.

public void SomeFunction(bool someCondition)
{
    if (someCondition)
    {
        // Do Something
    }
}
```

<p>or</p>

<pre class="lang-java prettyprint-override"><code>public void SomeFunction(bool someCondition)
{
    if (!someCondition)
        return;

    // Do Something
}
</code>```

I usually code with the first one since that is the way my brain works while coding, although I think I prefer the 2nd one since it takes care of any error handling right away and I find it easier to read

答:
I agree with the following statement:

I'm personally a fan of guard clauses
  (the second example) as it reduces the
  indenting of the function. Some people
  don't like them because it results in
  multiple return points from the
  function, but I think it's clearer
  with them.

Taken from this question in stackoverflow.


问:
POST/Redirect/GET with invalid form submission?
In the field of web development, is it good practice to do a POST/Redirect/GET when fields in a form submission are invalid, as well?

Typically, no sensitive transaction would have taken place, in this event. However, can an argument be made that, nonetheless, it is still good practice to utilize the POST/Redirect/GET pattern?

答: I would say generally not, on the grounds that when a form is POSTed with invalid fields, what you normally want to serve in response is the same form with the same field population, plus some error messages. This would be onerous to perform via POST/Redirect/GET - how would you ensure that the page returned by the GET already had the user's entries in the form fields?</p>


问:
Best development model for novice game developers
A small group of friends (including myself) decided to develop a simple 2D game. We are all fairly new to software development, so I wanted to ask which software development model would likely work best for such a group. From the list on Wikipedia, the Waterfall and Spiral models seem to be the two best options.

Our plan is to use C# with XNA for development.

答:
If you're new to software development, then the different software development models probably won't make much sense. Although I had studied (in school) and later read books about software development methodologies in the past, it probably took me about two decades (and ending up in a suitable industry) to truly understand what the so-called "Waterfall" process really meant and what information gets transferred between each step.

As a novice programmer, you are going to have to dedicate so much effort to actually developing software, that most of the "process" that you read about will seem like frivolous annoying bookkeeping. Believe me, you're not going to want to worry about cross-referencing the sections in the Software Design Document with the requirement numbers in the Software Requirements Document, when you've just got jumping working but there's a bug when you try to fire at the same time.


问:
Which online/hosted bug tracking tool do you use for your own work and projects?
I've accumulated a lot of side projects over the years, which I slowly improve on over time. Whenever I return to one, I take some time reading over text files that include design, recent bugs, next features, etc... that I should be working on - it's not pretty.

I'm looking to switch to something more formal. Ideally, this would be a full featured, online, bug tracking system, which allows for free or nearly free bug tracking for my own projects. Also, ideally this would be doable in a private manner - I don't really want everyone to see my side projects and what a mess I've made of some of them.

答:
BugHerd

BugHerd is a bug tracker specifically for websites. You embed their JavaScript snippet into your site header and users can start logging bugs on your site. This automatically captures a lot of data with bug reports such as browser version, it optionally allows users to pinpoint a location on the page and it takes a screenshot. So always enough data to troubleshoot the issue without needing to contact the client in a lot of cases.


问:
MVC - Isolating view and model logic
I understand that the model should generally consist of data manipulation and the view for data display from the model, but how do I keep my model and view layers decoupled?

My simple view has a few tables that display data. Its associated model manipulates the data based on the view's type of TableModel. Most of its methods involve using the TableModel type. Should the view generally "breakdown" the data into a more generic type of integers and strings for the model? Therefore all the model handles are simple generic lists of data without needing to use TableModel in case the view is changed into another interface. The model should be "unaware" of the view for good programming practices, right? If I change my view to a command-line interface, the associated model should still be able to perform its functions, given the correct associated Lists of integers/strings/whatever.

答: You're missing a layer.  You need a controller. The controller's job is to take data from the model, whatever your model abstraction might be, and to then use that data to populate the view, do page logic, etc.  MVC is the traditional model/view paradigm. My web application, here, is written in python and takes aadvantage of an MVC framework called Web.py. You can see the way the models and the views are separated by a controller layer, who controls the view.</p>

Title: MVC - Isolating view and model logic


答:
In modern way of working, Github stands out with an excellent way of tracking bugs.You can checkout the feature page to get a hang of it.. Also see this post

Though it's in an upcoming stage, I strongly recommend asana. You may lose certain kind of controls when comparing with legacy bug trakcing systems but they laid right the fundamentals like Projects, tags, assignment, collaboration. see help article here

Title: Which online/hosted bug tracking tool do you use for your own work and projects?

Body:
I've accumulated a lot of side projects over the years, which I slowly improve on over time. Whenever I return to one, I take some time reading over text files that include design, recent bugs, next features, etc... that I should be working on - it's not pretty.

I'm looking to switch to something more formal. Ideally, this would be a full featured, online, bug tracking system, which allows for free or nearly free bug tracking for my own projects. Also, ideally this would be doable in a private manner - I don't really want everyone to see my side projects and what a mess I've made of some of them.


问:
Why should we use externalized property files for an application?
I am currently working on a rails project and have a requirement where I want to be able to map a country name's initial letters to its ISD code. eg: IND => 91, USA => 1, etc.

The broader question here being (notwithstanding which framework you work on), what should be the best practice to store these things.
Should you be using a property file (yaml, in this case)?
OR
Should you just make a table in the database and read it from there?
OR
Should you just have a hash_map like structure in your ruby (or any other language) code?

答:
As you mentioned "any other language", I would've created a utility class in JAVA with a property object containing country names and codes as key,value pairs.

The reason I mentioned a utility class is, it can be used to store other things like these (for example mapping language files with countries for localization stuff, etc). Simply I mean having a utility class with globally required stuff is a better option.

This is just my opinion in JAVA.

ADDED : By using an externalized property file, you just have to add/remove entries in the properties file without having to change your program code. Gives lot of flexibility.


问:
IPv4 to IPv6. where is IPv5?
As all of us know that after IPv4 it came IPv6. How this transition happened?

I just want to know was there any IPv5 also? or there is any other logic in naming this version of IP as IPv6?

答:
According to Wikipedia, Internet Protocol Version 5 was used by the Internet Stream Protocol, an experimental streaming protocol.

The second version (of Internet Stream Protocol), known variously as
  ST-II or ST2, distinguishes its own packets with an Internet Protocol
  version number 5, although it was never known as IPv5.

The Internet Stream Protocol family was never introduced for public
  use, but many of the concepts available in ST are similar to later
  Asynchronous Transfer Mode protocols and can be found in Multiprotocol
  Label Switching (MPLS). They also presaged Voice over IP.

Title: IPv4 to IPv6. where is IPv5?


答:
If you have external property file, you also have the advantage that you can easily look up the configuration and you do not have to start the actual program.

This can be quite handy if you maintain more than one instance of you program and have to look up quickly, how everything is configured.
You can just check the Config-Files and see, if you spot an error there, change some Settings (e.g. a database-connectionstring) etc.

Another advantage is that you can back-up these settings easyily.

Title: Why should we use externalized property files for an application?

Body:
I am currently working on a rails project and have a requirement where I want to be able to map a country name's initial letters to its ISD code. eg: IND => 91, USA => 1, etc.

The broader question here being (notwithstanding which framework you work on), what should be the best practice to store these things.
Should you be using a property file (yaml, in this case)?
OR
Should you just make a table in the database and read it from there?
OR
Should you just have a hash_map like structure in your ruby (or any other language) code?


问:
Test driven development when implementing a flexible length list
According to the commonly used TDD strategy, to implement something, you write a test that fail the code first, write the simplest code, refactor, and then repeat. I am trying to imagine this scenario with implementing a flexible length list (e.g. List<T> in .net.

Let's say I first test by inserting one item. Probably the simplest way to achieve this is by backing the list with an array with length 1 (which will pass the test). Nothing to refactor here, so I'll go ahead and write another test that insert 2 items. I'll simply change the array length to 2, and the test pass again. Then I write test with 3 items, expand the array, and repeat again. I will end up forever doing this until I'm tired.

Is this an exception to the fail-test-first strategy? Or am I missing something in the above strategy?

PS: The actual implementation backs the list with an array which grows twice as large every time the number of elements exceed the array length.

答:
You can use for in tests. I would create one test which inserts one item. And then another test which inserts a random number of items (where count > reallocation size).

I would however never start with an internal array size of 1. There's no point, it's a list, isn't it?


答:
"Write the most simple thing that could possibly work" is one principle, but it is not the only one, and it isn't always the most important one. "Don't repeat yourself" is arguably more important, and repeating yourself the way you describe is definitely not justified by "most simple". As soon as you notice repeating yourself, you should switch to a solution that can handle more than one list length.

Note that this solution may very well still be a fixed-length array if you know that you will not need more than a given number of elements as per the requirements. Alternatively, it might be a dynamic structure that grows with the demands made on it. But in no case is it useful to climb the latter of integers one by one - not least because you can't possibly reach the top.

Title: Test driven development when implementing a flexible length list

Body:
According to the commonly used TDD strategy, to implement something, you write a test that fail the code first, write the simplest code, refactor, and then repeat. I am trying to imagine this scenario with implementing a flexible length list (e.g. List<T> in .net.

Let's say I first test by inserting one item. Probably the simplest way to achieve this is by backing the list with an array with length 1 (which will pass the test). Nothing to refactor here, so I'll go ahead and write another test that insert 2 items. I'll simply change the array length to 2, and the test pass again. Then I write test with 3 items, expand the array, and repeat again. I will end up forever doing this until I'm tired.

Is this an exception to the fail-test-first strategy? Or am I missing something in the above strategy?

PS: The actual implementation backs the list with an array which grows twice as large every time the number of elements exceed the array length.


问:
How to manage a virtual group in a company?
I have worked as a software engineer for more than 6 years. Recently, my boss has asked me to build and manage a virtual team. While I'm glad I can do some management work, I don't think it will be easy to do the management.

My team members are only part-time on this project, they come from several teams, and their direct manager is not me. They want to be given technical work but my boss wants us to organize some activities.

I'm trying to work out how to balance these two conflicting requirements.

Overall, my team manages several parts of an internal BBS which features topics about innovation. Unfortunately, the BBS is not very popular and few colleagues want to spend more than a second on it. They say that they are too busy, but more likely it is an excuse, probably because the BBS is not user-friendly. I don't know why BBS is so important.

However, my boss likes the BBS and want my team to make it better. Personally, I don't know why this BBS is so important.

Overall, I need some guidance about how to approach this.

答:
I don't know why BBS is so important.

Big red flag! If you don't see the point of using a tool, particularly one for bringing together technical experts, then you will almost certainly not be able to convince others to use it. Group-building is about communication, and nothing kills group action faster than the perception that the effort is useless to begin with. To have a chance, you must start out with a vision, a cost-benefit analysis, or something that will make others think "This might be useful to me". If you don't have one, and your managers can't provide one, realistically you can only expect to fail and try to blame the non-invovement on others. Not a nice outlook.


问:
Branches/decision count in an example
Having read SO, just found this question:

```<code>if (x > y)
     print (x)
else if (x < y)
     print (y)
else
     print (x,y)
</code>```

How many branches and decisions are there? It mentiones there should be 3 decision and 5 branches, yet I cannot see how. For me I can only imagine 4 branches (2 Ifs with two possible results).

Original question here

答:
```<code>           if
          /  \    < ---- 2 branches
      false true
      else
       if
      /  \        < ---- 2 branches
   false true
   else
    |             < ---- 5th and final branch
</code>```

as else part gives a decision, it is a branch too

Title: Branches/decision count in an example

Body:
           if
          /  \    < ---- 2 branches
      false true
      else
       if
      /  \        < ---- 2 branches
   false true
   else
    |             < ---- 5th and final branch

as else part gives a decision, it is a branch too