答:
Constructor is not expected to do much processing, generally, so I would steer clear of that at least.

Result object should be just the result, created and returned by some other class (or just function, if you're interfacing C). Depending on how much stuff there will be in the result, you can construct that either with constructor parameters, or if there are too many, then having constructor with no parameters (or mandatory parameters), and then set all (or optional) parameters of Result instance after construction, before returning it.

If the library->get_result(foo) involves actual processing and not just getting current result value, then I'd use alternative name. At least to me "get" suggests it is a lightweight operation.

So, in this case probably one of these (C++11 assumed), first declaration of a function (C++ is multi-paradigm language, nothing wrong with functions especially when interfacing with C libs):

```<code>namespace library {
   class Result {...}
   std::unique_ptr<Result> process(library_handle*, foo*); // note: uses move semantics
}

//usage
auto result = library::process(handle, foo)
</code>```

Also note how I removed "foo" from function name. C++ supports overloading, no point in duplicating information, which is already given by type of 2nd argument.

Or a more object-oriented approach:

```<code>namespace library {
    class Result {...}
    class Library {
        Library(library_handle*); // constructor
        std::unique_ptr<Result> process(foo*); // library handle already known
    }
}

//usage
auto result = library->process(foo);
</code>```

In that last example, result might also get stored as member variable in Library class, in which case you would have getter for it. Also, depending on who owns the Result and how big it is, you should consider passing it by value, after learning about C++11 move semantics which would avoid a lot fo copies.

General thoughts: if you are unsure about your C++, consider providing just a very thin C++ wrapper around C, basically just some convenience "value" classes like that Result, and plain functions in a namespace, almost 1:1 mapping to your C API. It might not be as nice as a good OOP C++ API, but it will be a lot better than crappy C++ API designed while learning modern C++ ;)

Title: C++ library API: new or getters?

Body:
I'm writing a C++ wrapper for my C library (my C++ skills are a bit rusty) and I'm wondering what's preferable: allowing user to construct objects themselves or give them objects via getters?

What would be idiomatic C++ equivalent of that C function?

```<code>result* process_foo(library_handle*, foo*);
</code>```

a constructor like this:

```<code>Result *res = new Result(library_handle, foo);
</code>```

or a getter like this? (that basically wraps the above code):

```<code>Result *res = library->get_result(foo);
</code>```

Does the answer change if creation of the result could fail?

Getter could return NULL, but what should constructor version do on failure?
AFAIK some people don't like exceptions. An extra method such as init() or is_valid() doesn't seem elegant.

OTOH the Result object sticks to RAII, it's tiny with inline methods, so it might be good candidate for stack allocation.

Body:
Constructor is not expected to do much processing, generally, so I would steer clear of that at least.

Result object should be just the result, created and returned by some other class (or just function, if you're interfacing C). Depending on how much stuff there will be in the result, you can construct that either with constructor parameters, or if there are too many, then having constructor with no parameters (or mandatory parameters), and then set all (or optional) parameters of Result instance after construction, before returning it.

If the library->get_result(foo) involves actual processing and not just getting current result value, then I'd use alternative name. At least to me "get" suggests it is a lightweight operation.

So, in this case probably one of these (C++11 assumed), first declaration of a function (C++ is multi-paradigm language, nothing wrong with functions especially when interfacing with C libs):

namespace library {
   class Result {...}
   std::unique_ptr<Result> process(library_handle*, foo*); // note: uses move semantics
}

//usage
auto result = library::process(handle, foo)

Also note how I removed "foo" from function name. C++ supports overloading, no point in duplicating information, which is already given by type of 2nd argument.

Or a more object-oriented approach:

namespace library {
    class Result {...}
    class Library {
        Library(library_handle*); // constructor
        std::unique_ptr<Result> process(foo*); // library handle already known
    }
}

//usage
auto result = library->process(foo);

In that last example, result might also get stored as member variable in Library class, in which case you would have getter for it. Also, depending on who owns the Result and how big it is, you should consider passing it by value, after learning about C++11 move semantics which would avoid a lot fo copies.

General thoughts: if you are unsure about your C++, consider providing just a very thin C++ wrapper around C, basically just some convenience "value" classes like that Result, and plain functions in a namespace, almost 1:1 mapping to your C API. It might not be as nice as a good OOP C++ API, but it will be a lot better than crappy C++ API designed while learning modern C++ ;)


问:
A string is immutable, so why are they not all constants?
The string type is immutable.

We can use the const keyword with strings in high level language like .NET. My understanding of 'const' means constant (it remains the same, we can't change the value).

Are strings not always constant (IMO the term constant should not be applicable in the same context if the type has to be recreated each time it means for the values life time, it was constant)?

In high level languages, specifically .NET (although I'd be interested in Java too), is this due to general memory management/tracking of objects or is there another reason?

答:
A simple demonstration of what const accompishes.  This is applicable to C# and similar languages.

```<code>string noconst = "foo";
noconst = "bar"; //noconst has changed! It was declared as "foo" but now is "bar"

const string yesconst = "foo";
yesconst = "bar"; //compiler error
</code>```

ContentLicense: CC BY-SA 3.0

Body:
A simple demonstration of what const accompishes.  This is applicable to C# and similar languages.

string noconst = "foo";
noconst = "bar"; //noconst has changed! It was declared as "foo" but now is "bar"

const string yesconst = "foo";
yesconst = "bar"; //compiler error


答:
As the comments say, you're confusing "constant" with "immutable", when they really mean two very different things.

A constant is a variable that can't be changed.  Depending on the language and the compiler, it's entirely possible for compiled code to simply replace every use of that variable with the value assigned to it, in which case it would never even be allocated a spot in memory.  Even if the compiler doesn't optimize that way, it's still allocated one spot in memory at launch (since const implies static) and stays there until exit.

An immutable is a value in memory that can't be changed (until the memory is reclaimed).  It's assigned a place in memory as needed, and it can (theoretically) be stored in multiple variables.  Assigning to a variable which is pointing at an immutable value simply creates a new immutable and alters the variable to point to that instead.  The old value stays in memory until garbage collected, which can happen even while the program is running.

Title: A string is immutable, so why are they not all constants?

Body:
The string type is immutable.

We can use the const keyword with strings in high level language like .NET. My understanding of 'const' means constant (it remains the same, we can't change the value).

Are strings not always constant (IMO the term constant should not be applicable in the same context if the type has to be recreated each time it means for the values life time, it was constant)?

In high level languages, specifically .NET (although I'd be interested in Java too), is this due to general memory management/tracking of objects or is there another reason?


问:
What can be used in lieu of use cases to gather requirements?
I'm a programmer currently working in rounds of meetings along with BAs and PM to gather/describe modules and functionality of our case management system; after a few meetings I saw that using 'use cases' would be a very very good fit to document many of the things and functions discuessed and/or proposed for the new system. When I suggested we needed to create 'use cases' so that we don't forget what we said/concluded and also to have programers know what they should code, the leading BA mentioned don't like 'use cases'.

What can be used to gather/document requirements when people supposed to write user requirements say they don't like 'use cases', or when you realize that they don't want to write 'use cases' to describe what the system should do?

I'm trying to find out if there's a close or effective substitution to using 'use cases' to document system functionality/scenarios.

答:
Another option would be Personas and Stories. Personas go a step beyond Use Case actors because the represent an actual person using the system and how they might interact with it. For example for a payroll system, you would have personas such as:

Bob from accounting

Alice from hr

Tom the manager

Bill the employee

John the CEO

This allows you to create stories around how these users go about their day using the system. To help get started with the concepts, check out Mike Cohn's book User Stories Applied


答:
You are confusing two different things:

Immutable means the object's memory contents cannot be modified. When you modify an immutable object (e.g, a string), the memory contents of this object are not modified. Instead:

A new block of memory is allocated.

The contents of the object you (tried to) modify is copied to this new block, with the part you wanted to change is changed in this new block.

The pointer (i.e, the reference) is assigned to this new block.

Constant means the variable cannot be modified at compile-time. Whether a string or an integer the contents of the variable (or what it points to) cannot be changed or assigned at compile time.


答:
Strings can't change.  Pointers to strings can change.  The following is valid code:

```<code>String text = "Text";
text = text.substring(1);
</code>```

The original "Text" object is still there, unchanged and immutable, except nothing is pointing to it anymore.  A mutable String would allow you to do text.substring(1) without having to assign it back to the text variable, and it would change the original object.  If you want the variable text not to change, that's when you make it a const.  There are valid use cases for both.

As a side note, this is a good example of a concept that's easier to understand in C++, because objects and pointers to objects have different types.

Body:
Strings can't change.  Pointers to strings can change.  The following is valid code:

String text = "Text";
text = text.substring(1);

The original "Text" object is still there, unchanged and immutable, except nothing is pointing to it anymore.  A mutable String would allow you to do text.substring(1) without having to assign it back to the text variable, and it would change the original object.  If you want the variable text not to change, that's when you make it a const.  There are valid use cases for both.

As a side note, this is a good example of a concept that's easier to understand in C++, because objects and pointers to objects have different types.


答:
Depending on your/their definition of a 'use case' you could instead look at 'user stories'. I say this if you define a use case similar to Usability.gov's definition

A use case is a description of how users will perform tasks on your Web site.
  A use case includes two main parts:
  the steps a user will take to accomplish a particular task on your site
  the way the Web site should respond to a user's actions. A use case begins with a user's goal and ends when that goal is fulfilled.

You can instead use user stories, which come from the agile development methodologies. They are more about what you want to do, then how to do it. There are many different articles and definitions about user stories out there. This older article actually presents what they see as the difference between use cases and user stories (New to User Stories?) And in the end, they really do the same thing. They just frame them differently. You still need the same information, who, what and why (goal). Their meant to be more narrative, with personas linked to real user types of your system. They're more descriptive, but still contain all the information you need.

It sounds like in your case, representing the same information you need differently might be exactly what you need.

Title: What can be used in lieu of use cases to gather requirements?

Body:
I'm a programmer currently working in rounds of meetings along with BAs and PM to gather/describe modules and functionality of our case management system; after a few meetings I saw that using 'use cases' would be a very very good fit to document many of the things and functions discuessed and/or proposed for the new system. When I suggested we needed to create 'use cases' so that we don't forget what we said/concluded and also to have programers know what they should code, the leading BA mentioned don't like 'use cases'.

What can be used to gather/document requirements when people supposed to write user requirements say they don't like 'use cases', or when you realize that they don't want to write 'use cases' to describe what the system should do?

I'm trying to find out if there's a close or effective substitution to using 'use cases' to document system functionality/scenarios.


答:
I believe that you're confusing variables and objects.

A variable is simply a reference to an object.

While your program is running, a variable can refer to multiple objects. Assigning something to the variable does not change the object. If there are no variables that reference an object, it becomes garbage.

A String is considered immutable (in Java, and I would also expect in .Net) because there is no way to change the object.

A constant is simply a variable that is not permitted to change during the life of the program. You define a constant with the final modifier in Java, and the const modifier in .Net.

However, if your "constant" variable points to a mutable object, the "constness" of the variable does not affect the mutability of the object (actually, I can't say that for sure in .Net, because I'm assuming it inherits some of the arcane rules of C++).


问:
What's the most absurd myth about programming issues?
To put it another way... What is the most commonly held and frustrating misunderstanding about programming, you have encountered?

Which widespread and longstanding myths/misconceptions do you find hard for programmers to dispel/correct.

Please, explain why this is a myth.

答:
I've had more than one person ask me about what it is like to program only to realize midway through the conversation that they actually think we program directly in binary or using mathematical symbols.

I don't know if I want to dispel that myth, it makes me look really smart!

ContentLicense: CC BY-SA 2.5


问:
Worst coding standard you've ever had to follow?
Have you ever had to work to coding standards that:

Greatly decreased your productivity?

Were originally included for good reasons but were kept long after the original concern became irrelevant?

Were in a list so long that it was impossible to remember them all?

Made you think the author was just trying to leave their mark rather than encouraging good coding practice?

You had no idea why they were included?

If so, what is your least favorite rule and why?

Some examples here

答:
at my previous job, which I gladly quit 3 months ago:

database:

Table names had to be uppercase.

Table names had to be prefixed TBL_

Fields had to be prefixed: DS_ (for
varchar, which made no sense) NU_ for
numbers CD_ for ("bit fields") DT_
for dates

database fields had also to be uppercase [CD_ENABLED]

same with sp names [SP_INFINITY_USER_GROUPS_QRY] and database names [INFINITY]

did I mention sp names were actually like that? SP_ prefix, then database name SP_INFINITY_ then table name, SP_INFINITY_USER_GROUPS then what the sp was actually expected to do (QRY,UPD,DEL,INS) jesus, don't even get me started on queries that weren't just CRUD queries.

all text fields had to be varchar(MAX), unequivocally.

numbers were either int or double, even when you could have used other type.

"boolean" fields (bit) were int, no reason.

stored procedures had to be prefixed sp_productname_

asp.net / c# / javascript

EVERY single function had to be wrapped in try{}catch{}, so the applications wouldn't "explode" (at least that was the official reason), even when this produced things not working and not having a clue why.

parameters must be prefixed with p, e.g pCount, pPage

scope variables had to be prefixed with w (as in "working", what the hell does that even mean?)

statics with g, etc.

everything post framework 1.1 was offlimits, like you had any real uses for linq and generics anyways. (I made it a point to enforce them to let me use jquery though, I succeded at that, at least).


问:
When and why would we use immutable pointees?
In Java, the String object is both immutable and also a pointee (aka reference type). I'm sure there are other types/objects which are both immutable and a pointee as well and that this extends further than just Java.

I can not think where this would be desirable possibly due to my own experience I've only  used either reference types OR immutable primitive types.

Can some one please give me a situation where it would be useful so I can get an appreciation for their meaning/value/concept.

答:
A string is a pointer that points to an immutable object.  The pointer itself is not immutable.  Changes to strings are made by changing the pointer to point to a new immutable object.

Strings are immutable precisely so that a variable that is actually a pointer can be treated as a normal variable, rather than a pointer.

Because strings are immutable, a string object (i.e. a pointer) can be passed around, without worrying about whether the thing it is pointing to will change.  That is the benefit of the system.

ContentLicense: CC BY-SA 4.0


答:
An immutable reference type behaves similarly to a value type.

If String were not immutable, something like this could happen:

```<code>String a = "abc";
String b = a;
a.ReplaceCharAt(1, "X");  // this is not possible, if the type is immutable

// b is now "aXc", which might be counter-intuitive
</code>```

Immutability prevents this from happening: Whenever I assign a string to a variable, I can be sure that this string won't change until I reassign the variable.

On the other hand, we still get the benefits of reference types for String:

In the example above, abc would only be stored once in memory.

Strings can be variable in size.

The latter one is probably the main reason why Strings are reference types in Java and .NET. Often, value types are stored on the stack. To put something on the stack, the compiler needs to know its size beforehand, which is kind of difficult for strings of varying size.

Title: When and why would we use immutable pointees?

Body:
In Java, the String object is both immutable and also a pointee (aka reference type). I'm sure there are other types/objects which are both immutable and a pointee as well and that this extends further than just Java.

I can not think where this would be desirable possibly due to my own experience I've only  used either reference types OR immutable primitive types.

Can some one please give me a situation where it would be useful so I can get an appreciation for their meaning/value/concept.

Body:
An immutable reference type behaves similarly to a value type.

If String were not immutable, something like this could happen:

String a = "abc";
String b = a;
a.ReplaceCharAt(1, "X");  // this is not possible, if the type is immutable

// b is now "aXc", which might be counter-intuitive

Immutability prevents this from happening: Whenever I assign a string to a variable, I can be sure that this string won't change until I reassign the variable.

On the other hand, we still get the benefits of reference types for String:

In the example above, abc would only be stored once in memory.

Strings can be variable in size.

The latter one is probably the main reason why Strings are reference types in Java and .NET. Often, value types are stored on the stack. To put something on the stack, the compiler needs to know its size beforehand, which is kind of difficult for strings of varying size.


问:
How to create an automated email in several languages (multipart/alternative)?
I need to send automated emails to customers whose language I am not sure about.

90 % are french and would probably not be able to read mails in english.
The other 10 % would probably be able to read in english and clearly not in french.

I don't know what their language is.

I investigated the multipart/alternative that looked promising, give the mailer several variants and he selects the best one.
( see: http://www.ietf.org/rfc/rfc1766.txt )

Unfortunately no mailer seems to care about that, they always show the last part...

did someone manage to make multi-lingual mail with automatic selection of the best version for the users?

Is there some kind of trick to know?

Do you have another solution?

答:
We send bilingual emails in the format

```<code><h1 lang="fr">*** La version française [follows] ***</h1>
<div lang="en">English text here</div>
<h1 lang="en">*** English version precedes ***</h1>
<div lang="fr">Texte français ici</div>
</code>```

Use of the lang attribute will allow a screen reader to correctly toggle between pronunciations; use of headings will allow a screen reader to jump to the relevant version of the email (both assume support in mail client).

http://www.w3.org/TR/html-markup/global-attributes.html#common.attrs.lang

Body:
We send bilingual emails in the format

<h1 lang="fr">*** La version française [follows] ***</h1>
<div lang="en">English text here</div>
<h1 lang="en">*** English version precedes ***</h1>
<div lang="fr">Texte français ici</div>

Use of the lang attribute will allow a screen reader to correctly toggle between pronunciations; use of headings will allow a screen reader to jump to the relevant version of the email (both assume support in mail client).

http://www.w3.org/TR/html-markup/global-attributes.html#common.attrs.lang


问:
Where to read from file?
In Java: I have a class Students. I would like to read a list of students from a file. Which one is more elegant:

Reading and constructing the list in main(), and creating a Student object with the new list passed to the constructor

Passing a FileReader to the constructor, who does the reading?

Something else?

答:
Create a dumb object of student.

Create a method to read each line of the file creating a new student object so you end up with a list of students.

Separate the logic of building up the list from determining which bit of the text file holds which attribute of the student object.

Just remember to follow rules like separation of concern and the principles of SOLID.

Title: Where to read from file?


答:
Use a separate method, which does the reading and the initialization of the Student object. The benefit of this is, that you can reuse this wherever you need it, not only in main or while constructing a new Student.

You could also implement the Serializable interface.

Title: Where to read from file?

Body:
In Java: I have a class Students. I would like to read a list of students from a file. Which one is more elegant:

Reading and constructing the list in main(), and creating a Student object with the new list passed to the constructor

Passing a FileReader to the constructor, who does the reading?

Something else?

OwnerDisplayName: Olaf Dietsche


答:
Which one is more elegant

Elegance (in programming) is a matter of personal taste.  You need to make up your own mind.

Other things to consider are:

whether a particular approach provides the required functionality,

whether the API is easy to understand, and

whether the API supports use-cases other than the current one; i.e. whether it is reusable.

Title: Where to read from file?

OwnerDisplayName: Stephen C


答:
Sounds like the factory pattern is required, something along the lines of a StudentFactorywhich generates the students object.

You should have that as an interface and a FileStudentFactory implementation which does the reading of the file and then if you wanted a different provider later you change out the implementation.

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

Title: Where to read from file?

OwnerDisplayName: James Baker


答:
Ahh...the blessed string, it's the photon of the software world. Depending on how you look at it, it exhibits properties of a reference type or a value type.

The benefit of being a reference type is that you can pass it by reference. But if I declared a string as "MyConstantValueString" and I passed it to a function, I wouldn't want that function to change the value because I'm always expecting it to be "MyConstantValueString".

By making it immutable, you get the benefits of passing by reference (no copy needed) with the security of knowing that the string you're pointing to will never change unless you explicitly point it to another.

There are other scenarios where this will come in handy. Think for example of a functional queue. For reference, I point you to the excellent work of Eric Lippert (it's in C# but it's easy enough to translate to Java, and I recommend reading that entire series, it's pretty eye opening). Where would I want to use a functional queue and what use would it be?

Believe it or not, functional queues are useful for...well queuing. E.g. I have work that needs to be done, I need to allow clients to add work to be done while also allowing workers to pull off work and do it. Internally, the queue is immutable with only one internal writer and reader. Externally, I can avoid the synchronization by just telling the writer to add my work to the queue and moving on. The reader meanwhile can pull off a batch of items and distribute them to workers also asynchronously. This reduces bottlenecks tremendously. In fact, this is how ZeroMQ is structured.


答:
If you create  class student you probably need to create a method which returns name of students like this

```<code>public String getName(){
return this.name;
}
</code>```

and in main class you create Student Object in an array or ArrayList like this:

```<code>Student [] students = new Student [size];
</code>```

and then you have setName(String name) and getName()

Then :

Create DefaultListModel add names to the model then add model to the list like This

```<code>DefaultListModel model = new DefaultListModel ();
for(int i = 0; i< students.length; i++){
model.addElement(students[i].getName());
}
list.setModel(model);
</code>```

I didn't test it hope you get the idea.

Title: Where to read from file?

Body:
If you create  class student you probably need to create a method which returns name of students like this

public String getName(){
return this.name;
}

and in main class you create Student Object in an array or ArrayList like this:

Student [] students = new Student [size];

and then you have setName(String name) and getName()

Then :

Create DefaultListModel add names to the model then add model to the list like This

DefaultListModel model = new DefaultListModel ();
for(int i = 0; i< students.length; i++){
model.addElement(students[i].getName());
}
list.setModel(model);

I didn't test it hope you get the idea.


问:
Why use a database instead of just saving your data to disk?
Instead of a database I just serialize my data to JSON, saving and loading it to disk when necessary. All the data management is made on the program itself, which is faster AND easier than using SQL queries. For that reason I have never understood why databases are necessary at all.

Why should one use a database instead of just saving the data to disk?

答:
File systems are a type of database. Maybe not a RDBMS like everyone else is talking about, but certainly a DB in the strictest sense. You're provide keys (file name) to look-up data (file contents), which has abstracted storage and an API by which your program communicates.

So, you are using a Database. The other posts can argue about the virtues of different types of database...


问:
What is the difference between a principle and a best practice?
I recently read http://simpleprogrammer.com/2013/02/17/principles-are-timeless-best-practices-are-fads/ and it resonated with me. I find the more experienced programmers/architects go against current best practices and their excuse is some best practices don't work with their problem domain. For example, I have just started to work for a new company as a programmer and my architect writes his nhibernate queries in the UI layer instead of writing it in a separate layer. A part of me shrieks knowing this because it sort of goes against everything I have been reading on the internet for the past 5 years but I'm willing enough to try this approach and weigh the pro's and con's. Who knows, maybe he's right. I do find him as a very component programmer.

What separates a principle from a best practice (if anything)? How can you distinguish between the two, and how can you determine when it's appropriate to ignore either?

答:
What separates a principle from a best practice (if anything)?

The practice will usually be specific and concrete where examples from the article would include source control, unit testing, continuous integration, and other ideas that while the concept may be abstract, there are specific tools that could be used to demonstrate this is being used.  For example, Subversion can be used for source control, nUnit for unit testing, Cruise Control.Net for continuous integration.

A principle on the other hand, would be more nebulous and thus not as tangible.  The Agile Manifesto that lists these four ideas:

Individuals and interactions over processes and tools

Working software over comprehensive documentation

Customer collaboration over contract negotiation

Responding to change over following a plan

Thus, while one can take a specific example and look at whether these are being applied, there isn't quite the tool to pull out to show, "Hey, we have working software over comprehensive documentation because we use X!" whereas the practices I noted above have tools that could be a litmus test.

How can you distinguish between the two, and how can you determine
  when it's appropriate to ignore either?

To my mind it is a level of detail.  How specific does one want to get in applying an idea?  At a high level there are principles and at a lower level there are practices.

As for when it is appropriate to ignore either, this is where you have to look on a case by case basis.  For example, if I'm writing a script that will be used to generate some test data that I'll probably use once, is it really worthwhile for me to spend hours planning it, building unit tests and applying a lot of extra overhead when what I could do is spend the half hour writing the script, run it and then commit my data when I'm done.  This focuses a bit more on practices as those are easier to see where it is worth applying things since sometimes on small things, it may not be worthwhile to set up various practices that would be useful in other environments.  Principles can be a bit harder to give a specific example.

How to Win Friends and Influence People is referenced in the article as having principles and here is something to consider in taking the ways to win people to your way of thinking:

Twelve Ways to Win People to Your Way of Thinking

The only way to get the best of an argument is to avoid it.

Show respect for the other person's opinions. Never say "You're Wrong."

If you're wrong, admit it quickly and emphatically.

Begin in a friendly way.

Start with questions to which the other person will answer yes.

Let the other person do a great deal of the talking.

Let the other person feel the idea is his or hers.

Try honestly to see things from the other person's point of view.

Be sympathetic with the other person's ideas and desires.

Appeal to the nobler motives.

Dramatize your ideas.

Throw down a challenge.

While this is a good list, it is worth noting that some ideas here can be a bit conflicting.  For example, is there a friendly way to throw down a challenge?  Perhaps there are friendlier ways but in trying to get someone to rise to a challenge there is something to be said for getting the person to stretch themselves.  There is another set of ideas in the book that may be worth reviewing here too:

Be a Leader: How to Change People Without Giving Offense or Arousing
  Resentment

Begin with praise and honest appreciation.

Call attention to people's mistakes indirectly.

Talk about your own mistakes before criticizing the other person.

Ask questions instead of giving direct orders.

Let the other person save face.

Praise every improvement.

Give the other person a fine reputation to live up to.

Use encouragement. Make the fault seem easy to correct.

Make the other person happy about doing what you suggest.

Notice how some of these are similar.  Number 7, "Give the other person a fine reputation to live up to," is similar to number 12 in the first list, "Throw down a challenge," which may demonstrate a principle about how most people have an inner fighting instinct that can be used at times.  Similarly, notice how the number 3 of each list is about admitting one's mistakes that may be about a principle around humility.


答:
Don't think of it as principles vs best practices. In the process of writing my book on MVVM (I would say it was a shameless plug but it's not out yet), I've come up with an analogy. Just like in art there were various movements throughout the ages, there are certain movements within software engineering. Just like you can identify a Gothic Cathedral via the flying buttresses and rose windows or a impressionist painting via its visible brushstrokes and open composition, so you can identify code that follows a certain software movement by looking for certain elements.

The MVVM movement has the View Model as its centerpiece with minimal code behind, functions encapsulated in commands, and decoupled messaging via an event aggregator. There is a beauty to the way these components are structured.

Those who follow Domain Driven Design create rich domain objects with persistence ignorance and logic embedded in the core of the objects.

CQRS proponents separate their domain models into a Query and Command model also referred to as a Read Model and a Write model. They like to use asynchronous calls via a message bus that updates the transactional store and the query store at the same time. And prefer a concept called eventual consistency.

The "best practices" of these movements aren't globally applicable, but more or less attributes that are consistent with the movement. As new movements rise to dominance and old movements fade, they won't be as prominent but that doesn't mean the techniques of one movement won't be useful with a subsequent one.

So What's a Principle

Principles, like the article said, are globally applicable no matter what movement. Think of Uncle Bob's SOLID principles. Or the Gang of Four's Composition over Inheritance. These principles are applicable almost anywhere. Almost being the keyword.

Naturally, you can't apply OO principles to Functional Programming. Well you can but they take on different forms. And once you have enough experience, you'll know when a principle doesn't apply. (You'll know if you have enough experience if you don't have to ask "Does it apply here" you'll just know that it doesn't look at the Dreyfus Model of Skill Acquisition at the Expert level, you don't need the principles...they're there but you don't rely on them for decision making).

In the same way, once you have achieved expertise using a certain approach or style of programming, you start adding your own touch to that style. For example, I and a few other MVVM pioneers simultaneously and independently "discovered" the DelegateCommand pattern (and we all called it the same thing except Josh Smith who called his RelayCommand which is practically a synonym for Delegate).

In Summary

Principles are guidance for less experienced developers to help them make decisions via rules.

"Best practices" or Code Styles are approaches to development that provide consistency and familiarity for those who follow that Style

You'll know when it's appropriate to ignore each when you "know without knowing".

Title: What is the difference between a principle and a best practice?

Body:
I recently read http://simpleprogrammer.com/2013/02/17/principles-are-timeless-best-practices-are-fads/ and it resonated with me. I find the more experienced programmers/architects go against current best practices and their excuse is some best practices don't work with their problem domain. For example, I have just started to work for a new company as a programmer and my architect writes his nhibernate queries in the UI layer instead of writing it in a separate layer. A part of me shrieks knowing this because it sort of goes against everything I have been reading on the internet for the past 5 years but I'm willing enough to try this approach and weigh the pro's and con's. Who knows, maybe he's right. I do find him as a very component programmer.

What separates a principle from a best practice (if anything)? How can you distinguish between the two, and how can you determine when it's appropriate to ignore either?


问:
C++ library API: new or getters?
I'm writing a C++ wrapper for my C library (my C++ skills are a bit rusty) and I'm wondering what's preferable: allowing user to construct objects themselves or give them objects via getters?

What would be idiomatic C++ equivalent of that C function?

```<code>result* process_foo(library_handle*, foo*);
</code>```

a constructor like this:

```<code>Result *res = new Result(library_handle, foo);
</code>```

or a getter like this? (that basically wraps the above code):

```<code>Result *res = library->get_result(foo);
</code>```

Does the answer change if creation of the result could fail?

Getter could return NULL, but what should constructor version do on failure?
AFAIK some people don't like exceptions. An extra method such as init() or is_valid() doesn't seem elegant.

OTOH the Result object sticks to RAII, it's tiny with inline methods, so it might be good candidate for stack allocation.

答:
You dismissed the constructor + init method approach, but it's not necessarily a bad choice.  In fact, Cocoa (the Objective C setup used widely in iOS/MacOS programming) uses the post-allocation "init" approach everywhere, so there is a widely used and successful precedent for it.  If you have a substantial and not-guaranteed initialization, and you are reluctant to throw exceptions (and I would be reluctant as well!), then maybe you actually do want to go the "init" route.

Here's a description of Cocoa's init pattern, I know you're doing C++, but it might be informative by way of analogy:

https://developer.apple.com/library/mac/#documentation/General/Conceptual/CocoaEncyclopedia/Initialization/Initialization.html#//apple_ref/doc/uid/TP40010810-CH6

Title: C++ library API: new or getters?


问:
Is there any real value in unit testing a controller in ASP.NET MVC?
I hope this question gives some interesting answers because it's one that's bugged me for a while.

Is there any real value in unit testing a controller in ASP.NET MVC?

What I mean by that is, most of the time, (and I'm no genius), my controller methods are, even at their most complex something like this:

```<code>public ActionResult Create(MyModel model)
{
    // start error list
    var errors = new List<string>();

    // check model state based on data annotations
    if(ModelState.IsValid)
    {
        // call a service method
        if(this._myService.CreateNew(model, Request.UserHostAddress, ref errors))
        {
            // all is well, data is saved,
            // so tell the user they are brilliant
            return View("_Success");
        }
    }

    // add errors to model state
    errors.ForEach(e => ModelState.AddModelError("", e));

    // return view
    return View(model);
}
</code>```

Most of the heavy-lifting is done by either the MVC pipeline or my service library.

So maybe questions to ask might be:

what would be the value of unit testing this method?

would it not break on Request.UserHostAddress and ModelState with a NullReferenceException? Should I try to mock these?

if I refractor this method into a re-useable "helper" (which I probably should, considering how many times I do it!), would testing that even be worthwhile when all I'm really testing is mostly the "pipeline" which, presumably, has been tested to within an inch of it's life by Microsoft?

I think my point really is, doing the following seems utterly pointless and wrong

```<code>[TestMethod]
public void Test_Home_Index()
{
    var controller = new HomeController();
    var expected = "Index";
    var actual = ((ViewResult)controller.Index()).ViewName;
    Assert.AreEqual(expected, actual);
}
</code>```

Obviously I'm being obtuse with this exaggeratedly pointless example, but does anybody have any wisdom to add here?

Looking forward to it...
Thanks.

答:
Obviously some controllers are much more complex than that but based purely on your example:

What happens if myService throws an exception?

As a side note.

Also, I'd question the wisdom of passing a list by reference (it's unnecessary since c# passes by reference anyway but even if it wasn't) - passing an errorAction action (Action) that the service can then use to pump error messages to which could then be handled however you want (maybe you want to add it to the list, maybe you want to add a model error, maybe you want to log it).

In your example:

instead of ref errors, do (string s) => ModelState.AddModelError("", s) for example.


问:
What's the right balance between code consistency and code improvement?
Recently I had a discussion with a colleague regarding code style. He was arguing that your usage of APIs and the general patterns you are using should be as similar as possible with the surrounding code, if not with the the codebase as a whole, just as you would with code appearance (brace positioning, capitalisation etc). For example if I were adding a method to a DAO class in C# I would try to use LINQ where appropriate to help make my code clean and easy to maintain, even if none of the other methods in that class were using it. However, my colleague would argue that I should not use it in that instance because it would be against the existing style of that class and thus harder to understand.

At first I found his position rather extreme, but after thinking it over for a while I am beginning to see his point. With the hypothetical LINQ example, perhaps this class doesn't contain it because my colleagues are unfamiliar with LINQ? If so, wouldn't my code be more maintainable for my fellow developers if I didn't use it? On the other hand, if I truly believe that using such a technique would result in cleaner code, then shouldn't I use it even if it differs drastically from the surrounding code?

I think that the crux of my colleague's argument is that if we all go about implementing similar functionality in a codebase in different ways, and we each think that our way is "best", then in the end the code as a whole just gets harder to understand. However at the moment I still think that if we blindly follow the existing code too much then the quality will just slowly rot over time.

So, to what extent are patterns part of code style, and where should we draw the line between staying consistent and making improvements?

答: We have regular, fairly informal, technical meetings which any one of us can run. If we find a new technique we present it at the meeting. You generally get a good feeling of how well the idea is accepted and understood by your colleagues. This helps you to decide whether it is wise to include it in your code, helps others to decipher it if you do and also establishes the 'go to' person if others need help with that style. If no one reinvented the wheel we'd still be dragging stuff around on logs.</p>


问:
The difference between "concurrent" and "parallel" execution?
What is the difference between the terms concurrent and parallel execution?  I've never quite been able to grasp the distinction.

The tag defines concurrency as a manner of running two processes simultaneously, but I thought parallelism was exactly the same thing, i.e.:  separate threads or processes which can potentially be run on separate processors.

Also, if we consider something like asynchronous I/O, are we dealing with concurrency or parallelism?

答:
Concurrency and parallelism are two related but distinct concepts.

Concurrency means, essentially, that task A and task B both need to happen independently of each other, and A starts running, and then B starts before A is finished.

There are various different ways of accomplishing concurrency. One of them is parallelism--having multiple CPUs working on the different tasks at the same time.  But that's not the only way.  Another is by task switching, which works like this:  Task A works up to a certain point, then the CPU working on it stops and switches over to task B, works on it for a while, and then switches back to task A.  If the time slices are small enough, it may appear to the user that both things are being run in parallel, even though they're actually being processed in serial by a multitasking CPU.


问:
Is relying on implicit argument conversion considered dangerous?
C++ has a feature (I cannot figure out the proper name of it), that automatically calls matching constructors of parameter types if the argument types are not the expected ones.

A very basic example of this is calling a function that expects a std::string with a const char* argument. The compiler will automatically generate code to invoke the appropriate std::string constructor.

I'm wondering, is it as bad for readability as I think it is?

Here's an example:

```<code>class Texture {
public:
    Texture(const std::string& imageFile);
};

class Renderer {
public:
    void Draw(const Texture& texture);
};

Renderer renderer;
std::string path = "foo.png";
renderer.Draw(path);
</code>```

Is that just fine? Or does it go too far? If I shouldn't do it, can I somehow make Clang or GCC warn about it?

答:
This is more of a comment than an answer but too big to put in a comment.

Interestingly, g++ does not let me do that:

```<code>#include <iostream>
#include <string>

class Texture {
        public:
                Texture(const std::string& imageFile)
                {
                        std::cout << "Texture()" << std::endl;
                }
};

class Renderer {
        public:
                void Draw(const Texture& texture)
                {
                        std::cout << "Renderer.Draw()" << std::endl;
                }
};

int main(int argc, char* argv[])
{
        Renderer renderer;
        renderer.Draw("foo.png");

        return 0;
}
</code>```

Produces the following:

```<code>$ g++ -o Conversion.exe Conversion.cpp
Conversion.cpp: In function ‘int main(int, char**)’:
Conversion.cpp:23:25: error: no matching function for call to ‘Renderer::Draw(const char [8])’
Conversion.cpp:14:8: note: candidate is: void Renderer::Draw(const Texture&)
</code>```

However, if I change the line to:

```<code>   renderer.Draw(std::string("foo.png"));
</code>```

It will perform that conversion.

Body:
This is more of a comment than an answer but too big to put in a comment.

Interestingly, g++ does not let me do that:

#include <iostream>
#include <string>

class Texture {
        public:
                Texture(const std::string& imageFile)
                {
                        std::cout << "Texture()" << std::endl;
                }
};

class Renderer {
        public:
                void Draw(const Texture& texture)
                {
                        std::cout << "Renderer.Draw()" << std::endl;
                }
};

int main(int argc, char* argv[])
{
        Renderer renderer;
        renderer.Draw("foo.png");

        return 0;
}

Produces the following:

$ g++ -o Conversion.exe Conversion.cpp
Conversion.cpp: In function ‘int main(int, char**)’:
Conversion.cpp:23:25: error: no matching function for call to ‘Renderer::Draw(const char [8])’
Conversion.cpp:14:8: note: candidate is: void Renderer::Draw(const Texture&)

However, if I change the line to:

   renderer.Draw(std::string("foo.png"));

It will perform that conversion.


答:
Parallel processing is a subset of concurrent processing.

Concurrent processing describes two tasks occurring asynchronously, meaning the order in which the tasks are executed is not predetermined. Two threads can run concurrently on the same processor core by interleaving executable instructions. For example, thread 1 runs for 10ms, thread 2 runs for 10ms etc.

Parallel processing is a type of concurrent processing where more than one set of instructions is executing simultaneously. This could be multiple systems working on a common problem as in distributed computing, or multiple cores on the same system.

Title: The difference between "concurrent" and "parallel" execution?

Body:
What is the difference between the terms concurrent and parallel execution?  I've never quite been able to grasp the distinction.

The tag defines concurrency as a manner of running two processes simultaneously, but I thought parallelism was exactly the same thing, i.e.:  separate threads or processes which can potentially be run on separate processors.

Also, if we consider something like asynchronous I/O, are we dealing with concurrency or parallelism?


答:
It's called implicit type conversion.  In general it's a good thing, as it inhibits unnecessary repetition.  For example, you automatically get a std::string version of Draw without having to write any extra code for it.  It can also aid in following the open-closed principle, as it lets you extend Renderer's capabilities without modifying Renderer itself.

On the other hand, it's not without drawbacks.  It can make it difficult to figure out where an argument is coming from, for one thing.  It can sometimes produce unexpected results in other cases.  That's what the explicit keyword is for.  If you put it on the Texture constructor it disables using that constructor for implicit type conversion.  I'm not aware of a method to globally warn on implicit type conversion, but that doesn't mean a method doesn't exist, only that gcc has an incomprehensibly large number of options.

Title: Is relying on implicit argument conversion considered dangerous?

Body:
C++ has a feature (I cannot figure out the proper name of it), that automatically calls matching constructors of parameter types if the argument types are not the expected ones.

A very basic example of this is calling a function that expects a std::string with a const char* argument. The compiler will automatically generate code to invoke the appropriate std::string constructor.

I'm wondering, is it as bad for readability as I think it is?

Here's an example:

```<code>class Texture {
public:
    Texture(const std::string& imageFile);
};

class Renderer {
public:
    void Draw(const Texture& texture);
};

Renderer renderer;
std::string path = "foo.png";
renderer.Draw(path);
</code>```

Is that just fine? Or does it go too far? If I shouldn't do it, can I somehow make Clang or GCC warn about it?


答:
My controllers are very small as well. Most of the "logic" in controllers is handled using filter attributes (built-in and hand-written). So my controller usually only has a handful of jobs:

Create models from HTTP query strings, form values, etc.

Perform some basic validation

Call into my data or business layer

Generate a ActionResult

Most of the model binding is done automatically by ASP.NET MVC. DataAnnotations handle most of the validation for me, too.

Even with so little to test, I still typically write them. Basically, I test that my repositories are called and that the correct ActionResult type is returned. I have a convenience method for ViewResult for making sure the right view path is returned and the view model looks the way I expect it to. I have another for checking the right controller/action is set for RedirectToActionResult. I have other tests for JsonResult, etc. etc.

An unfortunate result of sub-classing the Controller class is that it provides a lot of convenience methods that use the HttpContext internally. This makes it hard to unit test the controller. For this reason, I typically put HttpContext-dependent calls behind an interface and pass that interface to the controller's constructor (I use Ninject web extension to create my controllers for me). This interface is usually where I stick helper properties for accessing session, configuration settings, the IPrinciple and URL helpers.

This takes a lot of due diligence, but I think it is worth it.

Body:
I hope this question gives some interesting answers because it's one that's bugged me for a while.

Is there any real value in unit testing a controller in ASP.NET MVC?

What I mean by that is, most of the time, (and I'm no genius), my controller methods are, even at their most complex something like this:

```<code>public ActionResult Create(MyModel model)
{
    // start error list
    var errors = new List<string>();

    // check model state based on data annotations
    if(ModelState.IsValid)
    {
        // call a service method
        if(this._myService.CreateNew(model, Request.UserHostAddress, ref errors))
        {
            // all is well, data is saved,
            // so tell the user they are brilliant
            return View("_Success");
        }
    }

    // add errors to model state
    errors.ForEach(e => ModelState.AddModelError("", e));

    // return view
    return View(model);
}
</code>```

Most of the heavy-lifting is done by either the MVC pipeline or my service library.

So maybe questions to ask might be:

what would be the value of unit testing this method?

would it not break on Request.UserHostAddress and ModelState with a NullReferenceException? Should I try to mock these?

if I refractor this method into a re-useable "helper" (which I probably should, considering how many times I do it!), would testing that even be worthwhile when all I'm really testing is mostly the "pipeline" which, presumably, has been tested to within an inch of it's life by Microsoft?

I think my point really is, doing the following seems utterly pointless and wrong

```<code>[TestMethod]
public void Test_Home_Index()
{
    var controller = new HomeController();
    var expected = "Index";
    var actual = ((ViewResult)controller.Index()).ViewName;
    Assert.AreEqual(expected, actual);
}
</code>```

Obviously I'm being obtuse with this exaggeratedly pointless example, but does anybody have any wisdom to add here?

Looking forward to it...
Thanks.


答:
This is referred to as a converting constructor (or sometimes implicit constructor or implicit conversion).

I'm not aware of a compile-time switch to warn when this occurs, but it's very easy to prevent; just use the explicit keyword.

```<code>class Texture {
public:
    explicit Texture(const std::string& imageFile);
};
</code>```

As to whether or not converting constructors are a good idea:  It depends.

Circumstances in which implicit conversion makes sense:

The class is cheap enough to construct that you don't care if it's implicitly constructed.

Some classes are conceptually similar to their arguments (such as std::string reflecting the same concept as the const char * it can implicitly convert from), so implicit conversion makes sense.

Some classes become a lot more unpleasant to use if implicit conversion is disabled.  (Think of having to explicitly invoke std::string every time you want to pass a string literal.  Parts of Boost are similar.)

Circumstances in which implicit conversion makes less sense:

Construction is expensive (such as your Texture example, which requires loading and parsing a graphic file).

Classes are conceptually very dissimilar to their arguments.  Consider, for example, an array-like container that takes its size as an argument:

```
    class FlagList
    {
        FlagList(int initial_size);
    };

    void SetFlags(const FlagList& flag_list);

    int main() {
        // Now this compiles, even though it's not at all obvious
        // what it's doing.
        SetFlags(42);
    }
```

Construction may have unwanted side effects.  For example, an AnsiString class should not implicitly construct from a UnicodeString, since the Unicode-to-ANSI conversion may lose information.

Further reading:

The C++ FAQ on explicit constructors

The Google C++ Style Guide says to nearly always use explicit constructors.

This StackOverflow question goes into more pros and cons.

Body:
This is referred to as a converting constructor (or sometimes implicit constructor or implicit conversion).

I'm not aware of a compile-time switch to warn when this occurs, but it's very easy to prevent; just use the explicit keyword.

class Texture {
public:
    explicit Texture(const std::string& imageFile);
};

As to whether or not converting constructors are a good idea:  It depends.

Circumstances in which implicit conversion makes sense:

The class is cheap enough to construct that you don't care if it's implicitly constructed.

Some classes are conceptually similar to their arguments (such as std::string reflecting the same concept as the const char * it can implicitly convert from), so implicit conversion makes sense.

Some classes become a lot more unpleasant to use if implicit conversion is disabled.  (Think of having to explicitly invoke std::string every time you want to pass a string literal.  Parts of Boost are similar.)

Circumstances in which implicit conversion makes less sense:

Construction is expensive (such as your Texture example, which requires loading and parsing a graphic file).

Classes are conceptually very dissimilar to their arguments.  Consider, for example, an array-like container that takes its size as an argument:

    class FlagList
    {
        FlagList(int initial_size);
    };

    void SetFlags(const FlagList& flag_list);

    int main() {
        // Now this compiles, even though it's not at all obvious
        // what it's doing.
        SetFlags(42);
    }

Construction may have unwanted side effects.  For example, an AnsiString class should not implicitly construct from a UnicodeString, since the Unicode-to-ANSI conversion may lose information.

Further reading:

The C++ FAQ on explicit constructors

The Google C++ Style Guide says to nearly always use explicit constructors.

This StackOverflow question goes into more pros and cons.


答:
The two concepts are related, but different.

Concurrency means that two or more calculations happen within the same time frame, and there is usually some sort of dependency between them.

Parallelism means that two or more calculations happen simultaneously.

Put boldly, concurrency describes a problem (two things need to happen together), while parallelism describes a solution (two processor cores are used to execute two things simultaneously).

Parallelism is one way to implement concurrency, but it's not the only one. Another popular solution is interleaved processing (a.k.a. coroutines): split both tasks up into atomic steps, and switch back and forth between the two.

By far the best known example of non-parallel concurrency is how JavaScript works: there is only one thread, and any asynchronous callback has to wait until the previous chunk of code has finished executing. This is important to know, because it guarantees that any function you write is atomic - no callback can interrupt it until it returns. But it also means that "busy loops" won't work - you can't set a timeout and then loop until it fires, because the loop will prevent the timeout callback from executing.


答:
Even for something so simple, a unit test will serve multiple purposes

Confidence, what was written conforms to expected output. It may seem trivial to verify that it returns the correct view, but the result is objective evidence that the requirement was met

Regression testing. Should the Create method need to change, you still have a unit test for the expected output. Yes, the output could change along and that results in a brittle test but it still is a check against un-managed change control

For that particular action I'd test for the following

What happens if _myService is null?

What happens if _myService.Create throws an Exception, does it throw specific ones to handle?

Does a successful _myService.Create return the _Success view?

Are errors propagated up to ModelState?

You pointed out checking Request and Model for NullReferenceException and I think the ModelState.IsValid will take care of handling NullReference for Model.

Mocking out the Request allows you to guard against a Null Request which is generally impossible in production I think, but can happen in a Unit Test. In an Integration Test it would allow you to provide different UserHostAddress values (A request is still user input as far as the control is concerned and should be tested accordingly)

Title: Is there any real value in unit testing a controller in ASP.NET MVC?


问:
Test planning for an Agile sprint
Can anyone offer any tips or experience on developing a test plan for an Agile sprint? Most of the time our team simply creates a "Test Feature X" task and goes about writing ad-hoc test cases. There typically isn't much strategic forethought put into how features will be tested and how we'll communicate the expectations and results to the rest of the development team and our users.

Is it common to just write high-level testing tasks without making the actual test cases transparent to the development team? What sort of methodologies have you used when developing a test plan and what does it look like both at the beginning of a sprint and at the end? Any advice or tips on what comprises an effective and transparent test plan as well as a means of developing the test plan would be much appreciated.

答:
I think it really depends on the type of project and what kind of decisions you must made. I.e., what is the purpose of test plan for you.

Here I will share some experience regarding our project.

In our project and team testing means:

preparing test environments, required for system tests

preparing test data: getting real data from production or simulating

automating tests at unit, integration, system, system integration level.

writing mocks, test drivers, data simulators, test frameworks

demonstrating development output

So planning tests is about making high-level decisions to clarify above. For instance, we decide whether QA needs to end-to-end test a given story, or it is better if she increases test coverage at unit level, extending this way tests written by developers. Getting test data often means getting in contact with customers, business analytics and other stakeholders to get access to them. End-to-end tests often require know-how of more experiences testers, business analytics and delivery guys, so we must plan ahead training. Testers often present what the team achieved, so we sometimes plan what tests to prepare for the demo.

Automation is a separate story. We have established methodology and frameworks for testing, so testing means implementing and executing test cases. On other side, we are developing a new test framework, that is a separate development project going in parallel to the main one. This must be planned as well, cannot be done ad hoc, but we still learn from other teams how do plan this effectively.

We usually know what we will be doing in the current or coming release, so planning tests is done ahead for several iterations.

We usually do some test planning with the rest of the team, when iteration starts. We do not always write down all decisions about testing, but we still plan testing process.

We, as testers, sometimes need to support both current iteration and regression tests. So we need to plan how much our capacity can be devoted to current iteration and whether developers can cover our testing tests, if we are too busy with other responsibilities. This is agile, so developers can do some testing, but we still need to plan this to some degree.

Title: Test planning for an Agile sprint


问:
Is it OK to have multiple asserts in a single unit test?
In the comment to this great post, Roy Osherove mentioned the OAPT project that is designed to run each assert in a single test.

The following is written on the project's home page:

Proper unit tests should fail for
  exactly one reason, that’s why you
  should be using one assert per unit
  test.

And, also, Roy wrote in comments:

My guideline is usually that you test
  one logical CONCEPT per test. you can
  have multiple asserts on the same
  object. they will usually be the same concept being tested.

I think that, there are some cases where multiple assertions are needed (e.g. Guard Assertion), but in general I try to avoid this. What is your opinion? Please provide a real world example where multiple asserts are really needed.

答:
The goal of the unit test is to give you as much information as possible about what is failing but also to help accurately pinpoint the most fundamental problems first. When you know logically that one assertion will fail given that another assertion fails or in other words there is a dependency relationship between the test then it makes sense to roll these as multiple asserts within a single test. This has the benefit of not littering the test results with obvious failures which could have been eliminated if we bailed out on the first assertion within a single test. In the case where this relationship does not exist the preference would naturally be then to separate these assertions into individual tests because otherwise finding these failures would require multiple iterations of test runs to work out all of the issues.

If you then also design the units/classes in such a way that overly complex tests would need to be written it makes less burden during testing and probably promotes a better design.


问:
Whats the greatest most impressive programing feat you ever witnessed?
Everyone knows of the old adage that the best programmers can be orders of magnitude better than the average. I've personally seen good code and programmers, but never something so absurd. So the questions is, what is the most impressive feat of programming you ever witnessed or heard of?

You can define impressive by:

The scope of the task at hand e.g. John single handedly developed the framework for his company, a work comparable in scope to what the other 200 employed were doing combined.

Speed e.g. Stu programmed an entire real time multi-tasking app OS on an weekened including  its own C compiler and shell command line tools

Complexity e.g. Jane rearchitected our entire 10 millon LOC app to work in a cluster of servers. And she did it in an afternoon.

Quality e.g. Charles's code had a rate of defects per LOC 100 times lesser than the company average. Furthermore he code was clean and understandable by all.

Obviously, the more of these characteristics combined, and the more extreme each of them, the more impressive is the feat.

So, let me have it. What's the most absurd feat you can recount? Please provide as much detail as possible and try to avoid urban legends or exaggerations. Post only what you can actually vouch for.

Bonus questions:

Was the herculean task a one-of, or did the individual regularly amazed people?

How do you explain such impressive performance?

How was the programmer recognized for such awesome work?

答:
Terry Winograd's SHRDLU.

Doug Lenat's Automated Mathematician.


问:
How relevant are Brainbench scores when evaluating candidates?
I've seen many companies using certification services such as Brainbench when evaluating candidates. Most times they use it as a secondary screen prior to interview or as a validation to choose between candidates.

What is your experience with Brainbench scores? Did you try the tests yourself, and if so do you feel the score is meaningful enough to be used as part of a hiring process?

Difficult choice.

Consensus seems to be that BB cert are not very good as a certification.  The biggest argument was around the fact that some of the questions are too precise to form a good evaluation.  This view can probably be tempered somewhat but still, to hold someone's future solely on the results of this evaluation would be irresponsible.

That said, I still think it is possible to use them properly to gain additional objective knowledge on a candidate's level of expertise provided the test is done in a controlled environment ensuring that all taking it stand on equal footing.

Thus I went with the answer that best reflected this view keeping in mind that it is still just an hour long 50ish multiple choice question to evaluate skills and knowledge that take years to acquire.  To be taken with a grain of salt !

In short, the tests have value but whether or not they are worth the money is another debate.

Thanks all for your time.

答: Working as a technical lead at NASA on the Space Station, it became necessary for me to become certified in IT Security as well as Solaris Sys Admin.  NASA required a Brainbench certification at that time, and paid for the three certs I was required to take.  This in and of itself speaks volumes as to the opinion NASA has for Brainbench.  Since then, I have lost my certs after 3 years, and now NASA does not pay for certifications, and even my employer will not pay for them, so since I have to pay for it out of pocket, I find their prices reasonable.  Note that most certification sites do not meet the criteria for reimbursement from employers, since they do not issue CEUs, and do not have traditional accreditation.  My employer will pay for prepping for the exam, but not for the exam itself.  The yearly subscription at Brainbench is a great deal, if you need multiple certifications ($199 normally, but I got it on-sale for $99.50).  Their single certification costs is $49.  By comparison, if you want an MSCE for instance, that will cost $72 if you use the outfit recommended by Microsoft.  Brainbench requires an extra $15 for a nice printed certificate, so the total price is normally about $65 with certificate.  The subscription allows you to take as many certs within one year as you want, but you still have to pay the $15 for the certificate.  The tests generally are difficult, and certainly demonstrate the proficiency of the test taker.  </p>


问:
How do I make a cloud based web app accessible internally in the event of an internet outage?
I have a Java Web application backed by a database. Both are hosted in Amazon EC2. If the Internet is down, I need to allow internal users to be able to continue to work and somehow update the hosted service when the Internet is available again. Is this possible? How would I design such a solution.</p>

答:
When dealing with a web application there are two components of primary interest - the server and the network.

A java web application runs in an application server (this is an application such as jBoss, Weblogic, or self contained jetty) on a server itself (linux, windows, etc...).

If the application server is not running, the applications within it are not running and you will not be able to connect to them.  This is true no matter if the applications within them are providing web services or more traditional web pages.

If the server itself is down, the applications running on the server (the application server, database and the like) are not running.

If the network between you and the server is down then, well, the network is down and you cannot connect to the applications (no matter if they are running or not).

The standard approach to dealing with the server is down is redundancy - putting the application on multiple servers so that if one fails to connect it will attempt to connect to another one.  This does not guarantee that it will always work (a network outage in a wide enough area or a cascading problem in cloud computing can take multiple systems off line).

The specifics of how much and what redundancy are necessary depends on a given application's requirements.  Some people need 99.999% uptime, some just need 99% uptime (and wait for the network or the system to correct itself rather than investing in additional redundancy).

Remember that when planning for redundancy it is likely necessary that multiple components will need to be redundant.  If one has multiple redundant web applications all using the same database, and the database goes down you still have a single point of failure with the database.

Ok, so lets say the network has gone down after you have loaded the page.  You are now offline.

Html 5 provides the possibility for having some amount of local processing.  Note that this means that you can only work with the code and data that you have on the machine.  If the business logic for the application is hosted on the cloud it would mean that when the cloud is unavailable, that portion of logic is unavailable.

Some resources for html 5 offline applications:

http://www.ibm.com/developerworks/library/wa-offlineweb/

http://diveintohtml5.info/offline.html

http://www.w3.org/TR/offline-webapps/

A google search for "html5 offline web apps" (and related queries) will provide more resources.


答:
I would be extremely careful blindly following current design patterns. Of course, when there is no appreciable downside, one should always attempt to follow similar patterns across the code base.

However, it's far too easy to get into circumstances where the majority of developers feel as though it's "best practice" to following the existing bad patterns leading to situations where good developers are writing bad, unmaintainable code.

On the other hand, consistency is important. When dealing with enormous code bases, it's extremely useful to try to follow similar patterns so that even though developers have not read every inch of the code base, they know what to expect.

Therefore, I believe it's best to establish and update guidelines about what patterns developers should follow if able. This way, any new code is consistent with other new code.

Title: What's the right balance between code consistency and code improvement?

Body:
Recently I had a discussion with a colleague regarding code style. He was arguing that your usage of APIs and the general patterns you are using should be as similar as possible with the surrounding code, if not with the the codebase as a whole, just as you would with code appearance (brace positioning, capitalisation etc). For example if I were adding a method to a DAO class in C# I would try to use LINQ where appropriate to help make my code clean and easy to maintain, even if none of the other methods in that class were using it. However, my colleague would argue that I should not use it in that instance because it would be against the existing style of that class and thus harder to understand.

At first I found his position rather extreme, but after thinking it over for a while I am beginning to see his point. With the hypothetical LINQ example, perhaps this class doesn't contain it because my colleagues are unfamiliar with LINQ? If so, wouldn't my code be more maintainable for my fellow developers if I didn't use it? On the other hand, if I truly believe that using such a technique would result in cleaner code, then shouldn't I use it even if it differs drastically from the surrounding code?

I think that the crux of my colleague's argument is that if we all go about implementing similar functionality in a codebase in different ways, and we each think that our way is "best", then in the end the code as a whole just gets harder to understand. However at the moment I still think that if we blindly follow the existing code too much then the quality will just slowly rot over time.

So, to what extent are patterns part of code style, and where should we draw the line between staying consistent and making improvements?


问:
"I", "We", or Neither in code documentation
I find myself writing (hopefully) helpful comments in code (C++) documentation of the type:

```<code>The reason we are doing this is...
</code>```

The reason I use "we" instead of "I" is because I do a lot of academic writing where "we" is often preferred.

So here's the question. Is there a good reason to prefer one over the other in documenting code:

Use "We": The reason we are doing this is...

Use "I": The reason I am doing this is...

Use my name: The reason [my name] did this is...

Passive voice: The reason this was done is...

Neither: Do this because...

I choose #1 because I'm used to writing that way, but documentation is not for the writer, it's for the reader, so I'm wondering if adding the developer name is helpful or if that just adds yet another thing that needs to be changed when maintaining the code.

答:
I'd go with:

#6. Declarative: ...

Rather than say "The reason this was done is because each Foo must have a Bar", just say "Each Foo must have a Bar".  Make the comment into an active statement of the reason, rather than a passive one. It's generally a better writing style overall, better fits the nature of code (which does something), and the the reason this was done phrase adds no information whatsoever.  It also avoids exactly the problem you're encountering.


答:
I prefer neither, and actually would leave off that introductory phrase altogether and just get to the point.  I also try to avoid just saying "this" because it leaves no way to tell if the comment is in sync with the code.  In other words, instead of:

```<code>// The reason this was done is to prevent null pointer exceptions later on.
</code>```

I would say:

```<code>// Frobnicate the widget first so foo can never be null.
</code>```

The fact you're adding a comment at all implies you are stating a reason, so you don't need to redundantly tell people you're explaining the reason.  Just make the reason as specific as possible, so they know as clearly as possible how to maintain that code later on.

Title: "I", "We", or Neither in code documentation

Body:
I find myself writing (hopefully) helpful comments in code (C++) documentation of the type:

```<code>The reason we are doing this is...
</code>```

The reason I use "we" instead of "I" is because I do a lot of academic writing where "we" is often preferred.

So here's the question. Is there a good reason to prefer one over the other in documenting code:

Use "We": The reason we are doing this is...

Use "I": The reason I am doing this is...

Use my name: The reason [my name] did this is...

Passive voice: The reason this was done is...

Neither: Do this because...

I choose #1 because I'm used to writing that way, but documentation is not for the writer, it's for the reader, so I'm wondering if adding the developer name is helpful or if that just adds yet another thing that needs to be changed when maintaining the code.

Body:
I prefer neither, and actually would leave off that introductory phrase altogether and just get to the point.  I also try to avoid just saying "this" because it leaves no way to tell if the comment is in sync with the code.  In other words, instead of:

// The reason this was done is to prevent null pointer exceptions later on.

I would say:

// Frobnicate the widget first so foo can never be null.

The fact you're adding a comment at all implies you are stating a reason, so you don't need to redundantly tell people you're explaining the reason.  Just make the reason as specific as possible, so they know as clearly as possible how to maintain that code later on.


问:
Which design pattern is illustrated by inheriting IStructuralComparable interface?
We know that some design patterns are found so useful that they become features of the language itself.

For instance, the interface IEnumerator which is implemented by Array object.
This helps in separating the iterator from the collection object. The internal representation of the object is encapsulated.

The pattern: Iterator Pattern

I have just come across another interface IStructuralComparable(msdn). This is used to compare the structure of two collection types using StructuralComparisons(msdn) class.

The intent of this interface seems to be thus:

My understanding is that it's used for collection like types, and
  encapsulates the structural part of the comparison, but leaves the
  comparison of the elements to a comparer passed in by the user.
  (link)
  (Got from the comments section  of the question)

Is this an implementation of any familiar design pattern?
If yes, which pattern is it?

答:
I don't believe there is a commonly used pattern to describe this.  I would think of it as "broken composite pattern", because it seems to me that they nearly use the composite pattern and if they actually used it then it would work better.

As it was implemented, you compare collections using IStructuralComparable, which requires you to pass in an IComparer to use in comparing individual elements from the two structures.  Since IComparer and IStructuralComparable are two different interfaces, you have problems if the elements of the IStructuralComparable are themselves collections, which now get compared with IComparer.  But if you prefered IStructuralComparable to IComparer at the top level, why don't you prefer it now?

If the composite pattern had been used the interior nodes (collections) would have the same interface as the leaf nodes (non-collections) and would handle recursive substructures more cleanly.  (I've actually implemented structural comparisons exactly this way).

So, to me at least the problem looks like a composite pattern, but the solution looks like "near the composite pattern but really not as good".  This must have been done for historical reasons, since lots the IComparer interface has been implemented many times in and out of the .NET framework, and a composite interface wouldn't match it.


问:
In a resume, what all constitutes a Programming Language
In your resume, what would you classify as a Programming Language? For instance, under Programming Languages (or a similarly titled section of your resume), do you list C#, Java, C and leave it at that or do you go and add XML (because, well it is eXtensible Markup Language) and XSLT and jQuery and all that too?

If you are not going to add jQuery under languages, where exactly would you put it?

One resolution to this dilemma would be put in the technologies you have used under the project, but that way, you are forcing the recruiter to go through the projects that you have done rather than giving a highlight of the technologies and languages you are familiar in.

What are your thoughts?

答:
I'm going to respond from the perspective of someone who's read resumes. This is how I read them, so YMMV as always.

When I see a resume with something like "Languages: jQuery, Django, Joomla", it's pretty much an instant round-file. I would be fine the equivalent "Languages: JavaScript, Python, PHP", with a call out that you have experience with jQuery/Django/Joomla, but the first statement makes it look like you don't actually know the difference between a framework/library and a language, and that's not really a good sign.

I accept CSS/HTML/XML/XSLT as "languages". But I don't assume you've never heard of them if you fail to mention them specifically (though I will follow up to make sure, if you make it to the phone screen), and I don't raise an eyebrow at people who have a separate "tools" section where they list markups/VCS/servers they're familiar with.


答:
Good comments are hard to write, and even the best comments are often hard to read and comprehend. If your comment is concise enough for me to absorb and precise enough to convey what I need to know about the code, it doesn't make me any difference what pronouns you use.

I would hate to discourage somebody from commenting their code because they're concerned about the case, tense, and person of their pronouns.


答:
Another idea to consider would be a well crafted unit test that demonstrates why the code works the way it does in place of writing a descriptive comment. This has a couple benefits over writing comments:

Comments do not always change when the code is changed which can lead to confusion later on.

Units tests give the maintainer a easy way to play with the code. Learning a new codebase can be a lot easier if you have individual units that you can break to observe what changes.

Even though this avenue requires more work up front, unit testing can be an excellent form of documentation.


答:
In C# (and in most documentation tools in other languages) there is a difference between documentation and in-line commentary. My personal opinion is that you should always use formal, declarative-style comments as Bobson and others suggest in the documentation of a class or member, but within the code, there's nothing wrong with being less formal. In fact, sometimes an informal comment is more effective at explaining why something is being don than a full exposition in formal English.

Here's a sample which I think illustrates the point.

```<code>/// <summary>
/// Takes data from the remote client and stores it in the database.
/// </summary>
/// <param name="data">The data to store.</param>
public void StoreData(ComplexObject data)
{
    // Don't take candy from strangers
    ComplexObject safeData = SanitizeData(data);
    ...
}
</code>```

Body:
In C# (and in most documentation tools in other languages) there is a difference between documentation and in-line commentary. My personal opinion is that you should always use formal, declarative-style comments as Bobson and others suggest in the documentation of a class or member, but within the code, there's nothing wrong with being less formal. In fact, sometimes an informal comment is more effective at explaining why something is being don than a full exposition in formal English.

Here's a sample which I think illustrates the point.

/// <summary>
/// Takes data from the remote client and stores it in the database.
/// </summary>
/// <param name="data">The data to store.</param>
public void StoreData(ComplexObject data)
{
    // Don't take candy from strangers
    ComplexObject safeData = SanitizeData(data);
    ...
}


答:
The reason I use "we" instead of "I" is because I do a lot of academic writing where "we" is often preferred.

It is a bad style, even for academic papers, unless you are trying to hide who actually decided that exact point.

As for your specific question : I wouldn't leave such comment, unless it starts with :

```<code>// TODO: clean this up, ...
</code>```

or unless it explains something very important, that might not be so clear from the code. In that case, make the comment as brief as possible.

Body:
The reason I use "we" instead of "I" is because I do a lot of academic writing where "we" is often preferred.

It is a bad style, even for academic papers, unless you are trying to hide who actually decided that exact point.

As for your specific question : I wouldn't leave such comment, unless it starts with :

// TODO: clean this up, ...

or unless it explains something very important, that might not be so clear from the code. In that case, make the comment as brief as possible.


问:
What can be used in lieu of use cases to gather requirements?
I'm a programmer currently working in rounds of meetings along with BAs and PM to gather/describe modules and functionality of our case management system; after a few meetings I saw that using 'use cases' would be a very very good fit to document many of the things and functions discuessed and/or proposed for the new system. When I suggested we needed to create 'use cases' so that we don't forget what we said/concluded and also to have programers know what they should code, the leading BA mentioned don't like 'use cases'.

What can be used to gather/document requirements when people supposed to write user requirements say they don't like 'use cases', or when you realize that they don't want to write 'use cases' to describe what the system should do?

I'm trying to find out if there's a close or effective substitution to using 'use cases' to document system functionality/scenarios.

答:
It's quite strange that the BA rejects a requirements' template without proposing another one.  Generally the BA should make suggestions about the documentation (if there aren't already accepted standards in the company), or at least inform in what format he/she will prepare the requirements.

Typically business requirement documents (or BRD) don't have a strict format, but there are some topics they should cover:

general information (purpose, references, assumptions, etc.)

business processes

requirements scope

functional requirements (can include use-cases as well)

data requirements (data volume, data conversion, etc.)

non-functional requirements (security, performance, scalability, etc.)

UI requirements

etc.

Covering all the topics above will possibly be enough to document all the decisions made during the meetings. I also suggest that in addition to describing the final decisions, you also mention why this or that decision was/wasn't made and why a certain solution works/doesn't work. This will help you avoid having the same discussions all over again.

From my experience, the BA I worked with gave us the requirements in the form of UI diagrams. Since we worked on the same project all the time, there were some conventions which we all knew and there was no need to include those in requirements every time. Along with the diagrams the functionality was described. These documents were used both by developers and the UI designer, and whenever we had questions we were welcome to ask.
After the requirements were ready and the developers have studied them, we had a planning meeting during which the PM prepared user stories and tasks.


问:
WCF Keep Alive: Whether to disable keepAliveEnabled
I have a WCF web service hosted in a load balanced environment. I do not need any WCF session related functionality in the service.

QUESTION

What are the scenarios in which performances will be best if

keepAliveEnabled = false

keepAliveEnabled = true

Reference

From Load Balancing

By default, the BasicHttpBinding sends a connection HTTP header in messages with a Keep-Alive value, which enables clients to establish persistent connections to the services that support them. This configuration offers enhanced throughput because previously established connections can be reused to send subsequent messages to the same server. However, connection reuse may cause clients to become strongly associated to a specific server within the load-balanced farm, which reduces the effectiveness of round-robin load balancing. If this behavior is undesirable, HTTP Keep-Alive can be disabled on the server using the KeepAliveEnabled property with a CustomBinding or user-defined Binding.

答:
Keep-Alive tells the client that it can maintain the TCP connection the HTTP traffic is flowing over open, rather than opening and closing it per transport.

If you're in a load balanced environment you will not be able to have reliably 'sticky' sessions* / connections with a particular server. The chance is that on each transport the message will hit a different server in the environment.

Maintaining Keep-Alive means that you'll be maintaining a connection with every server the client hits. In a high-bandwidth low-latency scenario it's unnecessary as the overhead for a new connection is neglible.

*It's not so much related to sessions as those are handled differently (cookies on the client, a centralized store in the server cluster)


问:
What is the (craziest, stupidest, silliest) thing a client/boss asked you to do?
See title, but I am asking from a technical perspective, not

Take my 40 year old virgin niece on a date or you're fired.

答:
In my case it would be a client requesting a Web App feature to "block print screen" while on the application, which makes absolutely no sense because in order to do that you have to either disable the clipboard, disable the key for the whole computer, but no, they wanted to disable the print screen key client-side (through javascript), which makes it even more senseless, on top of that no matter what you do as long as you are not affecting the whole computer functionality (which, you shouldn't), the user could work around it by just focusing another application and using print screen when the focus is on that other window.

Ridiculous.


问:
Should I check integrity in my application code or defer to the database?
At work we have a lot of code like this (pseudocode):

```<code>response form_submit(string username, string password) {
  if (  username == ""
     || username.contains(invalid_chars)
     || password.length < 5
     || ...
     ) {
    return "errors: blah blah";
  } else {
    try {
      db("insert into users(username, password) values (?, ?)", username, password);
      return "success";
    }
    catch (DBException e) {
      return "errors: blah blah";
    }
  }
}
</code>```

Some of those are enforced as constraints on the DB, some aren't. It makes more sense to me to enforce everything as DB constraints and just do

```<code>response form_submit(string username, string password) {
  try {
    db("insert into users(username, password) values (?, ?)", username, password);
    return "success";
  }
  catch (DBException e) {
    return "errors: blah blah";
  }
}
</code>```

My opinion is obvious here, but what's yours: is this kind of application-level data integrity check bad practise?

答:
In the database, you won't be able to validate the password length at all (since it's hashed and not plaintext, right? RIGHT?).

Testing for invalid characters in the username must be done before you write your INSERT statement, otherwise you're wide open to a SQL injection attack. Which would be much less likely if you used a parameterized query instead, but it's a risk you must always consider.

Redundancy in your checks is valuable, as ratchet freak pointed out.


答:
Well, all performance and redundancy considerations aside, unless .net database exceptions are more sophisticated than in every other language I've ever worked with, the simple fact of needing to construct an error message readable by non-programmers sort of necessitates the first method, unless you prefer error messages that read something like:

Error #0x4b13: Violated length constraint '>=5' for table 'Users', field 'password'.

What you'll end up doing is recreating the validation code anyway to produce a decent error message, and if you're going to recreate that code anyway, you may as well do it before you incur the expense of a database call.

Title: Should I check integrity in my application code or defer to the database?

Body:
At work we have a lot of code like this (pseudocode):

```<code>response form_submit(string username, string password) {
  if (  username == ""
     || username.contains(invalid_chars)
     || password.length < 5
     || ...
     ) {
    return "errors: blah blah";
  } else {
    try {
      db("insert into users(username, password) values (?, ?)", username, password);
      return "success";
    }
    catch (DBException e) {
      return "errors: blah blah";
    }
  }
}
</code>```

Some of those are enforced as constraints on the DB, some aren't. It makes more sense to me to enforce everything as DB constraints and just do

```<code>response form_submit(string username, string password) {
  try {
    db("insert into users(username, password) values (?, ?)", username, password);
    return "success";
  }
  catch (DBException e) {
    return "errors: blah blah";
  }
}
</code>```

My opinion is obvious here, but what's yours: is this kind of application-level data integrity check bad practise?