问:
What parts of your coding standard contribute to quality code?
In response to This Question, I ask:   What are the best parts of your coding standard?

What are the best practices that help with code quality, reliability, maintainability, readability, etc.

Please include the language, the item from the standard, and the reason it improves your code.

答:
C:  Preprocessor macro 'functions' should be in all caps

Example:    #define CUBE(x) ((x)*(x)*(x))

Reason:   When scanning code, Macros stand out from regular functions, and alert you that there may side effects a normal function call would never have, like changing the value of the "input" argument, or having it evaluated 3 times.


问:
Is there any way to use Python to replace Flash for in browser animation, gaming, whatever?
Is there any way to use Python to replace Flash for in browser animation, gaming, webapps, whatever?  Pretty straight-forward IMHO.  Does anyone know how to do this?</p>

答: Pythagras' comment is basically accurate.  Python is a server-side language, like PHP or C#.  Flash is a client-side language like JavaScript.  You'd need to create a Python plug-in or translator to use it client-side. Fortunately, someone else already has: check out Skulpt.  </p>

ContentLicense: CC BY-SA 2.5


问:
What are the warning signs of impending doom to watch out for on a project?
Having worked on a failed project is one of the few things that most programmers have in common, regardless of language used, industry or experience.

These projects can be great learning experiences, soul-crushing disasters (or both!), and can occur for a multitude of reasons:

upper management change of heart

under-skilled / under-resourced team

emergence of superior competitor during dev cycle

over/under management

Once you've worked on a couple of such projects, is it possible to recognise at an early stage exactly when a project is doomed to fail?

For me, a big sign is having a hard & fast external deadline combined with feature creep. I've seen projects which were well planned out and proceeding right on schedule go horribly off the rails once the late feature requests started to roll in and get added to the final "deliverable". The proposers of these requests earned the nickname of Columbo, due to rarely leaving the room without asking for "just one more thing".

What are the warning signs you look out for that set off the alarm bells of impending doom in your head?

答: A project, and future projects are doomed when the company decides to write an in-house "framework" because all the available frameworks don't fit their need perfectly.</p>


问:
What is the "default" software license?
If I release some code and binaries, but I don't include any license at all with it, what are the legal terms that apply by default (in the US, where I am). I know that I automatically have copyright without doing anything, but what restrictions are there on it?

If I upload my code to github and announce it as a free download / contribute at will, then are people allowed to modify and close source my work? I haven't said that they cannot, as a GPL would, but I don't feel that it would by default be acceptable to steal my work either.

So what can and cannot people do with code that is freely available, but has absolutely no licensing terms attached?

答:
Without a license, companies and individuals may be reluctant to use your code, because you don't grant them specific rights to do so.

Even when you put the code into the public domain, you are granting rights to use.  So you might as well make a statement of acceptable use that is acceptable to you.

Without such a statement or license, there is nothing preventing people from using your code in whatever way they see fit.  There is, of course, nothing preventing bad people from violating your license, but most good people and companies will respect your terms if you tell them what those terms are.

In short: you should have some form of license, even if that license grants unrestricted use.

ContentLicense: CC BY-SA 3.0

Title: What is the "default" software license?


答:
IANAL, TINLA, HAA.

Depending on the size of the posted code, most people just assume it's public domain, though that's not actually the case. (It's actually not possible to dedicate a work to the Public Domain in the US.)

For small code snippets - like just a single small function or an algorithmic example - any use would be a fair use since it's too small to be considered a "Work."

For larger snippets - small libraries, for example - no one can really make an assumption. Most programmers will probably assume it's free for use, but organizations will be hesitant to give it a look.

My suggestion is to just put a little preamble that summarizes the terms of use. If I want others to use it, I might simply say, "This code is free for any use," and leave it at that.

Title: What is the "default" software license?

Body:
If I release some code and binaries, but I don't include any license at all with it, what are the legal terms that apply by default (in the US, where I am). I know that I automatically have copyright without doing anything, but what restrictions are there on it?

If I upload my code to github and announce it as a free download / contribute at will, then are people allowed to modify and close source my work? I haven't said that they cannot, as a GPL would, but I don't feel that it would by default be acceptable to steal my work either.

So what can and cannot people do with code that is freely available, but has absolutely no licensing terms attached?


答:
The purpose of a copyright license is to give the licensee rights he would not otherwise have. Without a license, the only rights remaining are the ones guaranteed by copyright law, which are basically none.

Without a license, you aren't even allowed to download the code, since that implies making a copy, which is forbidden by copyright law. You cannot distribute it, since that implies making a copy. You cannot even run it, since that implies copying it into RAM.

However, you wrote:

If I […] announce it as a free download / contribute at will […]

That is a license. Or at least, it may or may not be construed as one.

So what can and cannot people do with code that is freely available, but has absolutely no licensing terms attached?

Nothing. Well, almost. Nothing interesting, certainly.

There are certain fair use rights, that would allow someone to quote parts of the code in a scientific research paper, for example, or to make a parody (but not a satire) of your code.

Title: What is the "default" software license?


问:
What syntax element do you hate most in a programming language you use frequently?
No matter how much you love a programming language, there are always a few details in it that aren’t quite as nice as they could be.

In this question, I would like to specifically focus on syntax elements. In a programming language that you use frequently (perhaps your favourite programming language, or perhaps the one you are forced to use at work), which syntax element do you find most unreadable, unclear, inconvenient or unpleasant?

答:
Redundant parameterization in Java:

```<code>HashMap<String,HashMap<String,String>> foo = new HashMap<String, HashMap<String, String>>();
</code>```

What other type parameterization does the compiler think foo could have?

Body:
Redundant parameterization in Java:

HashMap<String,HashMap<String,String>> foo = new HashMap<String, HashMap<String, String>>();

What other type parameterization does the compiler think foo could have?


问:
Which back-end web programming language to use
I have a project where I will be collaborating to build a fairly simple site with some database access. I will be doing the back-end work, and my colleague will be doing the web design. The problem is that my colleague has only worked with PHP developers and I have a lot more experience in Perl. The options would be to either learn PHP while doing the project or for my colleague to learn how to design around Perl. (I guess a third option would be to decline the project because this obstacle is just too insurmountable).

If the answer is to use Perl, the next question is which templating module would be easiest for my PHP-aware web designer colleague to adapt to. HTML::Mason? HTML::Template? Something else?

答: If you design your application properly, with adequate separation of presentation and content, you can bring in your web designer, who can provide you with the needed CSS and graphics, and it shouldn't matter what language you develop the backend in.


答: You can use IronPython (an implementation of Python on .NET) to create Silverlight applications.  Silverlight is a plug-in like Flash, and you can do essentially the same things with it (the installed base is smaller, although no-one really knows exactly what the numbers are).</p>

Title: Is there any way to use Python to replace Flash for in browser animation, gaming, whatever?

Body: Is there any way to use Python to replace Flash for in browser animation, gaming, webapps, whatever?  Pretty straight-forward IMHO.  Does anyone know how to do this?</p>


问:
What is abstraction?
Is there a generally agreed upon definition for what a programming abstraction is, as used by programmers? [Note, programming abstraction is not to be confused with dictionary definitions for the word "abstraction."] Is there an unambiguous, or even mathematical definition? What are some clear examples of abstractions?

答:
Abstraction is when you ignore details deemed irrelevant in favor of those deemed relevant.

Abstraction encompasses encapsulation, information hiding, and generalization. It does not encompass analogies, metaphors, or heuristics.

Any mathematical formalism for the concept of abstraction would itself be an abstraction, as it would necessarily require the underlying thing to be abstracted into a set of mathematical properties! The category-theory notion of a morphism is probably closest to what you're looking for.

Abstraction is not something you declare, it is something that you do.

Title: What is abstraction?


问:
What is the best C++ interview question?
If you could ask a C++ programmer one question to measure their C++ skills, what would it be?

The question I think is best is: Can you call "delete this;" inside a member function? (I put this as a link so you can think it through first, then go to The Best C++ Interview Question – Ever! to see the correct answer.)

I don't ask this because I expect most people to know the answer. If they did it would not be that useful a question. I ask to see if they can work their way to the correct answer and how they do so.

答:
I would actually present the person with a bit of code from another programming language that was object oriented and preferably not on the list of languages they know. The code should represent a simple task done in that language.

The point of this would not be to determine their knowledge of C++ but find out how well they understand programming. When you understand the basic concepts behind programming, then you can solve problems.


问:
Separate servers vs local machine for builds, issue tracking etc on solo project
For solo projects, do you keep your build / management tools on your local machine, or on a separate server? If the server is not guaranteed to be safer or more reliable than my own machine I struggle to see the point, but maybe I'm missing some things.

Note that I'm not debating the value of continuous integration or having a staging environment etc.. just the question of whether it exists on separate hardware.

答:
I'm primarily a C/C++ guy who does telecommute projects on Linux, Mac OS X, and Windows.

All my development machines at home are on a gigabit Ethernet LAN which also includes a Linux server that doubles for source control (Perforce and git) and issue tracking/wiki (Redmine).

Why have a separate server?

The more copies of the source there are, the less likely it is I'll be in pain if there's a hardware failure.

My Internet firewall forwards key ports to the server, so I can travel and get to all my important stuff without compromising my LAN. I've pulled a complete set of sources onto a laptop from a Starbucks.

I can keep all my development machines' sources synchronized.

It really doesn't take much horsepower to set up a Linux server to do this. I'm using a first-gen Intel iMac with a dinky hard drive and anemic CPU. It would be inadequate for most things and would probably gather dust in our crawl space, but it runs great with Ubuntu Maverick for this purpose.


问:
Metric by which to hold developers accountable
I asked a question on lines of code per hour and got torn a new one.  So my matured follow-up question is this:

If not lines of code, then what is a good metric by which to measure (by the hour/day/unit-of-time) the effectiveness of remote programmers?

答: You need an experienced developer or teamleader (who is not associated with those remote programmers) to estimate how long some task may take, and the effectiveness is measured by comparing their required time against the estimates. To be sure that the estimates are good, you could randomly pick a few tasks and have them executed by an in-house team you have under control.</p>


答:
C#: Use Extract Method instead of comments

If we felt like we needed to add a comment to a block of code to explain what it's doing, instead we would extract that code into a new method with a descriptive name.

This makes the code more readable and modular, and reduces the number of (out-of-date) comments floating around.

Title: What parts of your coding standard contribute to quality code?

Body:
In response to This Question, I ask:   What are the best parts of your coding standard?

What are the best practices that help with code quality, reliability, maintainability, readability, etc.

Please include the language, the item from the standard, and the reason it improves your code.


答:
The only metric I use is the amount of working software he produces for a given amount of money I invested.

Regardless its schedule, if she/he work remotely or not, number of pauses he/she takes, methodologies she/he uses or number of working hours.

By working software I mean:

List of features defined by user/customer that meets the required quality level

By amount of money:

How much the user/customer paid for the defined features + maintenance costs

So it has a direct on how it is built and quality of work produced but not bound to any source code line metrics.

Title: Metric by which to hold developers accountable

Body:
I asked a question on lines of code per hour and got torn a new one.  So my matured follow-up question is this:

If not lines of code, then what is a good metric by which to measure (by the hour/day/unit-of-time) the effectiveness of remote programmers?


答:
Explicitly mentioning the copyright in your work was an obligation in the past. It is no more required.

If the country you are in is a member of berne convention, then it's automatic. You have the full rights on your work.

The only exception to this is when your work is used in the context of "fair use". For example, I can copy/paste portion of text from internet or a book to illustrate what I explain. That's what I'm going to do right now, I'm fearless...

Copyright does not prohibit all copying or replication. In the United States, the fair use doctrine, codified by the Copyright Act of 1976 as 17 U.S.C. § 107, permits some copying and distribution without permission of the copyright holder or payment to same. The statute does not clearly define fair use, but instead gives four non-exclusive factors to consider in a fair use analysis.

This is from WikiPedia.

However, not explicitly mentioning the copyright may make some companies not very well informed on their rights & obligations to use your code in good faith.

You want to avoid all the paper work to force them to stop using your code, so as a general rules, even if it's not an obligation:

Add copyright statement in each source code file. Attach the full license to the project.

Title: What is the "default" software license?


答:
Some ideas:

features implemented

bugs fixed (also account for bugs later re-opened by QA)

user complaints resolved (note that it's not the same as 2 - one serious bug may be pain in the neck while 100 typos may not be that important)

Also may want to track:

Code coverage by tests

Code coverage by internal documentation

Feature coverage by external (user) documentation


问:
What are some good examples of using pass by name?
When I write programs I using pass by value or pass by reference always seem to be logical methods. When learning about different programming languages I came across pass by name.

Pass by name is a parameter passing method that waits to evaluate the parameter value until it is used. See Stack Overflow pass by name question for more information on the method.

What I would like to know is: what are some good examples and/or reasons to use pass by name and should it be re-introduced into some more modern languages.

答:
Some of the advantages are described in a description of pass by name linked to in your linked question's answer.

The advantages of pass-by-name are (paraphrased from the article):

It has a simple semantic model as textual substitution.

Modification and re-evaluation of argument expressions has useful applications, such as Jensen's device. (Ed: Described in the second section)

Argument expressions are not necessarily evaluated. Here, y is not evaluated if x is false:

```<code>boolean procedure and (x, y);
  boolean x, y;
begin
    if x then return y else return false
end;
</code>```

Would I use it?

I see no reason to, even considering the advantages put forward. Pointers and short-circuit evaluation prevent expression evaluation as much as I need it, and I'm quite happy with the semantic models I use regularly.

Body:
Some of the advantages are described in a description of pass by name linked to in your linked question's answer.

The advantages of pass-by-name are (paraphrased from the article):

It has a simple semantic model as textual substitution.

Modification and re-evaluation of argument expressions has useful applications, such as Jensen's device. (Ed: Described in the second section)

Argument expressions are not necessarily evaluated. Here, y is not evaluated if x is false:

boolean procedure and (x, y);
  boolean x, y;
begin
    if x then return y else return false
end;

Would I use it?

I see no reason to, even considering the advantages put forward. Pointers and short-circuit evaluation prevent expression evaluation as much as I need it, and I'm quite happy with the semantic models I use regularly.


问:
How do you go about training a replacement?
I recently asked about leaving a position and got a lot of great answers. One of the common threads was that being around to train the new person would be expected and could go a long way.

Now considering that (I think) most people don't stay at a company for a long time after they've given notice, and it will take time for the company to interview/hire one - that leaves for a short amount of time to get someone up to speed.

I've also never trained anyone before. I did a bunch of tutoring in University and College, but teaching a language/technology is far different from training someone to replace you on your job.

So the question is: how do you go about training someone to replace you in a, potentially, short amount of time?

答: Assuming your company doenst hire an absolute dud as your replacement then one of the key things is the domain of the applications that are being handed over. It might be a big assumption to make but you can't teach someone how to code good in a couple of weeks - they either have that down or don't, so the key thing is the domain imo.</p>


问:
What is the preferred way to hold a file over multiple requests in MVC
I am building a wizard and the first step of this wizard is to let the user select a file. In the following steps I need this file to display some data from it and as a final step I have to import some content of the selected file.

How can i preserve this file along the steps?

I can save the file on the server in a temp dir (and make sure it is linked to the user's session, so that no other import session will intervene).
I can save the file in the session state (Viewbag maybe?)
What would you do?

Edit:

The size can vary from 100kb - 10mb

答:
In general, holding a file open between user requests is not a good idea. There are several problems:

The session can time out, leaving the file in limbo. In a busy system, this can lead to file handles running out.

Many "enterprise" quality web containers serialize your session to a database when they are busy. You don't say what language you are using, but the Java File class is stateful and not Serializable, so you have a problem.

In a web farm environment, your next request may not be handled by the same server, so the file would have to be on a drive shared across the farm.

If you are unlucky, several users may want to access the same file concurrently, giving you some difficult synchronisation problems.

So what are the options:

If the file is small, you may be able to store the data in the session and write it out only on the final submit. But a 10MB file is a bit big for this option.

Rather than a file, you could persist the data to a database. Record locking, transactions etc are bread and butter features of databases, so a lot of the synchronisation problems just go away.

There are platform-independent ways of locking a file, but these are a bit arcane. One approach is to use a second "lock" file that contains nothing but the process ID of the file "owner". This gets tricky with web clients, as generally the web container will use a thread pool to service requests.

If you know you are always going to deploy on the same platform, most OS's provide platform specific semaphores and the like. You might find a library for your language that supports these.

Personally I would go for using a database...


答:
Stop coding immediately. Let the new guy do your day-to-day job and be there to answer his questions.

There is no better way to learn than doing.

Title: How do you go about training a replacement?

Body:
I recently asked about leaving a position and got a lot of great answers. One of the common threads was that being around to train the new person would be expected and could go a long way.

Now considering that (I think) most people don't stay at a company for a long time after they've given notice, and it will take time for the company to interview/hire one - that leaves for a short amount of time to get someone up to speed.

I've also never trained anyone before. I did a bunch of tutoring in University and College, but teaching a language/technology is far different from training someone to replace you on your job.

So the question is: how do you go about training someone to replace you in a, potentially, short amount of time?


问:
Best approach for storing huge data
I'll be handling 300,000+ users. Each user (after logging in) will be able to create lets say "folders", in each folder, users will create "name=value,name2=value2,name3=value3" entry pairs. Each name won't be more than 260 chars and each value won't be more than 1024 bytes. All readable characters.

My ideas for possible approaches:

Create tables called userentries_[first letter of username] so there will be 26 tables, each table will have entries and user ID. So when I want to retrieve user data, I'll do

```<code>select * from userentries_[firstletter] where userid= $UID"
</code>```

Create a single table to hold all information.

Create a table called userdata, here I'll have UID and FileName. So when user wants to retrieve data, I'll read database to find the name of file, then open FileName in PHP, create an XML/JSON response and client (which will be android/ios/desktop app) process it.

Which one is the best and most optimized (speed/performance vise) ?

P.S. name=value pairs etc. won't be searchable, even if user supposed to search through them, it will be in client-side, definitely not on DB

答:
You may want to consider not using SQL at all, but use something like Azure table storage.

Troy Hunt has an interesting article on its performance on huge datasets: http://www.troyhunt.com/2014/12/applied-azure-infographic-of-how-have-i.html

Title: Best approach for storing huge data


问:
Is there ever a reason to use an array when lists are available?
It seems like List<T> in C# can do everything an array can do and more, and seems also just as efficient in memory and performance as an array.

So why would I ever want to use an array?

I'm obviously not asking about cases where an API or other external constraint (i.e. the Main function) requires me to use an array... I'm only asking about creating new data structures in my own code.

答:
Here's some guidance you can use on when to select Array and when to select List.

Use Array when returning from a method.

Use List as the variable when you are constructing the return value (inside the method). Then use .ToArray() when returning from the method.

In general, use an Array when you don't intend the consumer to add items to the collection. Use List when you intend the consumer to add items to the collection.

Array is meant for dealing with "static" collections while List is meant for dealing with "dynamic" collections.


答:
The question can be reworded as "I have the canonical perfect application for a nosql key-value store, what should I do?". Yes, this can be done with sql, but a nosql implementation is likely to be more efficient.

Look at systems like riak, apache cassandra, berkeley db or memcachedb, or if you're planning on deploying to amazon web services dynamodb. Or perhaps consider a more traditional database with either memcache or redis as a cacheing layer.

Title: Best approach for storing huge data

Body:
I'll be handling 300,000+ users. Each user (after logging in) will be able to create lets say "folders", in each folder, users will create "name=value,name2=value2,name3=value3" entry pairs. Each name won't be more than 260 chars and each value won't be more than 1024 bytes. All readable characters.

My ideas for possible approaches:

Create tables called userentries_[first letter of username] so there will be 26 tables, each table will have entries and user ID. So when I want to retrieve user data, I'll do

```<code>select * from userentries_[firstletter] where userid= $UID"
</code>```

Create a single table to hold all information.

Create a table called userdata, here I'll have UID and FileName. So when user wants to retrieve data, I'll read database to find the name of file, then open FileName in PHP, create an XML/JSON response and client (which will be android/ios/desktop app) process it.

Which one is the best and most optimized (speed/performance vise) ?

P.S. name=value pairs etc. won't be searchable, even if user supposed to search through them, it will be in client-side, definitely not on DB


答:
Use a caching mechanism that is independent of the stateless queries run by the user. Much in the same way database connections are pooled - ie you never open a new DB connection apart from the first time, every subsequent 'open' really fetches a previously used connection from a cache inside the DB client driver.

You need to determine a method for handling the file's lifetime, maybe closing it after a minute or so of inactivity but it allows you to treat each access of the file as an entirely new operation from each request and have it perform acceptably.

That said, the OS already performs an amount of file caching so the system may perform very well if you repeatedly re-open the same file within a short amount of time (ie before it exits the OS cache) without having to bother doing anything.

Title: What is the preferred way to hold a file over multiple requests in MVC

Body:
I am building a wizard and the first step of this wizard is to let the user select a file. In the following steps I need this file to display some data from it and as a final step I have to import some content of the selected file.

How can i preserve this file along the steps?

I can save the file on the server in a temp dir (and make sure it is linked to the user's session, so that no other import session will intervene).
I can save the file in the session state (Viewbag maybe?)
What would you do?

Edit:

The size can vary from 100kb - 10mb


问:
Suitable software development method/model for R&D Projects
For Research and Development (R&D) project, what type of software development method / model more applicable/suitable?

For example, my recent R&D project has several parameters:

Requirement changes based on output of research.

Need to maintain High Level Documentation, Detail Level Documentation and others.

Need to develop prototype to show visible output to investors.

答:
Getting the original investment

According to my experience, the most difficult part is to get the original investment, because investors may be reluctant to give you money with no commitment from your side. What if your research leads to a dead end? What if it requires much more money than they can give you? Ordinary business projects, even Agile ones, are somehow more certain, for two reasons:

While the customer can't know in advance if it will cost $40 000 or $50 000, he probably knows that it will not cost $800 000 nor $1 000. In research-oriented projects, we often have no idea whatsoever how much would it cost.

In business projects, if a twelve-months project is canceled after four months, there should be a “working something” which may not meet the needs of the customer, but which can still be deployed in production and bring some money in.

In research-oriented projects, if after several months or years the project is canceled, there often will be nothing the investors will be able to use to get part of their money back.

This is very similar to Waterfall projects: unless the project is completed, time and money is simply wasted.

Note that this is a generalization. Some R&D projects can be very specific and predictable. Another example: I'm currently working on a project which is unrelated to research, but which didn't have a precise scope at the beginning, but rather a “we'll do whatever appears to be actually valuable and will release it whenever we'll finish it” spirit. Totally acceptable for me—I'm acting as both the investor and the implementer here, but not doable when you need to attract external investors.

Tracking project progress

Once you've convinced the investors to give you money, the next thing is to track project progress in order to manage risks and give precise feedback to your investors.

Here, R&D project is not much different from business projects with no up-front requirements, so any Agile methodology should work. With short iterations, you can track your progress while not knowing exactly your final destination. The difference compared to ordinary non-research projects is that the uncertainty doesn't come from customers who are not sure what they needs are, but the research aspect of the project.

You may also want to read about evolutionary prototyping (including the comments). The difference between evolutionary prototyping and ordinary Agile is that you don't have to deliver a fully working product at each iteration. Instead, every prototype you deliver can also contain some more or less broken features.

This makes it more attractive for R&D projects where you can be stuck for long periods of time on a particular aspect of your product, and not being able to deliver anything fully functional during several iterations. Given the uncertainty of the project, you'd rather show some progress, even inconclusive, than remain silent for several months.


问:
Do compilers attach the Garbage Collector to the final executable?
Since the Garbage Collector is part of the language implementation (not OS, etc.), does the compiler has to attach the GC to the final executable? Or is it like a dependency that has to be already available on the target machine?

If it's attaching the GC, then should I think of it as a Wrapper around my application that once in a while stops the execution, does some clean-ups, recovers the state of the application and let it continue the execution?

Also I think some languages like Java have their own GC included in their VM. In that case I'm only talking about languages that directly compile to the machine code and don't need any VM to execute.

答:
In D the standard runtime that gets linked in during compilation includes the implementation of the GC.

How the GC does the inspection of the program state depends on implementation. There is a stop-the-world type that uses a system call to suspend all program threads and lets the GC thread inspect the program without worrying about other threads invalidating the inspection (the mark fase, the sweep can work concurrently because you just proved no other thread will access the memory you are freeing).

However concurrent GCs exist that can do the inspection while the program is running; though that usually requires some support from the program threads.


问:
Should I use ASP .resx resources if the website is available in a single language?
Is it a best practice to always store strings in ASP .resx resources files, even when the application is not localized according to the user culture ? (Web pages will be displayed in french.)

Is there reasons for using resources other than provide pages in different languages easily ?

In favour of resources, something "smells wrong" or "seems ugly" about writing code that mix HTML, ASP/Razor and hard-coded strings :

```<code>@Html.LabelFor(Model.FirstName, "Votre prénom :");
...
<input type="submit" value="Modifier votre profil" />
...
<div class="error">Une erreur est survenue</div>
</code>```

Or worse, mixing .NET/C# code and hard-coded strings :

```<code>[Display(Name = "Le salaire actuel de l'employé")]
public int Salary { get; set; }
</code>```

In favour of hard-coded strings, using resources when they aren't needed is consequent extra-work for the developer and (seems to) violate YAGNI.

答:
There is no definite answer. Personally I'm strongly against internationalizing when you don't need it. I have done tons of corporate web sites and I can say for sure that doing internationalization consumes more time than you imagine at first. Event when using more advanced and less tedious methods than resource file provides.

Keep in mind, that you can have some kind of text's in database, deep in your backend, JS validation messages, etc. Not everything is translatable with resources.
And don't forget cases when user browser has different culture than your server (i.e. 0,3 is validates in browser, but fails in backend).

Having text hardcoded in your view models and using fixed culture is real joy and relaxation  :)


答:
In 16 years I've never actually found a workable metric of the sort you're looking for.

Essentially to be useful anything would need to be measurable, representative and ungameable (that is the system can't be played by clever developers).  There are simply too many variables within software development to make it measurable as piece work in this way.

The closest you get is progress against estimates - that is how many tasks are they completing within the agreed estimates.  The trick here is (a) getting good and fair estimates and (b) understanding where estimates have been exceeded for good reasons for which the developer can not / should not be blamed (that is something was genuinely more complex than anticipated).  Ultimately if you push developers too hard you're likely to find estimates gradually creeping up to a level where they're always met not because of increased productivity but because of padded timescales.

Go the other way too much in terms of the estimates (reducing them to create pressure to deliver) and you create phoney deadlines which studies have shown don't increase productivity and are likely to have an impact on team morale (see Peopleware for more information).

But essentially I wonder if you're looking at a slightly false problem.  Why are remote programmers different to other programmers when it comes to measuring productivity?  How do you measure the productivity of non-remote programmers?

If it's about not trusting them to work remotely then that's basically a wider trust issue.  If you don't trust them to work from home then you either need to establish that trust, not let them work from home, or find some way of satisfying yourself that they are indeed working when they're meant to be.


问:
Is it OK for an interface to only communicate half of how something should work?
I have a service where certain other services can report their status to. By status I don't mean whether they are running or not, but whether they have received data. The point is that other services can ask if data they need has been received.

I have two possible options of implementing this.

One is as follows:

```<code>public interface IDataPrerequisiteFulfillmentService
{
    bool ArePrerequisitesFulfilled(params DataPrerequisite[] dataPrerequisites);
    void ReportDataPrerequisiteFulfilled(DataPrerequisite dataPrerequisite);
}
</code>```

However, that would mean I would need an extra dependency in any service that needs to report to this service. Some services already have multiple dependencies and I like to keep dependencies to a minimum.

Another way to approach this would be to do the following:

```<code>public interface IDataPrerequisiteFulfillmentService
{
    bool ArePrerequisitesFulfilled(params DataPrerequisite[] dataPrerequisites);
}

public interface IDataPrerequisiteService
{
    event EventHandler<DataPrerequisiteEventArgs> PrerequisiteFulfilled;
}

public class DataPrerequisiteFulfillmentService : IDataPrerequisiteFulfillmentService
{
    private IList<DataPrerequisite> fulfilledPrerequisites = new List<DataPrerequisite>();

    public IDataPrerequisiteFulfillmentService(IEnumerable<IDataPrerequisiteService> services)
    {
        // receive services via injection
        foreach (var service in services)
        {
            service.PrerequisiteFulfilled += (s, e) =>
            {
                _fulfilledPrerequisites.Add(e.DataPrerequisite);
            }
        }
    }
</code>```

I prefer option 2. It also inverts the dependencies. However, it makes for an interface that doesn't communicate the fact that the implementation of IDataPrerequisiteFulfillmentService will also need input.

```<code>    public bool ArePrerequisitesFulfilled(params DataPrerequisite[] dataPrerequisites)
    {
        // check _fulFilledPrerequisites here
    }
}
</code>```

Is it ok to have an interface that only communicates half of how the implementation works?

答:
It is absolutely fine to have an interface that doesn't communicate how the implementation works. In fact that is the point of an interface, to hide implementation details!

Your second option is fine in this scenario.


问:
Matrices calculations on partial shape matching
I'm working in a shape recognition project where it is supposed for me to develop an application that receives two images: an original one and a sketch made by a user. I am supposed to detect contours of the two images and find the best match in the original image corresponding to the sketch made by the user.

I already have the contours of the image and sketch and I need to find the best match of the sketch in the image, disregarding translation, rotation, scaling and occlusion.

I've searched some of the literature on this subject and found this paper (http://www.icg.tugraz.at/Members/donoser/donoseraccv2009pdf) that seems very promising to accomplish what I want. In Java, I have succeeded in calculating the shape descriptors (matrix of angles between points), however i'm having trouble understanding how the matching algorithm is supposed to work.

On section 2.3, they state that we have two matrices, A1 with size M x M and A2 with size N x N and that for this example, M <= N. They explain that "In terms of comparing two descriptor matrices this equals to finding r×r sized blocks starting at the main diagonal elements A1(s,s) and A2(m,m) of the two descriptor matrices which yield a small angular difference defined by:"

"And to find such blocks all different matching possibilities and chain lenghts have to be considered and the brute-force method becomes inefficient for larger number of points."

Then, they say they use N integral images (that I've already understand how they work) each of size M x M are built for N descriptor difference matrices:

Here is where I am lost. What does n mean? And for example, if M=4 and N=5, how do you create 5 integral images of size 4 x 4 with different data? This notation is strange to me and I can't figure out what they are explaining. Is that how they calculate the integral images?

Maybe I'm just on a dumb day and can't figure this out without bumping my head on the wall :P
Anyhow, I would be very grateful for someone who enlightens me and explains this to me like I'm 5 years old.

Thank you for your attention.

答:
n appears to be a free parameter in the equation for M^{n}_D.  That is, this equation is defining N difference matrices for n=1:N, quoting from the paper:

"The difference matrices M^{n}_D represent the N possibilities to match the point
sequences onto each other."


问:
Design pattern for composition workflows
Please bear with me as I find this tricky to articulate exactly what I am after (probably not a good sign..).

I have several services set up which can be combined in a particular order to create workflows. For example, imagine I have the following services:

1) HTTP -> File Store (takes a file over HTTP and stores it)

2) FTP -> File Store

3) File Store-> FTP (takes a file over HTTP and pushes to FTP)

4) File Store-> Transformation -> File Store(applies a transformation to a file in File Store).

I might want to combine services to create a particular workflow, for example.

1) -> 4) -> 3)

Or

2) -> 4) -> 3)

And it might be the case that I perform exactly the same operation e.g. in the workflows above, step 4 could be applied on the same item twice, if the same item is sent over HTTP and FTP. I might also want to trigger subworkflows for example:

4) -> 3)

Would be a valid workflow. Is there a  design pattern/known approach to handling these 'cascading' workflows? I would like to avoid duplicate operations where possible but also design workflows in a separate, contained manner. The only thing that comes to mind for me is some sort of composition based approach where workflows are composed of several sub-workflows.

I hope this makes sense!

答:
Not sure really whether this will help but in F# you could create a computation expression something like the following,

```<code> let workFlow =
      workflow {
         let! pageContents = ("read url", readHttp "http://www.google.com")
         do! ("write file", writeFile @"c:\temp\google.html" pageContents)
      } |> runWorkflow
</code>```

This can be built from the following functions

```<code> let runStage (name, f:Async<'a>) =
     async {
         try
             do printfn "Running %s" name
             let! result = f
             return Choice1Of2(result)
          with e ->
             printfn "Stage %s failed %A" name e
             return Choice2Of2 e
     }

 type WorkflowBuilder() =
     member x.Bind((name,curr), next:('a -> Async<'b>)) =
             async {
                     let! result = runStage (name, curr)
                     match result with
                     | Choice1Of2(r) -> return! next(r)
                     | Choice2Of2(e) -> return raise(e)
             }
     member x.Return(a) = async { return a }
     member x.ReturnFrom(a) = a

 let workflow = WorkflowBuilder()
</code>```

you can then compose simple async workflows yourself to get the desired result.

```<code> let readHttp (uri:string) =
       async {
         let req = HttpWebRequest.CreateHttp(uri)
         req.Method <- "GET"
         let! response = req.GetResponseAsync() |> Async.AwaitTask
         let sr = new StreamReader(response.GetResponseStream())
         return sr.ReadToEnd()
      }

 let writeFile (path:string) (contents:string) =
      async {
          let fs = File.OpenWrite(path)
          let sw = new StreamWriter(fs)
          do sw.Write(contents)
      }
</code>```

Of course this implementation is language specific there is nothing really stopping a translation to C# or Java. The general design pattern being used here is a monad, put simply it is just some wrapping type (in this case Async<'a>) plus, two functions (bind and return), which you can see implemented in the WorkflowBuilder type.

I should mention some work will be required to productionize this code, but the idea is more important I feel.

Body:
Not sure really whether this will help but in F# you could create a computation expression something like the following,

 let workFlow =
      workflow {
         let! pageContents = ("read url", readHttp "http://www.google.com")
         do! ("write file", writeFile @"c:\temp\google.html" pageContents)
      } |> runWorkflow

This can be built from the following functions

 let runStage (name, f:Async<'a>) =
     async {
         try
             do printfn "Running %s" name
             let! result = f
             return Choice1Of2(result)
          with e ->
             printfn "Stage %s failed %A" name e
             return Choice2Of2 e
     }

 type WorkflowBuilder() =
     member x.Bind((name,curr), next:('a -> Async<'b>)) =
             async {
                     let! result = runStage (name, curr)
                     match result with
                     | Choice1Of2(r) -> return! next(r)
                     | Choice2Of2(e) -> return raise(e)
             }
     member x.Return(a) = async { return a }
     member x.ReturnFrom(a) = a

 let workflow = WorkflowBuilder()

you can then compose simple async workflows yourself to get the desired result.

 let readHttp (uri:string) =
       async {
         let req = HttpWebRequest.CreateHttp(uri)
         req.Method <- "GET"
         let! response = req.GetResponseAsync() |> Async.AwaitTask
         let sr = new StreamReader(response.GetResponseStream())
         return sr.ReadToEnd()
      }

 let writeFile (path:string) (contents:string) =
      async {
          let fs = File.OpenWrite(path)
          let sw = new StreamWriter(fs)
          do sw.Write(contents)
      }

Of course this implementation is language specific there is nothing really stopping a translation to C# or Java. The general design pattern being used here is a monad, put simply it is just some wrapping type (in this case Async<'a>) plus, two functions (bind and return), which you can see implemented in the WorkflowBuilder type.

I should mention some work will be required to productionize this code, but the idea is more important I feel.


问:
Productivity using .Net WPF for large ERP (LOB) desktop applicatons ~1500 forms\dialogs
I am wondering if WPF will fit in my case:

We want to refactor an old legacy application written in a 4GL language with about 1500 forms\dialogs. We want to do that in .Net (desktop application), now we have to consider using WinForms or WPF to accomplish that.

From my point of view, WinForms fits better because the UI is more "data driven" than "Fancy UI driven". For developers it is easier to create such dialogs using WinForms, instead of dealing with XAML and\or Blend in terms of producitivty. E. g. the WinForms Designer in Visaul Studio is more intuitive. But maybe that's, cause I am an old WinForms developer.

What do you think? Do you have "pros" (or "cons") to use WPF for a large ERP desktop applications?

答:
WPF has fantastic data binding. XAML is a wonderful declarative syntax for describing component layout. WPF/XAML excels at data-driven GUI.

I see no technical benefit of using WinForms over WPF/XAML.

However WPF/XAML will require a recent version of Visual Studio and a time investment to learn the new API. I strongly recommend writing XAML by hand rather than trying to use
any sort of WSYWIG tool. (Designers can use Blend, but programmers should take that design and convert that to the final XAML code). You will have more control and get better results, and be able to develop much faster once you've practiced a bit.


问:
How to avoid "type dispatchers" when working with SOLID
I've realized that since I've been more and more strict about the SOLID principles, my code tends to consist of more pure data objects and a lot of "operator" classes which seems to go against oop-principles. Specifically I often end up with "type dispatchers" that maps a specific object type to a suitable operator class.

Let me take an example:

In the old world I would have a base class FinancialInstrument with a .CalculatePrice() and .CalculateRisk() method. I would derive that to OptionInstrument and EquityInstrument with specific implementations of risk and price calculations.

But due to Single Responsibility (and since there are lots of different metrics to calculate, not just prices and risks), I now have a separate RiskCalculator class and a PriceCalculator class with derived specific implementations such as OptionPriceCalculator and EquityPriceCalculator etc.

When I want to iterate over instruments and calculate prices, I need have some kind of type-dispatcher class or factory that maps instruments to correct price calculation class, which just feels plain wrong and not very object oriented. I've seen this kind of pattern emerge in my projects more and more.

Am I doing something wrong or is there a better way to avoid these "type-dispatcher" factories?

答:
This sounds like the Visitor Pattern could be helpful. It does not get rid of the dispatching code, but it is a fairly elegantly and standard way to implement dispatching. In Java-style OOP:

// an interface for anything calculatable
interface FinancialInstrument {
    // acceptVisitor makes the pattern obvious,
    // but you might want to pick a more domain-specific name.
    <T> T acceptVisitor(FinancialInstrumentVisitor<T> v);
}

class Option implements FinancialInstrument {
    <T> T acceptVisitor(FinancialInstrumentVisitor<T> v) {
        return v.visit(this);
    }
}

class Equity implements FinancialInstrument {
    <T> T acceptVisitor(FinancialInstrumentVisitor<T> v) {
        return v.visit(this);
    }
}

// an interface for all calculators
// basically, this consists of "visit" overloads that handle each type
interface FinancialInstrumentVisitor<T> {
    T of(FinancialInstrument fi); // convenience wrapper
    T visit(Option o);
    T visit(Equity e);
}

class PriceCalculator implements FinancialInstrumentVisitor<Price> {
    Price of(FinancialInstrument fi) {
        return fi.acceptVisitor(this);
    }
    Price visit(Option o) { ... }
    Price visit(Equity e) { ... }
}

class RiskCalculator implements FinancialInstrumentVisitor<Risk> {
    Price of(FinancialInstrument fi) {
        return fi.acceptVisitor(this);
    }
    Risk visit(Option o) { ... }
    Risk visit(Equity e) { ... }
}
```

<p>Example usage:</p>

<pre class="lang-java prettyprint-override"><code>PriceCalculator price = new PriceCalculator();
for (FinancialInstrument fi : portfolio) {
   doSomethingWith(price.of(fi));
   ...
}
</code>```

The visitor pattern is great whenever you want to be free to easily add new operations, but the set of objects these operations work on is fairly fixed. Note that adding one type of financial instrument requires an overload to be added to the FinancialInstrumentCalculator interface, which is not backwards compatible – all consumers of that interface will have to be updated in order to support that method. This is not the case if the new financial instrument is a subtype of an existing class, as the existing handler can be used then.

If new financial instruments turn up more often than new operations, then using the visitor pattern is probably a bad idea. Note that whatever strategy you use to match n operations to m financial instruments, you will always (subtyping ignored for a moment) end up with n·m methods to code.

If your language allows this, I highly recommend to use traits or similar constructs to provide defaults in the FinancialInstrumentCalculator interface. E.g. when I have three types

class A implements FinancialInstrument
class B extends A
class C extends A
```

<p>then the visitor methods for <code>B</code> and <code>C</code> can implemented by the visitor method for <code>A</code> by default:</p>

<pre class="lang-java prettyprint-override"><code>interface FinancialInstrumentVisitor<T> {
    default T of(FinancialInstrument fi) { return fi.acceptVisitor(this); }
    T visit(A a);
    default T visit(B b) { return visit((A) b); }
    default T visit(C c) { return visit((A) c); }
}
</code>```

Body:
This sounds like the Visitor Pattern could be helpful. It does not get rid of the dispatching code, but it is a fairly elegantly and standard way to implement dispatching. In Java-style OOP:

// an interface for anything calculatable
interface FinancialInstrument {
    // acceptVisitor makes the pattern obvious,
    // but you might want to pick a more domain-specific name.
    <T> T acceptVisitor(FinancialInstrumentVisitor<T> v);
}

class Option implements FinancialInstrument {
    <T> T acceptVisitor(FinancialInstrumentVisitor<T> v) {
        return v.visit(this);
    }
}

class Equity implements FinancialInstrument {
    <T> T acceptVisitor(FinancialInstrumentVisitor<T> v) {
        return v.visit(this);
    }
}

// an interface for all calculators
// basically, this consists of "visit" overloads that handle each type
interface FinancialInstrumentVisitor<T> {
    T of(FinancialInstrument fi); // convenience wrapper
    T visit(Option o);
    T visit(Equity e);
}

class PriceCalculator implements FinancialInstrumentVisitor<Price> {
    Price of(FinancialInstrument fi) {
        return fi.acceptVisitor(this);
    }
    Price visit(Option o) { ... }
    Price visit(Equity e) { ... }
}

class RiskCalculator implements FinancialInstrumentVisitor<Risk> {
    Price of(FinancialInstrument fi) {
        return fi.acceptVisitor(this);
    }
    Risk visit(Option o) { ... }
    Risk visit(Equity e) { ... }
}

Example usage:

PriceCalculator price = new PriceCalculator();
for (FinancialInstrument fi : portfolio) {
   doSomethingWith(price.of(fi));
   ...
}

The visitor pattern is great whenever you want to be free to easily add new operations, but the set of objects these operations work on is fairly fixed. Note that adding one type of financial instrument requires an overload to be added to the FinancialInstrumentCalculator interface, which is not backwards compatible – all consumers of that interface will have to be updated in order to support that method. This is not the case if the new financial instrument is a subtype of an existing class, as the existing handler can be used then.

If new financial instruments turn up more often than new operations, then using the visitor pattern is probably a bad idea. Note that whatever strategy you use to match n operations to m financial instruments, you will always (subtyping ignored for a moment) end up with n·m methods to code.

If your language allows this, I highly recommend to use traits or similar constructs to provide defaults in the FinancialInstrumentCalculator interface. E.g. when I have three types

class A implements FinancialInstrument
class B extends A
class C extends A

then the visitor methods for B and C can implemented by the visitor method for A by default:

interface FinancialInstrumentVisitor<T> {
    default T of(FinancialInstrument fi) { return fi.acceptVisitor(this); }
    T visit(A a);
    default T visit(B b) { return visit((A) b); }
    default T visit(C c) { return visit((A) c); }
}


答:
If your classes should know how to calculate a risk, a price or other metrics, depends on what these are dependent on.

E.g. to calculate a price, if you only need all the properties of FinancialInstrument then it should be implemented by the class itself. If you however need some external dependencies like the tax of a specific country, then the calculation (or at least this specific part of the calculation) should be provided by another class. If you try to explain what is a simple plain financial instrument to a third person and you don't use taxes as the part of the explaination then this is a good sign that taxes should not be part of the class.

You also don't need type dispatchers to do this. because the common parts should be implemented in the classes itself and the parts that are class dependent should be implemented in another class. If you use type dispatchers then chances are high that either your classes have something in common which should be modeled by an interface so that you can use 1 additional class which can handle both these classes in the same way without having to use something like instanceof or both these classes are not the same so you need 2 additional (and semantical different) classes.

If you give additional semantic information about your mentioned classes then I can also give a concrete example how I would implement it. =)

Title: How to avoid "type dispatchers" when working with SOLID

Body:
I've realized that since I've been more and more strict about the SOLID principles, my code tends to consist of more pure data objects and a lot of "operator" classes which seems to go against oop-principles. Specifically I often end up with "type dispatchers" that maps a specific object type to a suitable operator class.

Let me take an example:

In the old world I would have a base class FinancialInstrument with a .CalculatePrice() and .CalculateRisk() method. I would derive that to OptionInstrument and EquityInstrument with specific implementations of risk and price calculations.

But due to Single Responsibility (and since there are lots of different metrics to calculate, not just prices and risks), I now have a separate RiskCalculator class and a PriceCalculator class with derived specific implementations such as OptionPriceCalculator and EquityPriceCalculator etc.

When I want to iterate over instruments and calculate prices, I need have some kind of type-dispatcher class or factory that maps instruments to correct price calculation class, which just feels plain wrong and not very object oriented. I've seen this kind of pattern emerge in my projects more and more.

Am I doing something wrong or is there a better way to avoid these "type-dispatcher" factories?


答:
You can do WinForms-like development quite easily in WPF. WPF was actually designed to be easy to use for WinForms developers. You don't have to do anything with DataBinding or MVVM, you can have everything in code-behind. Not that I agree with this approach.

But if you leverage full power of WPF and do it properly, it will give you tons of productivity boosts through DataBindings and MVVM. But this requires discipline and focus on separation of concerns. And when you talk about WPF being "Fancy UI driven", then I can hardly see that happening.

Title: Productivity using .Net WPF for large ERP (LOB) desktop applicatons ~1500 forms\dialogs

Body:
I am wondering if WPF will fit in my case:

We want to refactor an old legacy application written in a 4GL language with about 1500 forms\dialogs. We want to do that in .Net (desktop application), now we have to consider using WinForms or WPF to accomplish that.

From my point of view, WinForms fits better because the UI is more "data driven" than "Fancy UI driven". For developers it is easier to create such dialogs using WinForms, instead of dealing with XAML and\or Blend in terms of producitivty. E. g. the WinForms Designer in Visaul Studio is more intuitive. But maybe that's, cause I am an old WinForms developer.

What do you think? Do you have "pros" (or "cons") to use WPF for a large ERP desktop applications?


问:
Why all consider UAT a validation activity? It contradicts the original idea
Virtually any book dealing with software testing mentions that user acceptance testing (UAT) is an ultimate validation activity, often quoting Boehms informal definition: "Validation: Are building the right product?"

But how come that Boehm himself considers UAT a verification?

GUIDELINES FOR VERIFYING AND VALIDATING SOFTWARE REQUIREMENTS AND DESIGN SPECIFICATIONS.
B.Boehm:

From the V-chart, it is clear that the key artifact idstinguishes
  verification activities from validation activities is the software
  requirements baseline. This refers to the requirements specification
  which is developed and validated during the Plans and Requirements
  Phase, accepted by the customer and developer at the Plans and
  Requirements Review as the basis for the software development
  contract, and formally change-controlled thereafter.

By definition,verification involves the comparison between the requirements baseline
  and the successive refinements descending from it — the product
  design, detailed design, code, data base, and documentation — in order
  to keep these refinements consistent with the requirements baseline.
  Thus, verification activities begins in the Product Design Phase and
  conclude with the Acceptance Test. They do not lead changes in the
  requirements baseline; only to changes in refinements descending from
  it.

On the other hand, validation identifies problems which must be
  resolved by a change of the requirements specification. Thus, there
  are validation activities which occur throughout the software
  life-cycle, including the development phase. For example, a simulation
  of the product design may establish not only that the design cannot
  meet the baseline performance requirements (verification), but also
  that the performance requirements are too stringent for any
  cost-effective product designs, and therefore need to be changed
  (validations).

The only explanation I can think of would be that Boehm did not consider Acceptance test as a USER acceptance test but as some kind of final check against the specification.

In addition, I believe this original article every book refers to is much clearer than those artificial definitions of V&V (that are, in addition, wrong from this point of view). According to Boehm, when I check the products against the requirements, it is a verification. When I test the product for its use, I validate it as I might find something that leads to changes in the requirements.

Of course Boehm's original idea contradicts some standards, such as ISO 12207, in which validation is to confirm that the requirements for a specific intended use of the software work product are fulfilled. Which means checking against the spec.

Most books says that verification is only static and the code is not run. I believe that according to Boehm, it is not true. E.g.:

Software Engineering And Quality Assurance, A.A.Puntambekar: The verification activities fall into the category of static testing.

Effective Methods for Software Testing: Includes Complete
  Guidelines,William E. Perr: Verification testing - testing in a static
  mode - ..... Validation testing (e.g. unit, integration ...)

I would conclude that despite many authors' opinions, I believe VERIFICATION includes testing which is done in order to check the correspondence of the specification and the program. Validation includes testing as well but it would not be based on the specifications.

答:
In the opening sections of the paper that you quote, Boehm states:

There is very little agreement in the software field on the
  definitions of the terms "verification" and "validation."

Boehm defines the terms verification and validation as he intends to use them in the rest of the paper, in order to be able to clearly present the rest of the writing without ambiguity:

Verification - to establish the truth of the correspondence between a
  software product and its specification. (Note: This definition is
  derived from the Latin word for "truth," veritas. Note also that data
  bases and documentation are fit subjects for verification, as well as
  programs.)

Validation - to establish the fitness or worth of a software product
  for its operational mission. (Note: This definition is derived from
  the Latin word for "to be worthy," valere.)

I think that the Guide to the Software Engineering Body of Knowledge can provide some insight into this as well:

Classical treatments suggest that “verification” deals with static
  evaluation methods and that “testing” deals with dynamic evaluation
  methods. Recent treatments, including ISO/IEC draft 29119, are
  blurring this distinction, though, so testing standards are mentioned
  here.

What all of this says is that, at the time Boehm wrote his paper, there wasn't a widely accepted singular definition for what is "verification" and what is "validation". Even today, that's still true.

Now that we know that there is some ambiguity in the terms "verification" and "validation" (and how "testing" fits into these), we can look at the diagram that Boehm presented.

Something that Boehm didn't discuss, but I've seen in multiple sources (including ISO/IEC 12207), validation specifically requires that the validation activities occur in the operational environment and can achieve its intended purposes, from the user's perspective. This may be implied by Boehm's definitions, but it's not clearly stated.

Boehm also used the term "acceptance testing". You are interpreting this as "user acceptance testing". There are other kinds of acceptance testing, such as factory acceptance testing (FAT). In my experience, a FAT is performed by the developing organization at the developing organization's site, with the procedures reviewed and accepted by the customer. This is a check to ensure the complete system (all software and hardware) are fully functioning, meet the specification, and a final inspection prior to delivery to the customer's facility. Based on Boehm's definitions, this can be a verification activity the developing organization can not fully exercise the product within the operational context.

What you are considering "user acceptance testing" is likely "OT&E" - Operational Test and Evaluation. This is indeed a validation activity since the customer and user are able to see the product within the operational context and say if it does or does not meet their needs.


问:
Why using string[] args in all main methods?
I'm a beginner in learning programming. I ask about using the string array in main method as a parameter. Why not writing the Main()  method without the string array? What is the point of having this array in Main method?

For example:

```<code>public static void Main(string[] args)
{
Console.WriteLine(args.Length);
Console.WriteLine(args[1]);
}
</code>```

答:
Have you ever listed items in a directory using

```<code>ls -a ~/Downloads
</code>```

or

```<code>dir C:\Users\user1\Downloads\ /P
</code>```

Now those "ls" and "dir" are commands/programs and the latter arguments are passed to the programs as string[] argv or sometimes int argc, char** argv. They provide arguments to the programs so they can behave accordingly.

When you start a program the OS loads the program to the memory and pushes the arguments to the stack. Now they are available to the program to be used.

High-level languages give you an easy way to access those arguments on the stack (as string arrays or an array of pointers to null terminated strings). If you used assembly, you would need to do some pointer arithmetic and load the arguments from stack to registers when you needed them.

For more details checkout following link, good explanation: FreeBSD Command Line Arguments

Body:
Have you ever listed items in a directory using

ls -a ~/Downloads

or

dir C:\Users\user1\Downloads\ /P

Now those "ls" and "dir" are commands/programs and the latter arguments are passed to the programs as string[] argv or sometimes int argc, char** argv. They provide arguments to the programs so they can behave accordingly.

When you start a program the OS loads the program to the memory and pushes the arguments to the stack. Now they are available to the program to be used.

High-level languages give you an easy way to access those arguments on the stack (as string arrays or an array of pointers to null terminated strings). If you used assembly, you would need to do some pointer arithmetic and load the arguments from stack to registers when you needed them.

For more details checkout following link, good explanation: FreeBSD Command Line Arguments


问:
Is it allowed to embed an LGPL command-line tool?
I want to sell a closed-application that depends upon a certain command line tool. Am I allowed to distribute my software including this command line tool?

For example, as a separate binary accompanied by the proper NOTICE file and if needed the source code.

Do I need to explain how I call this binary, so the user could swap it?

答:
LGPL allows you to link or embed binaries without opening your own source, so long as you provide the source code for the binaries and publish any changes you make to the libraries.

You must also deploy your application in a way that allows someone to replace the LGPL'd library, if they so choose.  In practice, this means that you must dynamically link to the library, so that a compiler and your source code are not required to perform the linking.


答:
AFAICT it is not forbidden to sell (L)GPLed software, as long as you provide a way to get its source; e.g. Red Hat does exactly this. I assume you don't make any modifications to the (L)GPLed tool, so linking to the canonical source code should be fine.

It looks like the tool is specifically designed to be included as a part of a non-GPL derived work. At least, so it works for LGPL libraries that you can link to a non-GPL binaries.

Note: IANAL.

Title: Is it allowed to embed an LGPL command-line tool?

Body:
I want to sell a closed-application that depends upon a certain command line tool. Am I allowed to distribute my software including this command line tool?

For example, as a separate binary accompanied by the proper NOTICE file and if needed the source code.

Do I need to explain how I call this binary, so the user could swap it?


答:
Do consult a lawyer for this, anything you get from this site (such as the answer that follows) will not free you from any liability nor guaranteed that you will be safe from prosecution.  This site is most definitively NOT a proper replacement for any sort of legal advice.

Now to the matter at hand, from what I understand, LGPL will allow inclusion of a licensed library if the user of your proprietary software can replace, on his own, the LGPL components with his own.  This implies that either you used it directly without modifications or provide the source code with your modifications to the component and that you provide sufficient means for the customer to perform the modifications.

In other words the LGPL must guarantee that the customer remains free to do whatever it pleases to the LGPL covered parts that are shipped with your application without going though you first.

The wikipedia page is a pretty good place to get started to understand this
http://en.wikipedia.org/wiki/GNU_Lesser_General_Public_License

you could try browsing groklaw see if they covered the subject

http://www.groklaw.net/index.php

Again this is NOT legal advice in anyway do get yourself a lawyer to help you through this properly.

Thanks to GpN to fin this FAQ that pretty much covers what you are looking for.


答:
What you are looking for is the Chain of Responsibility pattern, which allows you to compose a pipeline of objects that can act on a message.

In the chain of responsibility (one version of it), you have a Handler interface, and your individual behaviors implement that interface, and have a reference to the next handler. Pseudo-code, and probably not specific enough for your needs, but good for example:

```<code>interface Handler {
    protected Handler nextHandler;

    protected void pullData(string name);
    protected void pushData(string name, string data);

    public void process(string name);
}
</code>```

So you would have an HTTPHandler implementing the interface:

```<code>class HTTPHandler implements Handler {
    public HTTPHandler(Handler nextHandler) {
        this.nextHandler = nextHandler;
    }

    protected void pullData(string name) {
        string data = getDataOverHTTP(name);
        if(!this.nextHandler == null) {
            this.nextHandler.pushData(name, data);
        }
    }

    protected void pushData(string name, string data) {
        postDataOverHTTP(name, data);
        if(!this.nextHandler == null) {
            this.nextHandler.pushData(name, data);
        }
    }

    public void process(string name) {
        this.pullData(name);
    }
}
</code>```

Other classes can be built up accordingly, then composed together. Each Handler implementation knows to call the next handler in the list. And, the Handlers can be composed together dynamically at runtime. With one call to process on the first Handler, the data will be sent all the way down the pipeline. This article details a fuller example of this way of chain of responsibility.

(FYI: An alternate way of doing this could be to create a collection that encapsulates a list of Handlers, and passes data between them using an intermediate data object.)

Title: Design pattern for composition workflows

Body:
Please bear with me as I find this tricky to articulate exactly what I am after (probably not a good sign..).

I have several services set up which can be combined in a particular order to create workflows. For example, imagine I have the following services:

1) HTTP -> File Store (takes a file over HTTP and stores it)

2) FTP -> File Store

3) File Store-> FTP (takes a file over HTTP and pushes to FTP)

4) File Store-> Transformation -> File Store(applies a transformation to a file in File Store).

I might want to combine services to create a particular workflow, for example.

1) -> 4) -> 3)

Or

2) -> 4) -> 3)

And it might be the case that I perform exactly the same operation e.g. in the workflows above, step 4 could be applied on the same item twice, if the same item is sent over HTTP and FTP. I might also want to trigger subworkflows for example:

4) -> 3)

Would be a valid workflow. Is there a  design pattern/known approach to handling these 'cascading' workflows? I would like to avoid duplicate operations where possible but also design workflows in a separate, contained manner. The only thing that comes to mind for me is some sort of composition based approach where workflows are composed of several sub-workflows.

I hope this makes sense!

Body:
What you are looking for is the Chain of Responsibility pattern, which allows you to compose a pipeline of objects that can act on a message.

In the chain of responsibility (one version of it), you have a Handler interface, and your individual behaviors implement that interface, and have a reference to the next handler. Pseudo-code, and probably not specific enough for your needs, but good for example:

interface Handler {
    protected Handler nextHandler;

    protected void pullData(string name);
    protected void pushData(string name, string data);

    public void process(string name);
}

So you would have an HTTPHandler implementing the interface:

class HTTPHandler implements Handler {
    public HTTPHandler(Handler nextHandler) {
        this.nextHandler = nextHandler;
    }

    protected void pullData(string name) {
        string data = getDataOverHTTP(name);
        if(!this.nextHandler == null) {
            this.nextHandler.pushData(name, data);
        }
    }

    protected void pushData(string name, string data) {
        postDataOverHTTP(name, data);
        if(!this.nextHandler == null) {
            this.nextHandler.pushData(name, data);
        }
    }

    public void process(string name) {
        this.pullData(name);
    }
}

Other classes can be built up accordingly, then composed together. Each Handler implementation knows to call the next handler in the list. And, the Handlers can be composed together dynamically at runtime. With one call to process on the first Handler, the data will be sent all the way down the pipeline. This article details a fuller example of this way of chain of responsibility.

(FYI: An alternate way of doing this could be to create a collection that encapsulates a list of Handlers, and passes data between them using an intermediate data object.)


问:
Metric by which to hold developers accountable
I asked a question on lines of code per hour and got torn a new one.  So my matured follow-up question is this:

If not lines of code, then what is a good metric by which to measure (by the hour/day/unit-of-time) the effectiveness of remote programmers?

答:
Measure in the same way as you are measured by the customer.  In terms of functional code, but on a smaller scale.

Make short goals - a week or two - and see if the programmers fulfill the goals, and do so in a satisfactory way.

I would strongly suggest peer review of code, as this allows you to catch bad code up front.


问:
Is premature optimization really the root of all evil?
A colleague of mine today committed a class called ThreadLocalFormat, which basically moved instances of Java Format classes into a thread local, since they are not thread safe and "relatively expensive" to create. I wrote a quick test and calculated that I could create 200,000 instances a second, asked him was he creating that many, to which he answered "nowhere near that many". He's a great programmer and everyone on the team is highly skilled so we have no problem understanding the resulting code, but it was clearly a case of optimizing where there is no real need. He backed the code out at my request. What do you think? Is this a case of "premature optimization" and how bad is it really?

答:
From a different perspective, it is my experience that most programmers/developers do not plan for success and the "prototype" is almost always becomes Release 1.0.  I have first hand experience with 4 separate original products in which the classy, sexy, and highly functional front-end (basically the UI) resulted in wide-spread user adoption and enthusiasm.  In each of these products, performance problems began to creep in within relatively short times (1 to 2 years) particularly as larger, more demanding customers,  began to adopt the product.  Very soon performance dominated the issues list, although new feature development dominated management's priority list.  Customers became more and more frustrated as each release added new features which sounded great but were almost inaccessible due to performance issues.

So, very fundamental design and implementation flaws that were of little or no concern in the "proto-type" became major stumbling blocks to long-term success of the products (and the companies).

Your customer demo may look and perform great on your laptop with XML DOMs, SQL Express, and lots of client-side cached data.  The production system will probably crash a burn if you are successful.

In 1976 we were still debating the optimal ways of calculating a square root or sorting a large array and Don Knuth's adage was directed at the mistake of focusing on optimizing that sort of low level routine early in the design process rather than focusing on solving the problem and then optimizing localized regions of code.

When one repeats the adage as an excuse for not writing efficient code (C++, VB, T-SQL or otherwise), or for not properly designing the data store, or for not considering the net work architecture, then IMO they are just demonstrating a very shallow understanding of the real nature of our work.
Ray

OwnerDisplayName: Craig Day


答:
It might be useful to examine the testing artifacts that  ISO 12207 demands under Verification and Validation:

Verification

7.2.4.3.2.3 Code verification.

The code shall be verified considering the criteria listed below:

a) The code is traceable to design and requirements, testable,
correct, and compliant with requirements and coding standards.

b)
The code implements proper event sequence, consistent interfaces,
correct data and control flow, completeness, appropriate allocation
timing and sizing budgets, and error definition, isolation, and
recovery.

This describes Unit Testing and Static Analysis, among other things.  Unit Testing and static analysis are below the red requirements baseline; they are verification activities.

7.2.4.3.2.4 Integration verification.

The integration shall be verified considering the criteria listed below:

a) The software components and units of each software item
have been completely and correctly integrated into the software item.

b) The hardware items, software items, and manual operations of the
system have been completely and correctly integrated into the system.

That's Integration Testing, still part of the Verification process.

Validation

7.2.5.3.2.3 [Testing Includes]:

a) Testing with stress, boundary, and singular inputs;

b) Testing the software product for its ability
to isolate and minimize the effect of errors; that is, graceful
degradation upon failure, request for operator assistance upon stress,
boundary, and singular conditions;

c) Testing that representative
users can successfully achieve their intended tasks using the software
product.

Testing of this kind is seldom embodied in the original requirements specification.  It normally arises as a result of user testing and feedback, among other things.  It rightly belongs above the Requirements Baseline, and is part of the Validation process.

ISO 12207 does not appear to make a distinction between "static" and "dynamic" testing.

As to Acceptance Testing, my view is that if a requirement is a valid requirement, it is testable.  Acceptance testing is, therefore, the process of verifying the requirements via tests, and belongs below the Requirements Baseline as part of the Verification process.

Accordingly, changes to the software requirements that arise as a result of user studies belong above the line, as part of the Validation process.

Title: Why all consider UAT a validation activity? It contradicts the original idea

Body:
Virtually any book dealing with software testing mentions that user acceptance testing (UAT) is an ultimate validation activity, often quoting Boehms informal definition: "Validation: Are building the right product?"

But how come that Boehm himself considers UAT a verification?

GUIDELINES FOR VERIFYING AND VALIDATING SOFTWARE REQUIREMENTS AND DESIGN SPECIFICATIONS.
B.Boehm:

From the V-chart, it is clear that the key artifact idstinguishes
  verification activities from validation activities is the software
  requirements baseline. This refers to the requirements specification
  which is developed and validated during the Plans and Requirements
  Phase, accepted by the customer and developer at the Plans and
  Requirements Review as the basis for the software development
  contract, and formally change-controlled thereafter.

By definition,verification involves the comparison between the requirements baseline
  and the successive refinements descending from it — the product
  design, detailed design, code, data base, and documentation — in order
  to keep these refinements consistent with the requirements baseline.
  Thus, verification activities begins in the Product Design Phase and
  conclude with the Acceptance Test. They do not lead changes in the
  requirements baseline; only to changes in refinements descending from
  it.

On the other hand, validation identifies problems which must be
  resolved by a change of the requirements specification. Thus, there
  are validation activities which occur throughout the software
  life-cycle, including the development phase. For example, a simulation
  of the product design may establish not only that the design cannot
  meet the baseline performance requirements (verification), but also
  that the performance requirements are too stringent for any
  cost-effective product designs, and therefore need to be changed
  (validations).

The only explanation I can think of would be that Boehm did not consider Acceptance test as a USER acceptance test but as some kind of final check against the specification.

In addition, I believe this original article every book refers to is much clearer than those artificial definitions of V&V (that are, in addition, wrong from this point of view). According to Boehm, when I check the products against the requirements, it is a verification. When I test the product for its use, I validate it as I might find something that leads to changes in the requirements.

Of course Boehm's original idea contradicts some standards, such as ISO 12207, in which validation is to confirm that the requirements for a specific intended use of the software work product are fulfilled. Which means checking against the spec.

Most books says that verification is only static and the code is not run. I believe that according to Boehm, it is not true. E.g.:

Software Engineering And Quality Assurance, A.A.Puntambekar: The verification activities fall into the category of static testing.

Effective Methods for Software Testing: Includes Complete
  Guidelines,William E. Perr: Verification testing - testing in a static
  mode - ..... Validation testing (e.g. unit, integration ...)

I would conclude that despite many authors' opinions, I believe VERIFICATION includes testing which is done in order to check the correspondence of the specification and the program. Validation includes testing as well but it would not be based on the specifications.


问:
Naming boolean field that is a verb
In Java, by convention getter and setter for boolean fields will be isField() and setField(). This works perfectly fine with field names that are adjectives like active, visible, closed, etc.

But how do I name a field that has meaning of a verb, like haveChildren? Add “_ing” to the verb (havingChildren), maybe?

To clarify, I don't have control of the method names (getter and setter) as they are auto-generated by the IDE. So what I need is an appropriate field name so that when the IDE generate a getter for it, it make senses. For example, hasChildren is a perfect field name, but when the IDE generate the getter for the field it would be isHasChildren. How do I solve this?

答:
Short answer:

method names aren't supossed to reflect internal implementation but expected behavior.

Long answer:

haveChildren() should be named hasChildren().

Also I don't see hasChildren() as necessarily being the getter for a boolean class member. I guess such a method would find out whether or not a member of type Collection is empty.

Default name an IDE gives to generated getters and setters aren't supossed to be a law set in stone.

Another point: Interfaces have names for yet-to-be-implemented methods.

If method names were supossed to reflect internal implementation, how would someone be able to ever design an interface ? Interfaces don't have an implementation nor they know beforehand what the implementators will do under the hood.

Take for example the Iterator interface in Java.

When you implement Iterator, even when you have a boolean member named next, you are not supossed to rename hasNext() to isNext() or isHavingNext(). That's an implementation detail. In fact, I've implemented Iterator and what I do is have a member of the type of whathever my class has a list of, named next (not a boolean). hasNext() then returns next!=null.

Also, see this:

```<code>class patient {
      private boolean hasPulse;
      private boolean isBreathing:
      public boolean isDead(){ return (!hasPulse & !isBreathing);}
}
</code>```

Note that isDead() is no normal getter.

Take IDEs' productivity tools for what they are.

Title: Naming boolean field that is a verb

Body:
Short answer:

method names aren't supossed to reflect internal implementation but expected behavior.

Long answer:

haveChildren() should be named hasChildren().

Also I don't see hasChildren() as necessarily being the getter for a boolean class member. I guess such a method would find out whether or not a member of type Collection is empty.

Default name an IDE gives to generated getters and setters aren't supossed to be a law set in stone.

Another point: Interfaces have names for yet-to-be-implemented methods.

If method names were supossed to reflect internal implementation, how would someone be able to ever design an interface ? Interfaces don't have an implementation nor they know beforehand what the implementators will do under the hood.

Take for example the Iterator interface in Java.

When you implement Iterator, even when you have a boolean member named next, you are not supossed to rename hasNext() to isNext() or isHavingNext(). That's an implementation detail. In fact, I've implemented Iterator and what I do is have a member of the type of whathever my class has a list of, named next (not a boolean). hasNext() then returns next!=null.

Also, see this:

class patient {
      private boolean hasPulse;
      private boolean isBreathing:
      public boolean isDead(){ return (!hasPulse & !isBreathing);}
}

Note that isDead() is no normal getter.

Take IDEs' productivity tools for what they are.

ContentLicense: CC BY-SA 4.0


问:
Why do objects created with no assignment not generate a syntax error in Python?
While working on a Python project, I realized that during my editing I had left a string floating around in the middle of my code and it didn't generate an error. For example, these few lines execute just fine:

```<code>print("Starting")

"This string does nothing"
["Neither does", "this list"]

print("Done")
</code>```

Output:

Starting

  Done

It seems to me that since there are no statements or function calls, those should generate syntax errors. Why is there no exception raised, and is there some use for a construct like this?

答:
It’s an expression statement. In the REPL, the repr of the result of an expression statement is printed if it’s not None. You use this type of statement all the time when calling functions:

```<code>f(x)
</code>```

It’s just that those functions typically have side effects, whereas literals do not. This is a common syntactic feature of imperative languages with a statement–expression distinction.

Body:
It’s an expression statement. In the REPL, the repr of the result of an expression statement is printed if it’s not None. You use this type of statement all the time when calling functions:

f(x)

It’s just that those functions typically have side effects, whereas literals do not. This is a common syntactic feature of imperative languages with a statement–expression distinction.


问:
Is it possible to use functional paradigm in imperative languages?
If I understand the concept correctly the goal, which functional languages are trying to achieve is to eliminate any side effects from functions and to eliminate a state. The rationale behind this is to obtain referential transparency, which leads to more predictable execution.

However, nothing prevents me from writing the code with above in mind in imperative language. I'm thinking only about classic constructs and not functional mixins.

Let's say I have following code in C.

```<code>int add(int x, int y) {
    return x + y;
}

int sqr(int x)
{
    return x*x;
}

int main()
{
    return sqr(add(3,5));
}
</code>```

So, I have two functions, which do not posses any side effects. Neither program has any state. Is this code missing something exceptionally functional?

Currently, I perceive functional languages like if they had built impressive decoration made of syntactic sugar over the core concept of functional programming. Their syntax discourages slicing the code into statements, however I don't see any substantial difference that prevents me to take functional approach (and yield its fruits) in imperative language. Am I wrong? Hence my question.

答:
It is certainly possible to program in a purely functional style in an imperative language. In fact, if you look at books like Effective Java or Java Concurrency in Practice, much of the advice in those books basically boils down to "don't use mutable state", "don't use side-effects", etc.

However, it may not always be a pleasant experience, and you may not be able to do everything you want to do.

You mentioned C specifically as an example. Unless I'm missing something, the purely functional subset of C is not Turing-complete, because there is no way to express iteration. C does not have Proper Tail Calls, so, you will eventually overflow the stack when trying to express something like iterating over an infinite list. You will need to use a loop for iteration, but loops rely on mutable state and side-effects.

Of course, the standard Turing-tarpit argument applies … you can do functional programming C by implementing a Haskell interpreter in C and then program in Haskell. But that's not how I interpret the OP's question.


问:
What is the "default" software license?
If I release some code and binaries, but I don't include any license at all with it, what are the legal terms that apply by default (in the US, where I am). I know that I automatically have copyright without doing anything, but what restrictions are there on it?

If I upload my code to github and announce it as a free download / contribute at will, then are people allowed to modify and close source my work? I haven't said that they cannot, as a GPL would, but I don't feel that it would by default be acceptable to steal my work either.

So what can and cannot people do with code that is freely available, but has absolutely no licensing terms attached?

答:
The copyright laws vary wildly from country to country.  THis means that what is legal in one country is not in another, and using unlicensed code is a ticking bomb.

This in turn means that the code should not be adopted by a team producing production code. (My personal opinion) as you never know when you reach such a situation.

If you want people to use your own code without you having any concerns about for what purpose, then consider the Apache 2.0 license.

Title: What is the "default" software license?


问:
In agile environment, how is bug tracking and iteration tracking consolidated.
This topic stemmed from my other question about management-imposed waterfall-like schedule. From the responses in the other thread, I gathered this much about what is generally advised:

Each story should be completed with no bugs.  Story is not closed until all bugs have been addressed.  No news there and I think we can all agree with this.

If at a later date QA (or worse yet a customer) finds a bug, the report goes into a bug tracking database and also becomes a story which should be prioritized just like all other work.

Does this sum up general handling of bugs in agile environment?

If yes, the part I'm curious about is how do teams handle tracking in two different systems? (unless most teams don't have different systems).

I've read a lot of advice (including Joel's blog) on software development in general and specifically on importance of a good bug tracking tool. At the same time when you read books on agile methodology, none of them seem to cover this topic because in "pure" agile, you finish iteration with no bugs. Feels like there's a hole there somewhere.

So how do real teams operate? To track iterations you'd use (whiteboard, Rally...), to track bugs you'd use something from another set of products (if you are lucky enough, you might even get stuck with HP Quality Center).  Should there be 2 separate systems? If they are separate, do teams spend time creating import/sync functionality between them? What have you done in your company? Is bug tracking software even used? Or do you just go straight to creating a story?

答:
I think the solution of this problem is to let team create Issues/bugs within user story, just like tasks.

Yodiz (www.yodiz.com) easily resolve this issue by allowing you to create Issues on Sprint board and assign them to a user story. Also same issue can be seen on Yodiz built-in issue tracker so now you can see the same issue at two places on your issue board as well as on your sprint or kanban board.

You can tread the issue as task and move it along the board just like you move your task from one problem state to another.

Again by doing so you never loose track of your bugs. There are times when testing teams start testing your completed tasks and in those situation it's very help to let you attach issues to user story.
In case of Yodiz testers can create an issue on issue tracker and attach (associate) it to a user story and that bug would start showing up in developers sprint board.