答:
Groovy's implementation of curry does not actually curry at any point, even behind the scenes. It is essentially identical to partial application.

The curry, rcurry and ncurry methods return a CurriedClosure object that holds the bound arguments. It also has a method getUncurriedArguments (misnamed—you curry functions, not arguments) which returns the composition of the arguments passed to it with the bound arguments.

When a closure gets called, it ultimately calls the invokeMethod method of MetaClassImpl, which explicitly checks to see if the calling object is an instance of CurriedClosure. If so, it uses the aforementioned getUncurriedArguments to compose the full array of arguments to apply:

if (objectClass == CurriedClosure.class) {
    // ...
    final Object[] curriedArguments = cc.getUncurriedArguments(arguments);
    // [Ed: Yes, you read that right, curried = uncurried. :) ]
    // ...
    return ownerMetaClass.invokeMethod(owner, methodName, curriedArguments);
}
```

<p>Based on the confusing and somewhat inconsistent nomenclature above, I suspect that whoever wrote this has a good conceptual understanding, but was perhaps a little rushed and—like many smart people—conflated currying with partial application. This is understandable (see Paul King's answer), if a little unfortunate; it will be difficult to correct this without breaking backwards compatibility.</p>

<p>One solution I've suggested is to overload the <code>curry</code> method such that when no arguments are passed it does <strong>real</strong> currying, and deprecate calling the method with arguments in favour of a new <code>partial</code> function. This might seem a little strange, but it would maximise backwards compatibility—since there's no reason to use partial application with zero arguments—while avoiding the (IMHO) uglier situation of having a new, differently-named function for proper currying while the function actually named <code>curry</code> does something different and confusingly similar.</p>

<p>It goes without saying that the result of calling <code>curry</code> is completely different from actual currying. If it really curried the function, you would be able to write:</p>

<pre class="lang-groovy prettyprint-override"><code>def add = { x, y -> x + y }
def addCurried = add.curry()   // should work like { x -> { y -> x + y } }
def add1 = addCurried(1)       // should work like { y -> 1 + y }
assert add1(1) == 2
</code>```

…and it would work, because addCurried should work like { x -> { y -> x + y } }. Instead it throws a runtime exception and you die a little inside.

Title: Does groovy call partial application 'currying'?

Body:
Groovy has a concept that it calls 'currying'.  Here's an example from their wiki:

def divide = { a, b -> a / b }

def halver = divide.rcurry(2)

assert halver(8) == 4

My understanding of what's going on here is that the right hand argument of divide is being bound to the value 2.  This seems like a form of partial application.

The term currying is usually used to mean transforming a function that takes a series of arguments into a function that only takes one argument and returns another function.  For example here is the type of the curry function in Haskell:

curry :: ((a, b) -> c) -> (a -> (b -> c))

For people who haven't used Haskell a, b and c are all generic parameters.  curry takes a function with two arguments, and returns a function that takes a and returns a function from b to c.  I've added an extra pair of brackets to the type to make this more clear.

Have I misunderstood what's going on in the groovy example or is it merely misnamed partial application?  Or does it in fact do both: that is to say convert divide into a curried function and then partially apply 2 to this new function.

Body:
Groovy's implementation of curry does not actually curry at any point, even behind the scenes. It is essentially identical to partial application.

The curry, rcurry and ncurry methods return a CurriedClosure object that holds the bound arguments. It also has a method getUncurriedArguments (misnamed—you curry functions, not arguments) which returns the composition of the arguments passed to it with the bound arguments.

When a closure gets called, it ultimately calls the invokeMethod method of MetaClassImpl, which explicitly checks to see if the calling object is an instance of CurriedClosure. If so, it uses the aforementioned getUncurriedArguments to compose the full array of arguments to apply:

if (objectClass == CurriedClosure.class) {
    // ...
    final Object[] curriedArguments = cc.getUncurriedArguments(arguments);
    // [Ed: Yes, you read that right, curried = uncurried. :) ]
    // ...
    return ownerMetaClass.invokeMethod(owner, methodName, curriedArguments);
}

Based on the confusing and somewhat inconsistent nomenclature above, I suspect that whoever wrote this has a good conceptual understanding, but was perhaps a little rushed and—like many smart people—conflated currying with partial application. This is understandable (see Paul King's answer), if a little unfortunate; it will be difficult to correct this without breaking backwards compatibility.

One solution I've suggested is to overload the curry method such that when no arguments are passed it does real currying, and deprecate calling the method with arguments in favour of a new partial function. This might seem a little strange, but it would maximise backwards compatibility—since there's no reason to use partial application with zero arguments—while avoiding the (IMHO) uglier situation of having a new, differently-named function for proper currying while the function actually named curry does something different and confusingly similar.

It goes without saying that the result of calling curry is completely different from actual currying. If it really curried the function, you would be able to write:

def add = { x, y -> x + y }
def addCurried = add.curry()   // should work like { x -> { y -> x + y } }
def add1 = addCurried(1)       // should work like { y -> 1 + y }
assert add1(1) == 2

…and it would work, because addCurried should work like { x -> { y -> x + y } }. Instead it throws a runtime exception and you die a little inside.


问:
Warn about 3rd party methods that are forbidden
Note: This question refers to code written in Java or C#.

I am managing a couple of large projects where we have discovered issues (not necessarily bugs) with some 3rd party/SDK methods and have written our own extensions that should be used instead. We want developers to remember that using those methods is not recommended for this project.

If we had been using our own libraries we could easily remove that method or mark it obsolete/deprecated but we cannot do so for libraries that we didn't write.

As an example, we use a library that provides us with two overloads:

```<code>acme.calculate(int quantity_, double priceInUsDollars_);
acme.calculate(int quantity_, string currencyCode_, double priceInCurrency_);
</code>```

We want developers to always use the first one and get price in US Dollars from our own standard FX rate systems. And it'd be nice to have the IDE (Eclipse/Visual Studio) warn the developers when they use the first one. A compiler warning will suffice too.

Right now, as it stands, we have to rely on the code reviewers to spot such errors and as you can see that is not a reliable approach.

One possible way I am prepared to go is to write my own check style check (http://checkstyle.sourceforge.net/writingchecks.html). But I was wondering if there was something simple that I could use. Does anyone know of ways to achieve an IDE/compiler warning of the sort I have described?

Non IDE/compiler solutions are most welcome.

答:
Using a tool like NDepend / JavaDepend, you could write custom CQL queries to generate warnings for these very specific cases.

You said in the question you wanted the IDE/Compiler to warn the developers. I think because NDepend/JDepend integrate closely with the IDE this may solve your problem.

ContentLicense: CC BY-SA 3.0


问:
How to hide the python code from users?
I am developing a paid application in python. I do not want the users to see the source code or decompile it. How can I accomplish this task to hiding the source code from the user but running the code perfectly with the same performance.</p>

答:
To a determined user, you can't.

From a practical standpoint, you can do some tricks, such as wrapping it into a binary executable or using obfuscation.

See here for full details: https://stackoverflow.com/questions/261638/how-do-i-protect-python-code

Title: How to hide the python code from users?


问:
C# foreach improvements?
I run into this often during programming where I want to have a loop count index inside of a foreach and have to create an integer, use it, increment, etc. Wouldn't it be a good idea if there was a keyword introduced that was the loop count inside of a foreach? It could also be used in other loops as well.

Does this go against the use of keywords seeing as how the compiler would not allow this keyword used anywhere but in a loop construct?

答:
If the collection in question is an IList<T>, you can simply use for with indexing:

```<code>for (int i = 0; i < collection.Count; i++)
{
    var item = collection[i];
    // …
}
</code>```

If not, then you could use Select(), it has an overload that gives you the index.

If that's also not suitable, I think maintaining that index manually is simple enough, it's just two very short lines of code. Creating a keyword specifically for this would be an overkill.

```<code>int i = 0;
foreach (var item in collection)
{
    // …
    i++;
}
</code>```

Title: C# foreach improvements?

Body:
If the collection in question is an IList<T>, you can simply use for with indexing:

for (int i = 0; i < collection.Count; i++)
{
    var item = collection[i];
    // …
}

If not, then you could use Select(), it has an overload that gives you the index.

If that's also not suitable, I think maintaining that index manually is simple enough, it's just two very short lines of code. Creating a keyword specifically for this would be an overkill.

int i = 0;
foreach (var item in collection)
{
    // …
    i++;
}


问:
For what problems is object oriented programming not a good choice?
Somewhat inspired by this question: For what common problems is functional programming not a good fit? - but nevertheless a question which I always wanted, but was too afraid to ask.

I've been in ... well, let's call it engineering software development practically all my life, and in all that time, although OO had always been there (well, most of that time) I've never had the need to use "its ways", nor to learn that paradigm. We've always used rather simple program structures, routines/functions/modules and although it is opposite to today's best practices managing those programs (programs up to roughly 300k LOC, nothing too big) never proved to be difficult, let alone impossible.

So I wanted to ask you, what would be the sorta problems for which object oriented paradigm would not be a good choice? In comparison to procedural programming ?

答:
I think that when building systems that combine other systems through web apis (rest, xmlprc, plain curl/wget) you can write OO wrappers but it's clearly just a convenience. If the web service to be used is simple, and it's just a matter of one or two lines, then OO is too much. If on the other hand you end up having to wrap a complex web api (like Amazon AWS for example) then it's nice to have a wrapper library (like boto in python for AWS).

Thoughts?

ContentLicense: CC BY-SA 2.5


问:
What is the difference between channel-based I/O and stream-based I/O in java?
What is the difference between stream-based Input and Channel-Based Input? The java API provides both stream-based in "java.io" package and channel-based in "java.nio" package. Which one of the two is better in performance and reduced run-time errors?</p>

答:
See this Oracle blog post for a good overview

Also don't neglect to read up on Java 7's NIO.2 APIs!

In terms of performance etc, well the answer is, "it depends".  It depends on the characteristics of your I/O, e.g. it's size, it's 'shape', whether it's Network or disc or in memory or ....


答:
There's no use in doing that.

If your application is not incredibly small and simple, then even if the client (or other programmers they hired) were to work on that code, they'd still need a lot of your help with it.

If it is incredibly small and simple, don't even bother with it. The client could just get someone to rewrite it from scratch anyway.

Title: How to hide the python code from users?

Body: I am developing a paid application in python. I do not want the users to see the source code or decompile it. How can I accomplish this task to hiding the source code from the user but running the code perfectly with the same performance.</p>


问:
When to write an explicit return statement in Groovy?
At the moment I am working on a Groovy/Grails project (which I'm quite new in) and I wonder whether it is good practice to omit the return keyword in Groovy methods. As far as I know you have to explicitly insert the keyword i.e. for guard clauses, so should one use it also everywhere else? In my opinion the additional return keyword increases readability. Or is it something you just have to get used to? What is your experience with that topic?

Some examples:

```<code>def foo(boolean bar) {
    // Not consistent
    if (bar) {
        return positiveBar()
    }
    negativeBar()
}

def foo2() {
    // Special Grails example
    def entitiy = new Entity(foo: 'Foo', bar: 'Bar')
    entity.save flush: true
    // Looks strange to me this way
    entity
}
</code>```

答:
Clarity is King.

Do what is most clear to the fellow programmer who has to read your code after you write it.


答:
We want developers to remember that using those methods is not
  recommended for this project.

Since you already had to create replacement methods in some cases.  I would create a wrapper class for the entire library and only use your wrapper class.

If the library is updated you would have to update your code anyways.  The wrapper class is easy enough to update.

It avoids developers from using the wrong method although....I dare say that a developer should be able to remember which methods he isn't suppose to use.

Title: Warn about 3rd party methods that are forbidden

Body:
Note: This question refers to code written in Java or C#.

I am managing a couple of large projects where we have discovered issues (not necessarily bugs) with some 3rd party/SDK methods and have written our own extensions that should be used instead. We want developers to remember that using those methods is not recommended for this project.

If we had been using our own libraries we could easily remove that method or mark it obsolete/deprecated but we cannot do so for libraries that we didn't write.

As an example, we use a library that provides us with two overloads:

```<code>acme.calculate(int quantity_, double priceInUsDollars_);
acme.calculate(int quantity_, string currencyCode_, double priceInCurrency_);
</code>```

We want developers to always use the first one and get price in US Dollars from our own standard FX rate systems. And it'd be nice to have the IDE (Eclipse/Visual Studio) warn the developers when they use the first one. A compiler warning will suffice too.

Right now, as it stands, we have to rely on the code reviewers to spot such errors and as you can see that is not a reliable approach.

One possible way I am prepared to go is to write my own check style check (http://checkstyle.sourceforge.net/writingchecks.html). But I was wondering if there was something simple that I could use. Does anyone know of ways to achieve an IDE/compiler warning of the sort I have described?

Non IDE/compiler solutions are most welcome.


问:
Does groovy call partial application 'currying'?
Groovy has a concept that it calls 'currying'.  Here's an example from their wiki:

def divide = { a, b -> a / b }

def halver = divide.rcurry(2)

assert halver(8) == 4

My understanding of what's going on here is that the right hand argument of divide is being bound to the value 2.  This seems like a form of partial application.

The term currying is usually used to mean transforming a function that takes a series of arguments into a function that only takes one argument and returns another function.  For example here is the type of the curry function in Haskell:

curry :: ((a, b) -> c) -> (a -> (b -> c))

For people who haven't used Haskell a, b and c are all generic parameters.  curry takes a function with two arguments, and returns a function that takes a and returns a function from b to c.  I've added an extra pair of brackets to the type to make this more clear.

Have I misunderstood what's going on in the groovy example or is it merely misnamed partial application?  Or does it in fact do both: that is to say convert divide into a curried function and then partially apply 2 to this new function.

答:
I think it is clear that groovy curry is actually partial application when considering functions with more than two arguments. consider

```<code>f :: (a,b,c) -> d
</code>```

its curried form would be

```<code>fcurried :: a -> b -> c -> d
</code>```

however groovy's curry will return something equivalent to (assuming called with 1 argument x)

```<code>fgroovy :: (b,c) -> d
</code>```

which will call f with the value of a fixed to x

i.e. while groovy's curry can return functions with N-1 arguments, curried functions properly only ever have 1 argument, therefore groovy cannot be currying with curry

Body:
I think it is clear that groovy curry is actually partial application when considering functions with more than two arguments. consider

f :: (a,b,c) -> d

its curried form would be

fcurried :: a -> b -> c -> d

however groovy's curry will return something equivalent to (assuming called with 1 argument x)

fgroovy :: (b,c) -> d

which will call f with the value of a fixed to x

i.e. while groovy's curry can return functions with N-1 arguments, curried functions properly only ever have 1 argument, therefore groovy cannot be currying with curry


问:
Is it advisable to disable the Microsoft enforced coding standards in VC# 2010?
Coming from eclipse I've developed my own coding standards which I got used to. In Visual C# 2010 however, it appears that some coding standards that MS recommends are enforced in the default configuration.

E.g.: I'm used to write conditional statements like this:

```<code>if (somecondition) {
    return true;
} else {
    return false;
}
</code>```

But the braces are forced to a newline in visual c#. Is it recommended to use that standard ?

答: I don't think it really matters as long as your code is clear and consistent. I think the latter is really the driving force behind your concern. I am a huge ReSharper fan and I work with code from many different developers; however, I often can't stand the way they format their code. Using my ReSharper scheme I can format it the way I like and when I'm done I can put it back the way it was before. I don't really think it matters so much in terms of formatting because everyone has their own preference. I will say that I think naming conventions should be adhered to more strictly than formatting style.</p>

OwnerDisplayName: Max


问:
Is BDD actually writable by non-programmers?
Behavior-Driven Development with its emblematic “Given-When-Then” scenarios syntax has lately been quite hyped for its possible uses as a boundary object for software functionality assessment.

I definitely agree that Gherkin, or whichever feature definition script you prefer, is a business-readable DSL, and already provides value as such.

However, I disagree that it is writable by non-programmers (as does Martin Fowler).

Does anyone have accounts of scenarios being written by non-programmers, then instrumented by developers?

If there is indeed a consensus on the lack of writability, then would you see a problem with a tool that, instead of starting with the scenarios and instrumenting them, would generate business-readable scenarios from the actual tests?

Update: regarding the “scenario-generator” tool, it would of course not guess business language magically  ;)  But, just like we currently use regexp matchers to create tests in a top-down approach (on the abstraction dimension), we could use string builders to create scenarios in a bottom-up approach.

A “to give an idea only” example:

```<code>Given I am on page ${test.currentPage.name}
And I click on element ${test.currentAction.element}
…
</code>```

答:
I've seen developers write scenarios; testers write scenarios and even a product owner write scenarios. I've also had conversations explicitly designed to bring out scenarios - "Given <this other context>, when  what should happen then?" - and written down the words the business use.

The best results I've had were from having a conversation with the product owner while he was in the office, capturing them on a wiki then sending them to him so he could correct and add more. He found a couple we'd missed in our conversations. That rocked.

The worst scenarios I've seen are the ones developers wrote themselves without any conversation with the business. I can tell because they use terms like "When I perform a search", or "When I submit the form with a date of today + 3". They're usually not very interesting scenarios, far too many of them, too low a level of detail and therefore completely unmaintainable. The business also don't read these.

Much better to focus on the conversations IMO. I've seen a few teams do this now for a couple of months with huge improvements to quality, irrespective of the automation. One team managed to get automation working in a very difficult environment some weeks later, much to the joy of the tester! But really, as long as the team are having the conversations and using scenarios to draw out other scenarios, I don't think it matters who writes them down.


问:
When to favor ASP.NET WebForms over MVC
I know that Microsoft has said

ASP.NET MVC is not a replacement for WebForms.

And some developers say WebForms is faster to develop on than MVC.  But I believe speed of coding comes down to comfort level with the technology so I don't want any answers in that vein.

Given that ASP.NET MVC gives a developer more control over their application, why isn't WebForms considered obsolete?  Alternatively, when should I favor WebForms over MVC for new development?

答:
I am a complete and total convert to ASP.NET MVC and have not looked back, that said I do still have to maintain several very large WebForms apps. Here's my take on it:

WebForms

Use these when you have some serious heavy lifting to do with grids. The grid controls are really very nice when you have a simple dataset that fits nicely in a tabular format and you want to provide a simple way for users to update records. Yes, I know that MVC 4 has a really snazzy Ajax list-type thing that you can use which works great but, in our business we often need to get something running yesterday and good old-fashioned grids work great and users are happy to be able to tab across a grid with glee. For me that's really the best thing about WebForms for me; but, as Ryan pointed out WebForms can be a big time mess because you're playing both sides of the fence from a nifty code-behind file. It can be both a rose and a thorn at the same time to keep all of your controller-type stuff intermixed with your view(s).

MVC

Use this when you really want to roll your own and you have the opportunity to start an application from scratch. Having a clearly defined MVC application is a bit more work to get started with but its benefits in maintainability outweigh the initial setup cost. If you want to do interesting Ajax interactions, prefer to write your model with code, like clean url's and routes, and be able to control the entire flow of your app then this is definitely the way to go. It takes some getting used to at first but I think it's the better option for greenfield apps.

In conclusion, for me, it comes down to grids and !grids. :)

Title: When to favor ASP.NET WebForms over MVC


问:
When/why is it easier to beg forgiveness than ask permission?
The saying "It's easier to beg forgiveness than ask permission" seems pretty popular among programmers and IIRC was attributed to Grace Hopper.  In what situations is this typically true, and why do you believe that such a counterintuitive proposition would hold?</p>

答:
I think that one important reason is responsibility. By asking for permission, you are transfering the responsibility to the person you are asking, so that person might be inclined to deny just to avoid being held responsible for the result, in case of failure.

On the other hand, once it's done, that's no longer a problem. Even if the result was a failure, it's still your responsibility, no matter if you get forgiveness or not.


问:
Should you exercise TDD on prototype applications?
I'm developing an iOS app, which is a prototype for a customer. They're expecting it to not be of production standard and are happy for a few rough edges here and there.

Since this is my first commercial venture into iOS / Objective C (I'm an android developer that is trying to cross-train into iOS), my primary focus has been learning the Objective C language and how to develop the app, and I have not invested any time into learning how TDD can be applied in this environment.

My question is, even for prototypes, should you still try to apply TDD and create unit tests?

答:
A prototype's scope should touch some key features which are implemented in a correct way. Since you will be demoing the prototype, having these features well tested seems to me to be a good idea.

But of primary concern is whether you believe TDD will actually accelerate your development. It is my opinion that having a high develop-test cycle frequency driven by TDD will accelerate any project, regardless of size or scope. Perhaps projects with a limited scope will actually benefit more, since it is easier to write tests for them.


答:
The "correct" answer is yes. TDD should be considered "best practice" wherever the tools for TDD are available either in the language or in the framework. Even if they aren't available in a form you may be used to with Java or .NET, you can create a simple program that consists of calling each of the unit test methods one at a time, catching thrown exceptions (which indicate a test failure).

The reason why is that cheap, inexpensive little in-house prototype apps, built as proof-of-concepts or for training/demo/personal use purposes, become production apps all the time. Just as an example, I had at one point a job duty to create bootable flash drives for our field techs, containing system tools and OS images. After doing it manually the first time for a batch of 50, I created a simple app, ThumbPrinter (being clever), that automated a large portion of the script-running and batch-tracking, and all I had to do was tell it how many thumb drives I wanted made, where the data to put on them was, and which drive letters would be used during the batch, and then handle the plugging in and unplugging of flash drives as it went.

That app is now used by others in my department and I'm constantly called on to "fix" things that were never a problem when I just used the program myself, because unlike in a production environment, I knew how I'd use it and never considered using it in any different way, and I also knew the causes of certain glitches and how to avoid them because that was easier than making the code work right. If I'd known the app would be used by anyone else I'd probably have taken more care building it, up to and including TDDing it.

Now, that being said, TDD is not necessarily the end-all be-all of proper software development. We got along for 3-plus decades before it was ever proposed, and people still write correct code without unit tests. So, it's really up to you; you'll have to find out just how easy it will or won't be to write and run unit tests for an iOS app, and whether that cost of time and effort is worth the advantages of TDD (regression prevention, YAGNI adherence, definition of "done" and automated proof of correctness).

Title: Should you exercise TDD on prototype applications?

Body:
I'm developing an iOS app, which is a prototype for a customer. They're expecting it to not be of production standard and are happy for a few rough edges here and there.

Since this is my first commercial venture into iOS / Objective C (I'm an android developer that is trying to cross-train into iOS), my primary focus has been learning the Objective C language and how to develop the app, and I have not invested any time into learning how TDD can be applied in this environment.

My question is, even for prototypes, should you still try to apply TDD and create unit tests?


答:
If you use TDD, then yes, you should use it even for prototypes. There's a couple of reasons for this:

First off, testing small bits of your code makes it easier (as always) to get the whole thing right. When you are just learning the language you are more likely to make crazy mistakes, and working with smaller pieces of code helps.

Second, prototypes have a way of mutating into production apps like you wouldn't believe. It'll be a lot easier to do that if you've already got a body of test code.

Downsides are that you not only have to figure out how to write an iOS app, you ALSO have to figure out how to write test code for an iOS app, which is two problems instead of just one. But remember that having all those tests is going to be a boon down the line when you're asked to turn the thing into the real deal on the double-quick.


问:
Passing class names or objects?
I have a switch statement

```<code>    switch ( $id ) {
        case 'abc':    return 'Animal';
        case 'xyz':    return 'Human';
                    //many more
                    }
</code>```

I am returning class names,and use them to call some of their static functions using call_user_func().
Instead I can also create a object of that class, return that and then call the static function from that object as $object::method($param)

```<code>    switch ( $id ) {
        case 'abc':    return new Animal;
        case 'xyz':    return new Human;
                    //many more
                    }
</code>```

Which way is efficient?
To make this question broader : I have classes that have mostly all static methods right now, putting them into classes is kind of a grouping idea here (for example the DB table structure of Animal is given by class Animal and so for Human class). I need to access many functions from these classes so the switch needs to give me access to the class

答: Obviously, needlessly calling a constructor for the sole reason of calling a static method is less efficient. Apparently there is some kind of meta-class encapsulating the static behavior of Animal/Human or perhaps the static method has the wrong location. The situation reeks of a modelling/design error, but there isn't enough context to determine which.</p>

Title: Passing class names or objects?


答:
If all you know is that the collection is an IEnumerable, but need to keep track of how many elements you have processed so far (and thus the total when you're done), you can add a couple lines to a basic for loop:

```<code>var coll = GetMyCollectionAsAnIEnumerable();
var idx = 0;
for(var e = coll.GetEnumerator(); e.MoveNext(); idx++)
{
   var elem = e.Current;

   //use elem and idx as you please
}
</code>```

You can also add an incremented index variable to a foreach:

```<code>var i=0;
foreach(var elem in coll)
{
   //do your thing, then...
   i++;
}
</code>```

If you want to make this look more elegant, you can define an extension method or two to "hide" these details:

```<code>public static void ForEach<T>(this IEnumerable<T> input, Action<T> action)
{
    foreach(T elem in input)
        action(elem);
}

public static void ForEach<T>(this IEnumerable<T> input, Action<T, int> action)
{
    var idx = 0;
    foreach(T elem in input)
        action(elem, idx++); //post-increment happens after parameter-passing
}

//usage of the index-supporting method
coll.ForEach((e, i)=>Console.WriteLine("Element " + (i+1) + ": " + e.ToString()));
</code>```

Title: C# foreach improvements?

Body:
I run into this often during programming where I want to have a loop count index inside of a foreach and have to create an integer, use it, increment, etc. Wouldn't it be a good idea if there was a keyword introduced that was the loop count inside of a foreach? It could also be used in other loops as well.

Does this go against the use of keywords seeing as how the compiler would not allow this keyword used anywhere but in a loop construct?

Body:
If all you know is that the collection is an IEnumerable, but need to keep track of how many elements you have processed so far (and thus the total when you're done), you can add a couple lines to a basic for loop:

var coll = GetMyCollectionAsAnIEnumerable();
var idx = 0;
for(var e = coll.GetEnumerator(); e.MoveNext(); idx++)
{
   var elem = e.Current;

   //use elem and idx as you please
}

You can also add an incremented index variable to a foreach:

var i=0;
foreach(var elem in coll)
{
   //do your thing, then...
   i++;
}

If you want to make this look more elegant, you can define an extension method or two to "hide" these details:

public static void ForEach<T>(this IEnumerable<T> input, Action<T> action)
{
    foreach(T elem in input)
        action(elem);
}

public static void ForEach<T>(this IEnumerable<T> input, Action<T, int> action)
{
    var idx = 0;
    foreach(T elem in input)
        action(elem, idx++); //post-increment happens after parameter-passing
}

//usage of the index-supporting method
coll.ForEach((e, i)=>Console.WriteLine("Element " + (i+1) + ": " + e.ToString()));


答:
Definitely go with the static-calling route. Constructing an object for the sole purpose of calling a static method on it is wasteful, but since you've decided to use PHP, you shouldn't be worrying about optimization on this level anyway. What you should worry about is side effects - there is no rule in PHP that says a constructor can't have any side effects, and if it does, it can bite you badly. For example, you might construct an object, and the constructor happens to output stuff to the client, and then you try to redirect, but header() fails because you've already sent output.

As an even better solution, see if you can come up with a proper design. I can see two sane routes you could take here:

a) Wrap each of the static methods you want to call in a free function, and pass that (as of PHP 5.3, you can use anonymous functions for this, which, BTW, also provide a neat way of controlling variable scope beyond the normal two-level rules).

b) Wrap each of the static methods in a non-static method of a class that implements a common interface defining this method; return instances by interface, and call the interface method. This is essentially your basic factory pattern with behavior classes.

Title: Passing class names or objects?

Body:
I have a switch statement

```<code>    switch ( $id ) {
        case 'abc':    return 'Animal';
        case 'xyz':    return 'Human';
                    //many more
                    }
</code>```

I am returning class names,and use them to call some of their static functions using call_user_func().
Instead I can also create a object of that class, return that and then call the static function from that object as $object::method($param)

```<code>    switch ( $id ) {
        case 'abc':    return new Animal;
        case 'xyz':    return new Human;
                    //many more
                    }
</code>```

Which way is efficient?
To make this question broader : I have classes that have mostly all static methods right now, putting them into classes is kind of a grouping idea here (for example the DB table structure of Animal is given by class Animal and so for Human class). I need to access many functions from these classes so the switch needs to give me access to the class


问:
What traits do the best managers you've worked for have in common?
I have been listening to Scott Hanselman and Rob Conery's podcast, This Developer's Life.

In the latest episode, they discuss personality traits:

1.0.4 - Being Mean.

What makes people mean in our
  industry? What about aggressive?
  Confident? What's the difference?
  Would you rather have a drill sergeant
  for a boss, or a zen master? We talk
  to Cyra Richardson and Giles Bowkett.

It got me thinking, what traits did the best managers you've worked for have in common?

EDIT: Just to clarify, as there have been a few close votes, I'm interested in whether there are traits common to managers of developers that are not necessarily those traits that a manager of some other profession requires.

As for whether this is programming related or not, well I don't want to ask this question on a site that isn't about programming because, frankly, I'm not as interested in what people who make cans of soup for a living want from their managers as I am interested in what developers want from their managers.

答:
Two things:

1)  Is (or fairly recently was) a developer him/her self.

  2)  Manages upwards as well as downwards.

Point 1 will give you, as a developer, a manager who truly understands what your job is and consists of, and understands what you need (and also don't need) to do your job to the best of your abilities.  If they're not a developer now (and they really shouldn't actually be a hands-on developer now as they're a manager - and that's a full time job itself) they should have previous development experience, but that should be fairly recently (ie. in the last few years) so that they're at least familiar with modern development languages, tools, methods and techniques.

Point 2 will give you a manager who accepts his responsibilities, shields his team from the office politics and needless distractions and fights for his team to be provided with the things they need (thus enabling Point 1) and can manage expectation from the business and those above him (This is even more important in a large corporation where many levels and layers of management exist between you (the developer) and the business decision makers (senior management)).

In a nutshell, having trait (1) gives you a manager who understands what you need to get your job done, and having trait (2) gives you a manager who will provide what you need.

Joel Spolsky's Talk at Yale (and the related "Command and Conquer and the Herd Of Coconuts" article) puts it very succinctly:

In talking about the (bad) management at Juno:

"The assumption there was that
  managers exist to tell people what to
  do."

In talking about the (generally good) management at Microsoft:

"Managers exist to get furniture out
  of the way so the real talent can do
  brilliant work."


答:
can you do factory methods in PHP?

```<code>Interfrace IMethodsINeedToCall()
    Method1INeed();
    Method2INeed();

and your Animal / Human classes implement the interface:

Class Animal:IMethodsINeedToCall
    ...implement methods

Class Human:IMethodsINeedToCall
    ...implement methods

IMethodsINeedToCall animalResults = CallSwitchStatementAndRetrunObject('animal');

animalResults.Method1INeed();
animalResults.Method2INeed();

IMethodsINeedToCall humanResults = CallSwitchStatementAndRetrunObject('human');

humanResults.Method1INeed();
humanResults.Method2INeed();
</code>```

not sure if PHP supports that methodology... I"m sure it does to some extent, but seems like a clean approach.

Title: Passing class names or objects?

Body:
can you do factory methods in PHP?

Interfrace IMethodsINeedToCall()
    Method1INeed();
    Method2INeed();

and your Animal / Human classes implement the interface:

Class Animal:IMethodsINeedToCall
    ...implement methods

Class Human:IMethodsINeedToCall
    ...implement methods

IMethodsINeedToCall animalResults = CallSwitchStatementAndRetrunObject('animal');

animalResults.Method1INeed();
animalResults.Method2INeed();

IMethodsINeedToCall humanResults = CallSwitchStatementAndRetrunObject('human');

humanResults.Method1INeed();
humanResults.Method2INeed();

not sure if PHP supports that methodology... I"m sure it does to some extent, but seems like a clean approach.


问:
All unit tests in one executable, or split them up?
When writing tests for one piece of software, say a library, do you prefer to compile all unit tests into one, or separate them into several executables?

The reason I'm asking is because I am currently using CUnit to test a library I'm working on. The tests are split up into separate suites that are compiled into one executable complete with printed output for failures. Now, the build system for that library is CMake (which, despite its name, has little to do with CUnit), which comes with its own testing framework, CTest. CTest allows me to register a list of executables that serve as tests.

I'm pondering whether to use CTest for automated testing runs. However, this would require me to split up the tests I've written so far into separate compile targets. Otherwise, I can't really utilize some of CTests advanced features, such as selectively running tests.

I realize this is more a question of what tools to use and their handling and conventions, but apart from that, are there any other reasons to prefer a single test executable over separate ones? Or vice versa?

答:
I like to have my automated tests in individual binaries, or at least clumped per "belongs-together" group, and then call them from a simple shell script (where a non-zero exit code signals failure, and output on stderr may be captured to record an explanation). This way, I retain full flexibility on the testing - I can run individual tests directly from the command line, I can make all sorts of fancy scripts if I want to, I can reorder them as I see fit without recompiling anything, etc.

But more importantly, it also allows me to include tests written in different languages or using different toolchains in the same run. For example, the unit tests I write are most likely in the project's main language, and running them is a matter of building and invoking the binaries; but I also want to test my database, and I might want to feed SQL scripts directly to the database for this; I might want to run some static code analysis tool on my code (even if it's just some sort of linter). I may want to run my static HTML through a validity checker. I could run a grep command over the codebase to check for suspicious constructs, coding style violations, or "red-flag" keywords. The possibilities are endless - if it can be run from the command line and adheres to "zero exit status means OK", I can use it.


答:
I tend to have one library for the unit tests of one application (or for a package of libraries that is commonly shared). Within that library, I try to replicate or approximate the namespaces of the objects under test for the test fixtures (I use NUnit mostly). This simplifies compilation, as in .NET there is an overhead inherent in building each binary that would increase the build time of a 20-project solution over that of a 10-project solution with the same LOC. Test binaries aren't distributed anyway, so any organization of the tests into binaries is for your own convenience, and I generally find that YAGNI applies here as anywhere.

Now, I usually don't have the considerations that tdammers has; my code is virtually all in one language, and any test involving SQL strings is not a unit test (unless you're testing that a query-producer returns the expected SQL string given certain criteria), and I virtually never unit-test the actual UI (in many situations it's simply impossible). I also use a unit-testing library that is well-accepted by third-party tools such as build-bots and IDE plugins, and so any concerns of running individual tests, partial suites etc are minimal.

Title: All unit tests in one executable, or split them up?

Body:
When writing tests for one piece of software, say a library, do you prefer to compile all unit tests into one, or separate them into several executables?

The reason I'm asking is because I am currently using CUnit to test a library I'm working on. The tests are split up into separate suites that are compiled into one executable complete with printed output for failures. Now, the build system for that library is CMake (which, despite its name, has little to do with CUnit), which comes with its own testing framework, CTest. CTest allows me to register a list of executables that serve as tests.

I'm pondering whether to use CTest for automated testing runs. However, this would require me to split up the tests I've written so far into separate compile targets. Otherwise, I can't really utilize some of CTests advanced features, such as selectively running tests.

I realize this is more a question of what tools to use and their handling and conventions, but apart from that, are there any other reasons to prefer a single test executable over separate ones? Or vice versa?


问:
Passing compound object for parameters
I have different data modules, which take a couple of parameters from a configuration list. Do you think it's ok to pass a configuration object as a whole module1(config) and let the module pick what it needs, or should I rather pass the individual parameters module1(config.a, config.c, config.f)?
The first case doesn't require change interfaces in case I need more configuration parameters, but the second case encapsules more?

答:
The parameter object pattern is widely used in .NET and other object oriented frameworks.

This is essentially what you are describing what talking about passing in a single object and is considered a good practice, so long as the individual parameters have good defaults (so the modules will work even when only some of the parameters are passed in).

If your modules don't have a use for all items in the configuration object I would call this a code smell, however. If they are not needed, why pass them in? The configuration object should match the needs of the module.

Title: Passing compound object for parameters


答:
Kent Beck would say no, but based on other things he's written I would say that the caveat
 there is that you need to throw away that code.  If you aren't the person who decides what to do with your code, then you should probably write tests all the time.</p>


问:
How to talk to management about using integrated project management/bug tracking
Background: I have just started at a new shop, where there is one other developer.  This shop was not historically a software shop, and their software development process really shows it.  They recently started using subversion (although most of the code is not in a repository), and they do not have a bug tracker.  They sell desktop software, and more recently mobile GPS devices with proprietary software.  This seems pretty unsustainable.

My problem: My manager seems amenable to installing Trac and integrating it with subversion.  He's asked me to write a proposal for the company owners about it to justify why I might spend my valuable time fiddling with a Trac installation, and why we might change the development process to include formal bug reports and feature requests.

I have been trying to come up with reasons that matter to people other than me (e.g., not: "So I can see the whole story about why someone wrote this now-buggy code.") and sort of falling flat.  I'm not a manager, and I don't know a lot about managing things.  I just want to avoid the headaches attendant with coding in the wild west.

My Question: How do I (politely) tell managers that it's in their best interest to use Trac?

答:
What kind of "issue tracking system" are you using right now? Emails, PostIt notes, memory, none at all? In either case, a proper system will probably save some of your time, and by extension, your managers' money, in the long run. If you have some form of customer support or even a tester or two, a central tracking system will also cut down the necessary communication overhead between them and you.

Another point is accountability. Not in the sense of playing the blame game of who messed up, but once an issue is added to the tracker, it's much harder to forget than an email you got a month ago. And don't forget the possibility of time tracking. I'm not sure if trac can do this out of the box (if not, there's probably a plugin for it), but if you can attach work hours to an issue, this data will someday help you make more accurate estimations for future features. Which, in turn, will allow your managers to better plan their release schedule.


问:
A programmer should concentrate on at least how many languages?
For me I am C# and Java person. I find these 2 languages are quite similar so its easier for me to crossover each other. I'm not sure if its good idea to pick up other different languages. Any thoughts?</p>

答: It is good to learn one new programming language each year. But rather than learning something similar to what you already know, I will advise you to learn something radically different like Scala or F#. It will show you new ways to do things and eventually enrich your programming skills.</p>


问:
Considerations for accepting contributed code to an Open Source project
I’m working on a "for fun" project in my spare time. I may end up making it Open Source and this makes me wonder what I need to think about if someone cares enough to contribute to it.

Do I need to have some sort of legal mumbo jumbo about “if you give
me yer code, it accepts the same license as the project, bla bla bla”
(what is the norm here?)

Is there a way to check contributed code to
make sure it is not plagiarized or would that liability fall on the
contributer?

Are there any other gotchas, standard/common practices I
should follow, recommendations, things I need to think about?

答:
I am not a lawyer and this is not legal advice.

Do I need to have some sort of legal mumbo jumbo about “if you give me yer code, it accepts the same license as the project, bla bla bla” (what is the norm here?)

I've contributed to a dozen open source projects, and have only once been asked about such things. In that specific case, I slapped on an LGPL license which was not acceptable and had to be replaced by GPL + a linking exception.

I think it seems fair to assume that, if someone sends you code for inclusion in your open source project, they intend for it to be licensed under the same terms. If you want to be sure, then put a copyright notice on every file listing all the contributors; new contributors are likely to imitate that when they write new files.

Or just ask them: "hey, you forgot to put a legal notice in file x, is

```<code># Copyright © 2012 J. Random Contributor
# See the file COPYING for details
</code>```

ok?"

Also, if you use the GPL, then

[anyone distributing a modified version] must license the entire work, as a whole, under this License to anyone who comes into possession of a copy

so that seems pretty much covered.

Is there a way to check contributed code to make sure it is not plagiarized or would that liability fall on the contributer?

You can make a good faith effort for large contributions. There used to be Google Code Search for open source, but that's down now. You can still search for code on GitHub and other popular places to share code. As for software for which you can't see the source code, it's hard to tell when something has been plagiarized. A contributor not understanding "their own" code may be a sign, in which case you probably shouldn't accept it anyway.

If the contributor did violate somebody else's copyright, though, you may be obliged to take action to remove the code in future versions and keep your users from using versions containing the stolen code.

Are there any other gotchas, standard/common practices I should follow, recommendations, things I need to think about?

Read whatever license you use, and make sure you understand it. You don't need to become a lawyer, but be aware of things like license compatibility that may hamper your program's usefulness, esp. when it's designed to operate in conjunction with other software. Decide whether or not you want copyleft to apply.

If you actually want people to contribute, make it easy. I personally like GitHub a lot since it makes forking and contributing extremely easy.

Body:
I am not a lawyer and this is not legal advice.

Do I need to have some sort of legal mumbo jumbo about “if you give me yer code, it accepts the same license as the project, bla bla bla” (what is the norm here?)

I've contributed to a dozen open source projects, and have only once been asked about such things. In that specific case, I slapped on an LGPL license which was not acceptable and had to be replaced by GPL + a linking exception.

I think it seems fair to assume that, if someone sends you code for inclusion in your open source project, they intend for it to be licensed under the same terms. If you want to be sure, then put a copyright notice on every file listing all the contributors; new contributors are likely to imitate that when they write new files.

Or just ask them: "hey, you forgot to put a legal notice in file x, is

# Copyright © 2012 J. Random Contributor
# See the file COPYING for details

ok?"

Also, if you use the GPL, then

[anyone distributing a modified version] must license the entire work, as a whole, under this License to anyone who comes into possession of a copy

so that seems pretty much covered.

Is there a way to check contributed code to make sure it is not plagiarized or would that liability fall on the contributer?

You can make a good faith effort for large contributions. There used to be Google Code Search for open source, but that's down now. You can still search for code on GitHub and other popular places to share code. As for software for which you can't see the source code, it's hard to tell when something has been plagiarized. A contributor not understanding "their own" code may be a sign, in which case you probably shouldn't accept it anyway.

If the contributor did violate somebody else's copyright, though, you may be obliged to take action to remove the code in future versions and keep your users from using versions containing the stolen code.

Are there any other gotchas, standard/common practices I should follow, recommendations, things I need to think about?

Read whatever license you use, and make sure you understand it. You don't need to become a lawyer, but be aware of things like license compatibility that may hamper your program's usefulness, esp. when it's designed to operate in conjunction with other software. Decide whether or not you want copyleft to apply.

If you actually want people to contribute, make it easy. I personally like GitHub a lot since it makes forking and contributing extremely easy.


答:
I've found it easier to make Configuration objects static.  That way, you don't have to pass them around.

The assumption behind static is that you have a single configuration for each process.  For me, so far, that assumption holds.

Title: Passing compound object for parameters

Body:
I have different data modules, which take a couple of parameters from a configuration list. Do you think it's ok to pass a configuration object as a whole module1(config) and let the module pick what it needs, or should I rather pass the individual parameters module1(config.a, config.c, config.f)?
The first case doesn't require change interfaces in case I need more configuration parameters, but the second case encapsules more?


问:
Is automatically checking code quality via metrics possible?
For several years now I am a big fan of using static code analysis tools for checking the source code quality. We are mostly doing C# development so NDepend was the best way to go for me. Most of the time I manually perform the analysis, for example once every two weeks.

Lately I have had a discussion with a colleague whether we should include NDepend in our continuous integration process so that the build automatically turns red if for example a method has a too high complexity.

My opinion hereby is that it's not possible to define metrics that are valid for the whole code. I think that you would either get way to many "false complaints" - code that generally is ok but does not match the metrics. The following code for example has a very high complexity, even if I think that sometimes you can't prevent it.

```<code>if (remoteResult == RemoteResult.Dummy1 || remoteResult == RemoteResult.Dummy2 ||
    remoteResult == RemoteResult.Dummy3 || remoteResult == RemoteResult.Dummy4 || ...
</code>```

Of course it would also work to increase the thresholds of the metrics, but in this case I would loose valuable information.

Another example for example is the maximum number of members for a class. I would like to keep this lower than 10 for classes with lots of logic. But on the other hand there are many "domain models" with more than 10 properties. I wouldn't  like to extract another class just because of the metric - as this would lower the readability and does not improve it which should be the goal of code quality metrics.

Do you think automatically checking code quality via metrics is possible? If yes, for all or only for specific metrics? (A list of common NDepend metrics can be found at http://www.ndepend.com/Metrics.aspx )

答:
I think that it's certainly possible.

However: it should never break the build.

I don't know of software that integrates with CI out of the gate for this type of static analysis (the way that FxCop does), however, I think they can/should be raised as warnings that should flag those areas for code reviews. Upon review, those warnings can be suppressed if code review appoves the code. Similar to how FxCop and StyleCop have suppressions in the source/globalsuppressions.

In summary: these metrics are better as code smells, not code errors.


答:
Metric only aren't enough, but can provide great informations about the code. Just like every metrics, they have to be interpreted to have meaning.

Consider a table which is 2 meters long. Is is too much ? Not enough ? Actually, it depends on what you want to do with the table.

As well, you expect most of your code to have a low cyclomatic complexity, but it is expected that algorithms have a bigger one than regular code. So depending on the code, what is a good and a bad value can change.

As metric, you should look at :

NPATH (measure the logic complexity of a piece of code).

CRAP (a metric that combine cyclomatic complexity with code coverage to tell you how risky it is to change a given piece of code).

Data abstract coupling, fan in and out (to have an idea of the quality of the isolation within an application).

Some problem will not be revealed by any metrics I know of. For instance, temporal coupling. Metric cannot be a substitute for code review, or any quality process you have in the company. This is, however, a great addition and can help in the task.

By the way, Sonar provide what you need to automate code metrics measurement and make report. Check it out : http://www.sonarsource.org/

Title: Is automatically checking code quality via metrics possible?

Body:
For several years now I am a big fan of using static code analysis tools for checking the source code quality. We are mostly doing C# development so NDepend was the best way to go for me. Most of the time I manually perform the analysis, for example once every two weeks.

Lately I have had a discussion with a colleague whether we should include NDepend in our continuous integration process so that the build automatically turns red if for example a method has a too high complexity.

My opinion hereby is that it's not possible to define metrics that are valid for the whole code. I think that you would either get way to many "false complaints" - code that generally is ok but does not match the metrics. The following code for example has a very high complexity, even if I think that sometimes you can't prevent it.

```<code>if (remoteResult == RemoteResult.Dummy1 || remoteResult == RemoteResult.Dummy2 ||
    remoteResult == RemoteResult.Dummy3 || remoteResult == RemoteResult.Dummy4 || ...
</code>```

Of course it would also work to increase the thresholds of the metrics, but in this case I would loose valuable information.

Another example for example is the maximum number of members for a class. I would like to keep this lower than 10 for classes with lots of logic. But on the other hand there are many "domain models" with more than 10 properties. I wouldn't  like to extract another class just because of the metric - as this would lower the readability and does not improve it which should be the goal of code quality metrics.

Do you think automatically checking code quality via metrics is possible? If yes, for all or only for specific metrics? (A list of common NDepend metrics can be found at http://www.ndepend.com/Metrics.aspx )


答:
So you want to write this method Module1, which depends on some subset of the properties of a Configuration object.

Some reasones you might want Module1 to take the Configuration object as a single parameter:

Future versions of Module1 might use additional properties of the Configuration object. This would require changes to every call site if you use individual parameters. (This might not matter too much if Module1 is only exposed internally to your own project, and you have and IDE with strong refactoring features. It matters a lot if it is part of a publicly published API.)

At the places where you want to call Module1, you have a Configuration object available, and it is more convenient to just pass the whole object than to pass in each relevant property.

You might want Module1 to take the relevant properties as individual parameters if:

At the places where you want to call Module1, you don't have a Configuration object available, and you can supply values for the relevant properties but not all the properties. (This is a strong reason if you are confident that future versions will not use more properties.)

So really, it depends on how you expect the method might change in the future, and how much of a burden it is to change call sites if the signature changes.

Title: Passing compound object for parameters


答:
It is definitely impossible to automatically check code quality, you can only check for some minimum code quality.

Even "experienced" programmers are having trouble to formalize what actually constitutes code quality. And even among the "most skilled" ones, there's a high divergence in opinion on what is good or bad.

There are some obvious rules that shouldn't be broken. A thousand lines in a method is definitely too much. A thousand members in a class is also. Nobody would argue on that. Most people would choose for smaller numbers. I personally rarely have a file with more than 200 LOCS, but it largely depends on personal taste, habit and also the programming language used.

The thing is, automatic code analysis tools can only use rather simple criteria. Therefore, not unlike testing, they can never be used to ascertain code quality, only determine horrible lack of it. If there is an absolute way to define code quality, I would think it means a sensible ratio of complexities between a solution and the problem that it solves.

However you do not care for code quality as such and do not seek its absolute value - well, you personally may (I hope you do), but the people who pay you generally don't care. What you really care for is maintainability and ideally a low bus factor.

And this is something relatively subjective, depending a lot on the people in your team. They need to be able to look at a piece of code and understand what it is doing. And that can ultimately only be achieve through code reviews.

So while you can implement automated means to uncover obviously bad code, you cannot implement such means to really assure good code. Only code reviews can do that (or at least drastically help getting towards that goal) and they also definitely protect you from code that is obviously bad.

So it really depends on your team (size, continuity, etc.), whether or not such an automated check makes sense. It might as well save time to do more important things in reviews. Or it might just piss people off to no end. In the long term you should find the discipline to not commit super-obviously-bad code in the first place. It's really not that hard and it really pays off.


答:
You may want to consider using an interface for your parameter itself. Your configuration object will implement the interface, but the interface should include only the properties that you can use on this method.

We call this using role interfaces, and it is an important part of the Interface Segregation Principle. It means that as your configuration object changes, you can choose which properties this particular method is interested in, and add those properties to the interface. No additional refactoring is required. And you still don't have the code smell of getting passed a lot of information you don't need.

Title: Passing compound object for parameters


问:
Why are side-effects considered evil in functional programming?
I feel that side effects are a natural phenomenon. But it is something like taboo in functional languages. What are the reasons?

My question is specific to functional programming style. Not all programming languages/paradigms.

答:
A few notes:

Functions without side effects can trivialy be executed in parallel, while functions with side effects typically require some sort of synchronisation.

Functions without side effects allow for a more aggressive optimization (e.g. by transparentely using an result cache), because as long as we get the right result, it doesn't even matter whether or not the function was really executed


答:
Most managers listen to one thing: money. So try to explain why this will save you time and effort in the future as you use it, and how that compares to the time needed to set it up (hint: graphs).

Also, ask them if they would expect you to do development work without a desk, or computer. The same thing applies with your other tools, you need them to develop (good) software.

Try and nail everything Trac can do down in terms of money, such as reporting costs. If you use Trac, a report costs $0 to produce for them. Otherwise, each report they request is inaccurate, flawed, and requires X hours of your time to produce. Which means that without Trac, a flawed report costs X*Rate, say 3*80=$240 per report!

Title: How to talk to management about using integrated project management/bug tracking

Body:
Background: I have just started at a new shop, where there is one other developer.  This shop was not historically a software shop, and their software development process really shows it.  They recently started using subversion (although most of the code is not in a repository), and they do not have a bug tracker.  They sell desktop software, and more recently mobile GPS devices with proprietary software.  This seems pretty unsustainable.

My problem: My manager seems amenable to installing Trac and integrating it with subversion.  He's asked me to write a proposal for the company owners about it to justify why I might spend my valuable time fiddling with a Trac installation, and why we might change the development process to include formal bug reports and feature requests.

I have been trying to come up with reasons that matter to people other than me (e.g., not: "So I can see the whole story about why someone wrote this now-buggy code.") and sort of falling flat.  I'm not a manager, and I don't know a lot about managing things.  I just want to avoid the headaches attendant with coding in the wild west.

My Question: How do I (politely) tell managers that it's in their best interest to use Trac?


答:
I use static analysis & linting tools as part of my CI and build process, and I find it both helpful and useful. There are drawbacks, but the added confidence that you get in the quality of the code makes it worthwhile, IMHO.

There have been quite a few occasions where the static analysis has rejected functions of mine that I would otherwise have considered quite reasonable; for example, too many variables, or too many input arguments, excessive McCabe complexity etc... However, I have always been able to take a philosophical view, and refactor the code into compliance.

As a result of this approach, I feel a lot more comfortable with my code-base, and can move a lot faster when I need to make changes.

The primary benefits are psychological, and they are significant and meaningful.

(For me, the key to getting it to work well is to use the static analysis tools right from the very beginning, as refactoring legacy code to meet code quality standards is a pain in the backside, whereas continuing development of already-compliant code is much easier).


答:
I was in similar situation once. What happened was:

I simply installed the damn issue tracker. A few hours to figure out and configure it, not a big deal.

Started using it myself. Not everybody was using it yet, but so what: it was helping me already.

Eventually the usage increased, as people recognized that it's actually quite useful.

So it boils down to: with ideas that are relatively easy and cheap to implement, just do it instead of wasting time with politics and proposals. Show, don't tell.


问:
Splitting code from form operations in C#
I have a large (at least for me - approximately 10k lines) project that is written in C#. I have a treeview object on the left of my form and i have many nodes on my treeview. When i click a node, i bring up a panel on the right side of form. Since i only do GUI item operations (filling textboxes, clicking buttons, showing images on pictureboxes etc.), i write all of my code into MainForm class. This seems not very good but on the other side, i think i have to write into MainForm class because all of my job is to evaluate form items on panels. What should i do to write a more portable or understandable code? Do i have to write into MainForm class or do i have some options or methods to implement?</p>

答:
This is something that you will only learn by writing more and more code.  A 10k line file is gigantic, and you probably have a lot of code that can be split out.  The problem is that if you didn't initially approach the problem with plans to separate concerns, things may be so intermingled now that it would require essentially an entire rewrite.

That said, at 10k lines, is the program "complete"?  Or is someone going to be maintaining this?  If this was a small one off utility, then you might be best off to leave as is.  On the other hand, if this is something you need to maintain, you will likely benefit from intense refactoring.

Not knowing your domain makes this difficult, but here are some common forms patterns that might be applicable:

separate the data layer

decompose the form into UserControls to contain pieces of it

create service classes that act as helpers to encapsulate computations


答:
That kind of code would be much easier to handle if, for example, instead of having all the customizing behavior of a treeview in your MainForm, you actually had a class that extended TreeView and made all of the customization there, and your MainForm just used it.

You should do that for every control that exists in your window (or canvas).

Title: Splitting code from form operations in C#

Body: I have a large (at least for me - approximately 10k lines) project that is written in C#. I have a treeview object on the left of my form and i have many nodes on my treeview. When i click a node, i bring up a panel on the right side of form. Since i only do GUI item operations (filling textboxes, clicking buttons, showing images on pictureboxes etc.), i write all of my code into MainForm class. This seems not very good but on the other side, i think i have to write into MainForm class because all of my job is to evaluate form items on panels. What should i do to write a more portable or understandable code? Do i have to write into MainForm class or do i have some options or methods to implement?</p>


答:
GUI classes can quickly grow into a ball of mud if they're not managed carefully.  Simple refactoring will do the trick.  Some tips:

Push everything that's not directly related to the GUI into separate classes.

Refactor as much of the remaining code as possible out of the event handlers into their own methods.

Use #regions to separate the event handlers from the rest of the code, and to break the rest of the code into functional areas.

Encapsulate customized behavior by subclassing controls.


答:
I'd say the most important thing is the ability to learn fast.
That said it's important to know different languages that are used for different purposes.
For example I know:

1) Python and Perl for the scripting languages category

2) C++ as "framework" language

3) Java for mobile application

4) C for the huge amount of legacy code

5) Some obsolete languages I used to know when I was young (Basic, Pascal, Clipper etc)

I'd say that you need at least a main language and a scripting one.
Knowing C# I'd say you need to learn Python or Perl or Ruby next. (I'd go with Python but that's just a matter of preference).

Title: A programmer should concentrate on at least how many languages?

Body: For me I am C# and Java person. I find these 2 languages are quite similar so its easier for me to crossover each other. I'm not sure if its good idea to pick up other different languages. Any thoughts?</p>


答: I guess you do not have only GUI operations (or at least not only operations that must be programmed in this way): your treeview shows some data, and in your panels you have also a lot of data. You may have used (or abused) just GUI items as containers for this, but that's not the way things must (or should) be organized. I suggest start separating the GUI-dependent parts from the data. Then you will most probably identify GUI-independent operations which you can separate from your main form.


答:
Bug/feature tracking is similar to a check register--it lets the business know what they are spending on what, and why they may be running out of resources.

With a checking account, you can spend money and do your best to keep track in your head how much you have in your account, but it's a risky venture.  It's not so bad if you only write one or two checks a month, but if you write 50 or 500, chances are you are going to bounce one some time.  If you keep a register, you'll know when your balance is low, and prioritize your bills over your cool-to-haves.

Likewise, if you only occasionally ask a developer to do something (fix a bug, add a feature), you may be able to judge how much that work is costing the business, and how much time she is spending on doing your work.  The more you ask for, though, the harder it is to judge.  At some point you will start asking for more than the developer(s) can accommodate immediately, so you'll need to keep a backlog of bugs/features (to make sure they get done eventually).  You'll also need to prioritize which features get done first--are the developers wasting time on trivial stuff when there's something critical waiting?  How do you know?  Ultimately, if the backlog gets too big, it lets you know they have to make some deposits and hire are another developer.

So, really, bug tracking IS a management tool that let's management know how it is using the company's resources.


答:
Trying to think of reasons that would persuade a manager, here are a couple of suggestions.

Resource tracking

With a central repository for tasks and bugs it will be much easier for a manager to keep track of where the time (and therefore the money) is spent. Even without time tracking a project management tool should provide a higher level overview of what is going on in terms of product development.

Customer satisfaction

Actually keeping track of issues forces you to address them. Without bug tracking it's easier to postpone tasks or simply forget about them. Following up is key to customer satisfaction.

Priority

Failure to prioritize is a recurring problem many companies suffer under. When you don't keep a list of what you need to get done, it's much harder for you to figure out which task is more important at the moment. People tend to focus on whatever problem falls into their lap, forgetting to stop and think "is this really the most important thing to be working on now?".

Keeping track of issues helps you stay focused on what is important. When everything is equally important, nothing is important. And when you don't work on the most important task, or leave it half done because something else comes along, you are wasting time and money.


问:
EPL-Licensed Library with Closed-Source Commercial Product
The Eclipse Public License is not entirely clear for me.  As I understand it, anyone who redistributes a Library whose code is licensed under the EPL is considered to be a Contributor.  It then states that you are not required to redistribute source-code but you must make mention of where to obtain it.

Other websites have said you do not need to release the source code of your project unless you specifically modify parts of the EPL-licensed program, but from reading the license, it seems to indicate otherwise.

If I would like to use Library X in my Java program where I link the library to my project via the Build Path and then redistribute Library X with my program, am I required to allow the obtaining of the source code or not, "Ask A Lawyer" advice aside.

答:
The EPL license basically says:

The software is authorized to be used with commercial, closed-source applications and derivative works.  It is not copyleft; i.e. it doesn't compel you to release the source code of your closed-source application.

You agree to use and distribute the software in such a way that it limits the liability of all contributors as much as possible.

If you do distribute the source code, you do so in a manner that respects the terms of the Eclipse license, and readily identifies the original contributors. Generally speaking, this means retaining all of the original notices in the source code.


问:
As a software engineer, who should I be following on Twitter?
Who in the software engineering and software development fields uses Twitter to tweet about relevant happenings in the field?</p>

答:
For a quickstart, have a look to this list:

http://twitter.com/jvortmann/software-guru

You got:

Kent Beck

Martin Fowler

Chad Fowler

UncleBob

Erich Gamma
..

I would then search by name, starting from the book authors you are reading.

For example: i'm currently reading Professional Android Application development by Reto Meier; Googling his name + twitter i get his twitter account.


问:
Is 100% code coverage a pipe dream?
Is it feasible to expect 100% code coverage in heavy jquery/backbonejs web applications?  Is it reasonable to fail a sprint due to 100% coverage not being met when actual code coverage hovers around 92%-95% in javascript/jquery? </p>

答:
It is equally realistic as it is unrealistic.

Realistic

If you have automated testing that has been shown to cover the entire code base, then insisting upon 100% coverage is reasonable.

It also depends upon how critical the project is.  The more critical, the more reasonable to expect / demand complete code coverage.

It's easier to do this for smaller to medium sized projects.

Unrealistic

You're starting at 0% coverage ...

The project is monstrous with many, many error paths that are difficult to recreate or trigger.

Management is unwilling to commit / invest to make sure the coverage is there.

I've worked the gamut of projects ranging from no coverage to decent.  Never a project with 100%, but there were certainly times I wished we had closer to 100% coverage.

Ultimately the question is if the existing coverage meets enough of the required cases for the team to be comfortable in shipping the product.

We don't know the impact of a failure on your project, so we can't say if 92% or 95% is enough, or if that 100% is really required.  Or for that matter, the 100% fully tests everything you expect it to.

Title: Is 100% code coverage a pipe dream?


答:
No

In my opinion it's far more trouble than it is worth.  If you have mediocre programmers, they will slavishly refactor their code to satisfy the style cop, making the code even worse.  If you limit the number of class members, you will get something like this:

```<code>class BunchOfStuff {
  public class Bunch1 { // properties with names from A-M
     Integer a { get; set; }
     Double b { get; set; }
     ...
  }
  public class Bunch2 { // N-Z
     ...
  }

  Bunch1 bunch1 { get; }
  Bunch2 bunch2 { get; }
  ...
}
</code>```

I've seen it.  In response to an automated check for 'magic numbers', at least one developer complied thusly:

```<code>private static final int SEVENTEEN = 17;
...
Something[] things = new Something[SEVENTEEN];
</code>```

If you want maintainable code, there is no substitute for good judgment and a second pair of eyes.

Body:
No

In my opinion it's far more trouble than it is worth.  If you have mediocre programmers, they will slavishly refactor their code to satisfy the style cop, making the code even worse.  If you limit the number of class members, you will get something like this:

class BunchOfStuff {
  public class Bunch1 { // properties with names from A-M
     Integer a { get; set; }
     Double b { get; set; }
     ...
  }
  public class Bunch2 { // N-Z
     ...
  }

  Bunch1 bunch1 { get; }
  Bunch2 bunch2 { get; }
  ...
}

I've seen it.  In response to an automated check for 'magic numbers', at least one developer complied thusly:

private static final int SEVENTEEN = 17;
...
Something[] things = new Something[SEVENTEEN];

If you want maintainable code, there is no substitute for good judgment and a second pair of eyes.


问:
Does using GCC specific builtins qualify as incorporation within a project?
I understand that linking to a program licensed under the GPL requires that you release the source of your program under the GPL as well, while the LGPL does not require this. The terminology of the (L)GPL is very clear about this.

```<code>#include "gpl_program.h"
</code>```

means you'd have to license GPL, because you're linking to GPL licensed code. And

```<code>#include "lgpl_program.h"
</code>```

means you're free to license however you want, so that it doesn't explicitly prohibit linking to LGPL source. Now, my question about what isn't clear is:

[begin question]

GCC is GPL licensed, compiling with GCC, does not constitute "integration" into your program, as the GPL puts it; does using builtin functions (which are specific to GCC) constitute "incorporation" even though you haven't explicitly linked to this GPL licensed code? My intuition tells me that this isn't the intention, but legality isn't always intuitive. I'm not actually worried, but I'm curious if this could be considered the case.

[end question]

[begin aside]

The reason for my equivocation is that GCC builtins like __builtin_clzl() or __builtin_expect() are an API technically and could be implemented in another way. For example, many builtins were replicated by LLVM and the argument could be made that it's not implementation specific to GCC. However, many builtins have no parallel and when compiled will link GPL licensed code in GCC and will not compile on other compilers. If you make the argument here that the API could be replicated by another compiler, couldn't you make that identical claim about any program you link to, so long as you don't distribute that source?

I understand that I'm being a legal snake about this, but it strikes me as odd that the GPL isn't more specific. I don't see this as a reasonable ploy for proprietary software creators to bypass the GPL, as they'd have to bundle the GPL software to make it work, removing their plausible deniability. However, isn't it possible that if builtins don't constitute linking, then open source proponents who oppose the GPL could simply write a BSD/MIT/Apache/Apple licensed product that links to a GPL'd program and claim that they intend to write a non-GPL interface that is identical to the GPL one, preserving their BSD license until it's actually compiled?

[end aside]

Sorry for the aside, I didn't think many people would follow why I care about this if I'm not facing any legal trouble or implications. Don't worry too much about the hypotheticals there, I'm just extrapolating what either answer to my actual question could imply.

答:
Without additional details, I believe you have answered your own question:```... and when compiled will link GPL licensed code ...```

The act of linking in GPL code is binding your project to a GPL project.

I would double check that you understand the licensing of those builtins correctly.

Whether or not the FSF / GNU would attempt to pursue a claim on that basis is a completely different question.  I'm leaning towards "not very likely."

I'm revising my answer based upon some additional research.  In short, I don't think there's a problem and your code would not be required to be licensed as GPL.

From the FAQ:

Using GNU tools

System Lib #1

System Lib #2

Also see Section 1 of the GCC GPL.

The builtins would qualify as system libraries as they enable significant function for GCC as well as provide an interface implementation for the various C* standards.  They're just extensions of the tool.

Most likely, the builtins are released as LGPL, so you'd be exempt due to the linking exclusion.  Even if they aren't, you're still exempt based upon the system library exemption.

Body:
Without additional details, I believe you have answered your own question:
... and when compiled will link GPL licensed code ...

The act of linking in GPL code is binding your project to a GPL project.

I would double check that you understand the licensing of those builtins correctly.

Whether or not the FSF / GNU would attempt to pursue a claim on that basis is a completely different question.  I'm leaning towards "not very likely."

I'm revising my answer based upon some additional research.  In short, I don't think there's a problem and your code would not be required to be licensed as GPL.

From the FAQ:

Using GNU tools

System Lib #1

System Lib #2

Also see Section 1 of the GCC GPL.

The builtins would qualify as system libraries as they enable significant function for GCC as well as provide an interface implementation for the various C* standards.  They're just extensions of the tool.

Most likely, the builtins are released as LGPL, so you'd be exempt due to the linking exclusion.  Even if they aren't, you're still exempt based upon the system library exemption.


答:
100% code coverage for unit tests for all pieces of a particular application is a pipe dream, even with new projects.  I wish it were the case, but sometimes you just cannot cover a piece of code, no matter how hard you try to abstract away external dependencies.  For example, let's say your code has to invoke a web service.  You can hide the web service calls behind a interface so you can mock the that piece, and test the business logic before and after the web service.  But the actual piece that needs to invoke the web service cannot be unit tested (very well anyway).  Another example is if you need to connect to a TCP server.  You can hide the code that connects to a TCP server behind a interface.  But the code that physically connects to a TCP server cannot be unit tested, because if it is down for any reason then that would cause the unit test to fail.  And unit tests should always pass, no matter when they are invoked.

A good rule of thumb is all of your business logic should have 100% code coverage.  But the pieces that have to invoke external components, it should have as close to 100% code coverage as possible.  If you cannot reach then I wouldn't sweat it too much.

Much more important, are the tests correct?  Do they accurately reflect your business and the requirements?  Having code coverage just to have code coverage doesn't mean anything if all you doing is testing incorrectly, or testing incorrect code.  That being said, if your tests are good, then having 92-95% coverage is outstanding.

Title: Is 100% code coverage a pipe dream?

Body: Is it feasible to expect 100% code coverage in heavy jquery/backbonejs web applications?  Is it reasonable to fail a sprint due to 100% coverage not being met when actual code coverage hovers around 92%-95% in javascript/jquery? </p>


答:
In most cases, 100% code coverage means that you've "cheated" a little bit:

Complex, frequently changing parts of the system (like the gui) have been moved to declarative templates or other DSLs.

All code touching external systems has been isolated or handled by libraries.

The same goes for any other dependency, particularly the ones requiring side effects.

Basically, the difficult to test parts have been shunted to areas where they don't necessarily count as "code". It's not always realistic, but note that independent of helping you test, all of these practices make your codebase easier to work on.

Title: Is 100% code coverage a pipe dream?


问:
C# foreach improvements?
I run into this often during programming where I want to have a loop count index inside of a foreach and have to create an integer, use it, increment, etc. Wouldn't it be a good idea if there was a keyword introduced that was the loop count inside of a foreach? It could also be used in other loops as well.

Does this go against the use of keywords seeing as how the compiler would not allow this keyword used anywhere but in a loop construct?

答:
Scoping also works if you want to keep the block clean of collisions with other names...</p>

```<code>{ int index = 0; foreach(var el in List) { Console.WriteLine(el + " @ " + index++); } }
</code>```

Title: C# foreach improvements?

Body:
Scoping also works if you want to keep the block clean of collisions with other names...

{ int index = 0; foreach(var el in List) { Console.WriteLine(el + " @ " + index++); } }


答:
It's not about how many languages you learn. It's about learning new concepts. Some languages might be able to teach you many concepts, while others might be able to teach only one.

If you know C#, you probably wouldn't learn anything terribly new by learning Java. But you would if you learned Haskell.

So when you pick a new language to learn, pick something that will teach you concepts you don't already know.


问:
Setters or constructor for many variables?

Possible Duplicate:

  Are there guidelines on how many parameters a function should accept?

I have got class with 30 variables (it is an application form), so I wonder what is the best practice to organize class creation.

Should I use huge constructor:

```<code>MyClass mc = new MyClass(a, b, c, d)
</code>```

Or setters:

```<code>MyClass mc = new MyClass();
mc.setA(a);
mc.setB(b);
mc.setC(c);
mc.setD(d);
</code>```

What is the best practice in OOP for such a situation? I saw a similar question, but I don't need immutability.

答:
The main difference between your 2 examples is that the user of the class is forced to use the constructor but not forced to set its state via set methods.

You should place all arguments in the constructor that will setup your instance in the correct state. Other 'setting' methods should be optional.

What I would do in your case is identify within your 30 variables comman themes that in themselves can be broken down into DTO's. So you might have instead (for example):

```<code>MyClass mc = new MyClass(personInfo, companyInfo, salaryInfo);
</code>```

Addtionally you might want to look at whether your class is doing too much and whether you can limit the use of internal state by creating smaller component classes rather than having one large class.

ContentLicense: CC BY-SA 4.0

Body:
The main difference between your 2 examples is that the user of the class is forced to use the constructor but not forced to set its state via set methods.

You should place all arguments in the constructor that will setup your instance in the correct state. Other 'setting' methods should be optional.

What I would do in your case is identify within your 30 variables comman themes that in themselves can be broken down into DTO's. So you might have instead (for example):

MyClass mc = new MyClass(personInfo, companyInfo, salaryInfo);

Addtionally you might want to look at whether your class is doing too much and whether you can limit the use of internal state by creating smaller component classes rather than having one large class.


答:
I'd go with the huge constructor.  It's simplest.  If each call to the constructor uses different parameters (that is, you'd end up passing a lot of nulls), either make more constructors.  The basic idea is keep the code to a minimum; make it as simple as possible.  If you need to get real fancy setting values and the setters would be simpler, use them.

There's something sloppy about too many parameters, so you might want to see if you should be passing objects that each contain several parameter values.  Don't strain yourself on this one, but if you've got 15 parameters, I betting you'll find a simpler way to do it.

Too many parameters are bad, but too many mindless setters aren't good either; there's no right answer.  You have to choose the lesser of two weevils.  This discusses setters better than I can.

Title: Setters or constructor for many variables?

Body:
Possible Duplicate:

  Are there guidelines on how many parameters a function should accept?

I have got class with 30 variables (it is an application form), so I wonder what is the best practice to organize class creation.

Should I use huge constructor:

```<code>MyClass mc = new MyClass(a, b, c, d)
</code>```

Or setters:

```<code>MyClass mc = new MyClass();
mc.setA(a);
mc.setB(b);
mc.setC(c);
mc.setD(d);
</code>```

What is the best practice in OOP for such a situation? I saw a similar question, but I don't need immutability.


问:
Truly useful UML diagrams
UML has a jungle of Diagrams.

Profile Diagrams, Class Diagrams, Package Diagrams...

However, (IMH-and-not-too-experienced-O) I quite see that doing each and every diagram is  overkill.

Therefore, which UML Diagrams are more suitable in a web context, more expecificly a blog (we want to build it from scratchs).

I understand that just because I used UML Diagrams does not imply that our code would be great and brilliant... but, it certainly would be better than just unplanified code...

答:
UML was designed as a communication language among involved people. (programmers-programmers, programmers-business people, business people-users) People express their mental models in a simple, unified language everybody understands.

You need to ask yourself how much of that communication you need.

Is it an internal software or product you want to sell along with documentation?

How long will you maintain the software? Will you hire a programmer to maintain it?

How much agile do you want to be? You might waste time by too detailed planning.

How strange things do you want to do? You usually don't need to document common patterns like detailed use case of registration or overall architecture of a blog.

A rule of thumb is to do the high level diagrams to give you overview and spend time on complicated or not so common stuff. Writing/drawing down your mental model in UML forces you to fully understand it and solve many bugs before writing a single line of code.

Title: Truly useful UML diagrams


答:
As a general guideline:

One deployment diagram for an overview of the architecture (good for any system)

One use case diagram for an overview of what users will do with the system (dito)

One class diagram for the data model

Activity diagrams for the flow of individual use cases if they are complex

Perhaps a state machine diagram if you have a create/review/publish workflow for blog entries

Some diagram types (e.g. timing diagram) have rather specialized uses, others tend towards a level of detail where actual code does a better job (e.g. sequence diagrams), and others yet seem to be intended for gigantic projects but have questionable utility even there (package diagrams? Any IDE can show you your packages).

Title: Truly useful UML diagrams

Body:
UML has a jungle of Diagrams.

Profile Diagrams, Class Diagrams, Package Diagrams...

However, (IMH-and-not-too-experienced-O) I quite see that doing each and every diagram is  overkill.

Therefore, which UML Diagrams are more suitable in a web context, more expecificly a blog (we want to build it from scratchs).

I understand that just because I used UML Diagrams does not imply that our code would be great and brilliant... but, it certainly would be better than just unplanified code...


答:
There is a Third Option that is the most Object Oriented Idiom

The best thing to do is to use the Builder pattern.

The class has an default no-arg constructor, and you set all the required parameters and then call .build() or .materialize() or some appropriately named method to validate and finalize the construction of the object and get return a reference to the completed object.

This can be used very successfully with the Fluent API design pattern as well.

Here is an example on how to enforce a Builder pattern API adherence to construct only valid objects. The blog post is about Java, but it applies to any statically type Object Oriented language that supports interfaces. It makes it very easy to know what you must do next with auto completion in an IDE as well.

I am not a big fan of the Fluent API pattern because it can be abused very easily, and when it abused the method chaining makes it very hard to diagnose exceptions, but in this particular case it is very appropriate.


答:
I would ask yourself if you will ever really be constructing this giant object, or will it always be loaded from a database?

I cannot see any reasons to have an object this large constructed with values coming from code.

If this thing is always saved and loaded from a database or a file, give it a simple default constructor and focus on getting the object-database mapping or serialization correct.