问:
To branch or not to branch?
Till recently my development workflow was the following:

Get the feature from product owner

Make a branch (if feature is more than 1 day)

Implement it in a branch

Merge changes from main branch to my branch (to reduce conflicts during backward merging)

Merge my branch back to main branch

Sometimes there were problems with merging, but in general I liked it.

But recently I see more and more followers of idea to not make branches as it makes more difficult to practice continuous integration, continuous delivery, etc. And it sounds especially funny from people with distributed VCS background who were talking so much about great merging implementations of Git, Mercurial, etc.

So the question is should we use branches nowadays?

答:
the question is should we use branches nowadays?

Well about half year ago I was assigned to perform a study to answer that question. Here's the summary, based on references studied (listed below)

there's no commonly agreed "best" branching strategy applicable to any project

most resources seem to agree that choosing productive strategy depends on the particular project specifics

side note. Based on above it looks like any changes to project branching strategy need to be tested, measured and compared to other options tested

popular opinion is that merging with Subversion takes a lot of efforts. All who compared SVN and Git note that merging is critically easier with Git

an important factor seem to be whether production releases originate from trunk or branches. Teams doing prod releases from trunk (which seem to be not quite a popular way) are essentially prohibited to use unstable trunk strategy. Teams doing prod releases from branches have more branching options to choose from.

popular strategies seem to be stable trunk, unstable trunk and development (integration) branch

references

http://msdn.microsoft.com/en-us/library/aa730834%28v=vs.80%29.aspx

...Deciding on the best branching strategy is a balancing act. You must trade off productivity gains against increased risk. One way to validate a chosen strategy is to consider a scenario of change. For example, if you decide to align branches with the system architecture (for example, a branch represents a system component) and you expect significant architectural changes, you might have to restructure your branches and associated processes and policies with each change. Choosing an inadequate branching strategy can cause process overheads and lengthy integration and release cycles that prove frustrating for the whole team...

http://www.cmcrossroads.com/bradapp/acme/branching/

...Frequent, incremental integration is one of the signposts of success, and its absence is often a characteristic of failure. Current project management methods tend to avoid strict waterfall models and embrace the spiral-like models of iterative/incremental development and evolutionary delivery. Incremental integration strategies, like Merge Early and Often and its variants, are a form of risk management that tries to flush out risk earlier in the lifecycle when there is more time to respond to it. The regularity of the rhythm between integrations is seen by [Booch], [McCarthy], and [McConnell] as a leading indicator of project health (like a "pulse" or a "heartbeat").

Not only does early and frequent integration flesh out risk sooner and in smaller "chunks," it also communicates changes between teammates...

http://www.codinghorror.com/blog/2007/10/software-branching-and-parallel-universes.html

...In most source control systems, you can create hundreds of branches with no performance issues whatsoever; it's the mental overhead of keeping track of all those branches that you really need to worry about... Branching is a complex beast. There are dozens of ways to branch, and nobody can really tell you if you're doing it right or wrong...

http://www.lostechies.com/blogs/derickbailey/archive/2010/02/24/branching-strategies-when-to-branch-and-merge.aspx

...There are many aspects of a system to be considered when branching your code... In the end, the goal is to provide a sandbox for the context in which code is being written. Understanding the available options, when each option is best suited to the situation at hand and the cost of these options will help you in deciding how and when to branch...

http://www.snuffybear.com/ucm_branch.htm

Note given other references listed here, author's claim that "This article describes three key branching models used in Software Engineering projects" does not look justified. Terminology used does not look widespread (EFIX, Model-1,2,3 etc).

http://svn.haxx.se/users/archive-2007-10/att-0101/SCMBranchingModels-talkback.pdf

Reference presents an interesting example of difficulties communicating branching strategies.

http://simpleprogrammer.com/2010/06/04/simple-branching-strategy-part-1-back-to-basics/

...Keep it simple. Working directly off the trunk is by far the best approach in my opinion.

It almost sounds like heresy when I actually type it onto my screen, but if you'll bear with me for a moment, not only will I show you why I think this is essential for an Agile process, but I'll show you how to make it work...

...If I had to base my reasoning on one solid argument, it would be the value of continuous integration.  I blogged about the value of CI and best practices in the past.  I am a pretty big advocate of CI...

...You really have to ask yourself a question here: "Is all the overhead you are incurring from doing your complicated branching and merging strategy resulting in a real value that does not exist over a more simple strategy?"...

...A strategy I have effectively used in the past and have developed over time.  I'll sum it up briefly here.

Everyone works off of trunk.

Branch when you release code.

Branch off a release when you need to create a bug fix for already released code.

Branch for prototypes.

  ...

http://simpleprogrammer.com/2010/06/07/simple-branching-strategy-part-2-implementation/

  ...pretty detailed walk-through...

http://www.codelathe.com/blog/index.php/2009/07/02/a-svn-branching-strategy-that-works/

...Finally, remember that there is no ideal branching and merging strategy. It pretty much depends on your unique development environment...

http://blog.perforce.com/blog/?cat=62

...The worst case scenario is that you introduce a "semantic merge" problem, where the result of an automated merge is incorrect, but compiles OK and sneaks past testing, possibly even surviving long enough to be a customer-visible bug.  Eek!

Adding insult to injury, because they can escape detection longer, semantic merge problems are harder to fix later, since the change is no longer fresh in the mind of the developer who originated the change.  (It's usually best to merge changes soon after there made, ideally by the developer who originated the change if that's practical)...

http://blog.perforce.com/blog/?p=1635

Note recommended policy appears similar to development branch as it is defined in http://www.infoq.com/articles/agile-version-control#q11 and http://msdn.microsoft.com/en-us/library/bb668955.aspx

Promotion model explanation: http://www.perforce.com/perforce/papers/life.html

https://stackoverflow.com/questions/34975/branching-strategies

Community members share different experience in various projects using various branching strategies. No agreed consensus on "best" or "worst".

http://oreilly.com/catalog/practicalperforce/chapter/ch07.pdf

"classic" reading - explained terminology like Mainline Model, Codeline etc

http://www.stickyminds.com/s.asp?F=S16454_COL_2

Essentially a brief summary of stuff presented in http://oreilly.com/catalog/practicalperforce/chapter/ch07.pdf

http://www.stickyminds.com/s.asp?F=S16511_COL_2

...There are three common approaches for deciding when and how to branch:

Create the release branch when you are "feature complete," and plan to fix last-minute issues on this code line. In this case, the release branch is really a "release-prep code line," as described in Software Configuration Management Patterns, since you expect that there is still work to be done.

Change your work style to avoid final integration work, working off of the active development line.

Branch for the new work by creating a task branch and merging that work into the active development line after the release is complete.

  ...A rationale for branching is to isolate code at the end of a release so that it can stabilize. Isolation through branching often masks a quality problem that will end up manifesting itself in the added cost of maintaining parallel streams before a product is released. Branching is easy. Rather, it's the merging and the cognitive overhead of understanding how changes flow between branches that are difficult, so it's important to choose a process that minimizes the cost of branching and merging...

http://nvie.com/posts/a-successful-git-branching-model/ Git-oriented strategy.

...We consider origin/master to be the main branch where the source code of HEAD always reflects a production-ready state.

We consider origin/develop to be the main branch where the source code of HEAD always reflects a state with the latest delivered development changes for the next release. Some would call this the "integration branch". This is where any automatic nightly builds are built from....

Somewhat resembling development branch strategy as defined in http://www.infoq.com/articles/agile-version-control#q11 and http://msdn.microsoft.com/en-us/library/bb668955.aspx

http://svnbook.red-bean.com/en/1.5/svn.branchmerge.html

...project policies vary widely concerning exactly when it's appropriate to create a feature branch. Some projects never use feature branches at all: commits to /trunk are a free-for-all. The advantage to this system is that it's simple—nobody needs to learn about branching or merging. The disadvantage is that the trunk code is often unstable or unusable. Other projects use branches to an extreme: no change is ever committed to the trunk directly. Even the most trivial changes are created on a short-lived branch, carefully reviewed, and merged to the trunk. Then the branch is deleted. This system guarantees an exceptionally stable and usable trunk at all times, but at the cost of tremendous process overhead.

Most projects take a middle-of-the-road approach. They commonly insist that /trunk compile and pass regression tests at all times. A feature branch is required only when a change requires a large number of destabilizing commits. A good rule of thumb is to ask this question: if the developer worked for days in isolation and then committed the large change all at once (so that /trunk were never destabilized), would it be too large a change to review? If the answer to that question is "yes," the change should be developed on a feature branch. As the developer commits incremental changes to the branch, they can be easily reviewed by peers.

Finally, there's the issue of how to best keep a feature branch in "sync" with the trunk as work progresses. As we mentioned earlier, there's a great risk to working on a branch for weeks or months; trunk changes may continue to pour in, to the point where the two lines of development differ so greatly that it may become a nightmare trying to merge the branch back to the trunk.

This situation is best avoided by regularly merging trunk changes to the branch. Make up a policy: once a week, merge the last week's worth of trunk changes to the branch...

http://thedesignspace.net/MT2archives/000680.html

...This section of the Eclipse CVS tutorial is based on Paul Glezen's article on the Eclipse website: Branching with Eclipse and CVS, and is used with his permission under the terms of the EPL license. The changes I am making to his version are mainly to expand it with more step by step images and explanations, and integrate it with my own beginner tutorials in an attempt to make it more accessible to beginners and designers. Experienced developers will probably prefer to work from Paul's version...

http://www.eclipse.org/articles/article.php?file=Article-BranchingWithEclipseAndCVS/article1.html

http://www.eclipse.org/articles/article.php?file=Article-BranchingWithEclipseAndCVS/article2.html

http://learnsoftwareprocesses.com/2007/12/29/common-branching-strategies/

...Here are some of the common branching models:

Branch-by-release Model: One of the most common branching strategies is to align branches with product releases. A branch holds all the software development assets for a single release. Occasionally, updates need to be merged from one release to another, but they usually never merge. Branches will be discontinued when a release is retired.

Branch per Promotion: Another very common approach is to align branches with software asset promotion levels. A specific development version is branched off into a Test branch, at which all the integration and system testing is performed. When you complete testing, the software development assets are branched into the Production branch and ultimately deployed.

Branch per Task: To avoid overlapping tasks (or activities) and a loss in productivity, you can isolated them on a separate branch. Keep in mind that these are short-term branches that should be merged as soon as the task is completed, for otherwise the merging effort required may exceed the productivity benefits of creating them in the first place.

Branch per Component: You could align each branch with the system architecture. In this strategy, you branch off individual components (or subsystems). Then each team developing a component decides when to merge their code back into the development line that serves as the integration branch. This strategy can work well if system architecture is in place and the individual components have well-defined interfaces. The fact that you develop components on branches enables more fine-grained control over software development assets.

Branch per Technology: Another branching strategy aligned with the system architecture. In this case the branches are aligned to technology platforms. Common code is managed on a separate branch. Due to the unique nature of the software development assets managed on the branches, they probably never merge...

http://msdn.microsoft.com/en-us/library/bb668955.aspx

...Refer to the branching and merging guidelines in "Source Control Guidelines" in this guide for a summary of branching and merging guidelines.
...When branching, consider the following:

Do not branch unless your development team needs to work on the same set of files concurrently. If you are unsure about this, you can label a build and create a branch from that build at a later point. Merging branches can be time consuming and complex, especially if there are significant changes between them.

Structure your branch trees so that you only need to merge along the hierarchy (up and down the branch tree) rather than across the hierarchy. Branching across the hierarchy requires that you use a baseless merge, which requires more manual conflict resolution.

The branch hierarchy is based on the branch parent and branch child, which may be different than the physical structure of the source code on disk. When planning your merges, keep in mind the logical branch structure rather than the physical structure on disk.

Do not branch too deeply. Because it takes time to execute each merge and resolve conflicts, a deep branching structure can mean that changes in a child branch may take a very long time to propagate to the main branch. This can negatively impact project schedules and increase the time to fix bugs.

Branch at a high-level and include configuration and source files.

Evolve your branching structure over time.

Merging requires one or more developers to execute the merge and resolve conflicts. The merged source must be thoroughly tested because it is not uncommon to make bad merge decisions that can destabilize the build.

Merging across the branch hierarchy is especially difficult and requires you to manually handle many conflicts that could otherwise be handled automatically.

  The decision whether to create a branch can be reduced to whether the cost of merging conflicts in real time is higher than the overhead cost of merging conflicts between branches...

http://kashfarooq.wordpress.com/2009/11/23/bazaar-branching-strategy-with-a-subversion-trunk/

http://kashfarooq.wordpress.com/2010/12/16/bazaar-branching-strategy-with-a-subversion-trunk-revised/

http://kashfarooq.wordpress.com/2009/11/02/using-bazaar-feature-branches-with-a-subversion-trunk/

http://kashfarooq.wordpress.com/2009/09/08/bazaar-or-git-moving-away-from-subversion/

...Do any of these Subversion complaints sound familiar?

You are randomly instructed that "you need to run update". You then do an update - which takes ages to complete. And then, finally, you see that there were no changes that needed to be downloaded.

You are randomly instructed that "you need to run cleanup".

You have huge merge problems. For example, you use ReSharper to rename a class, and some else has updated that class in the meantime. You then see the dreaded tree conflict error (shudder). Or even worse, you rename an entire namespace and folder (double shudder). Now you really are in for a world of pain.

Your merges tend to be more and more manual. You frequently have to use WinMerge because Subversion hasn't got a clue.

You are often waiting around for Tortoise to update/check for modifications/anything.

I have a subversion repository on my USB pen drive. I get tree conflicts and merge problems with that, and I'm the only user!

The main problem is merging...

"subversion sucks" sounds familiar. Time to listen to Joel and Linus?

http://social.msdn.microsoft.com/Forums/en/tfsversioncontrol/thread/f127676c-8f05-410c-9a30-0eb43a26a9fa

discussion of the best practice for release isolation branch strategy in the case of evolving systems.

http://branchingguidance.codeplex.com/

"Microsoft Team Foundation Server Branching Guidance" - huge and detailed document with recommendations tailored to different projects: HTML version here. Proves that Microsoft does not believe in one-size-fits-all approach wrt branching strategies.

https://stackoverflow.com/questions/597707/best-branching-strategy-when-doing-continuous-integration

What is the best branching strategy to use when you want to do continuous integration?
...The answer depends on the size of your team and quality of your source control and the ability to merge correctly complex change sets...

http://www.zeroturnaround.com/blog/continuous-integration-and-feature-branches/
more detailed analysis of branching interplay with continuous integration, based on concrete experience with Hudson/Jenkins - along with a couple of useful references

...My greatest discovery was that although CI is about committing, pushing and getting feedback often (i.e. the CI cluster provides you with feedback that your workstation could never give you in the same amount of time), the true purist CI actually has one more requirement — that the team needs to work on the same  baseline...

Materials used

Multiple Branches Best Practices – post to Jenkins list

Is it possible to handle multiple branches where some jobs should run on each one without duplicating – post to Jenkins list

Parallel Development with Branches – post to Jenkins list

Configure or Create Hudson Job Automatically – stackoverflow.com

Continuous Integration with Multiple Branch Development – stackoverflow.com

Handling Multiple Branches in Continuous Integration – stackoverflow.com

Continuous integration – Martin Fowler

Continuous integration – Wikipedia

http://codicesoftware.blogspot.com/2010/03/branching-strategies.html

...CVS and SVN were discouraging the whole branching/merging strategy since they were totally unable to do so...
...Simple rule: create a task branch for every new feature or bugfix you've to implement... It can sound like overkill for SVN/CVS users but you know any modern SCM will let you create branches in a second, so there's no real overhead.

Important note: if you look at it carefully you'll see that I'm talking about using task branches as rich-man changelists...

http://publib.boulder.ibm.com/infocenter/cchelp/v7r0m1/index.jsp?topic=/com.ibm.rational.clearcase.cc_proj.doc/c_bntr_plnbrstrat.htm

...Branching policy is influenced by the development objectives of the project and provides a mechanism to control the evolution of the code base. There are as many variations of branching policy as organizations that use Rational ClearCase version control. But there are also similarities that reflect common adherence to best practices...

http://blogs.open.collab.net/svn/2007/11/branching-strat.html

...The Subversion model (or general open source model more accurately) is what is being shown in the unstable trunk model...

http://en.wikipedia.org/wiki/Trunk_%28software%29

In the field of software development, trunk refers to the unnamed branch (version) of a file tree under revision control. The trunk is usually meant to be the base of a project on which development progresses. If developers are working exclusively on the trunk, it always contains the latest cutting-edge version of the project, but therefore may also be the most unstable version. Another approach is to split a branch off the trunk, implement changes in that branch and merge the changes back into the trunk when the branch has proven to be stable and working. Depending on development mode and commit policy the trunk may contain the most stable or the least stable or something-in-between version.

Often main developer work takes place in the trunk and stable versions are branched, and occasional bug-fixes are merged from branches to the trunk. When development of future versions is done in non-trunk branches, it is usually done for projects that do not change often, or where a change is expected to take a long time to develop until it will be ready for incorporating in the trunk...

http://www.mcqueeney.com/roller/page/tom/20060919

...These are notes from a webinar on Subversion best practices, conducted Aug. 30, 2006 by CollabNet.
...Two organizational strategies: unstable trunk vs. stable trunk...
...PREFER an unstable trunk when possible...

https://stackoverflow.com/questions/153812/subversion-is-trunk-really-the-best-place-for-the-main-development

In SVN, trunk is the recommended place for the main development and I use this convention for all of my projects. However, this means that trunk is sometimes unstable, or even broken...
...wouldn't it be better to do the "wild development" on some branch like /branch/dev and only merge to trunk when the build is reasonably solid?

...The trunk is where the ongoing development is supposed to happen. You really shouldn't have a problem with "broken" code, if everyone is testing their changes before committing them. A good rule of thumb is to do an update (get all the latest code from the repos) after you have coded your changes. Then build and do some unit testing. If everything builds and works, you should be good to check it in...

...Nope trunk isn't the best place. At our organization we always follow this approach: Trunk contains release code, so it always compiles. With new each release/milestone we open a new branch. Whenever a developer owns up an item, he/she creates a new branch to this release branch and merges it into a release branch only after testing it. Release branch is merged into trunk after system testing...

http://blog.yclian.com/2009/03/working-on-branches-and-stable-trunk.html

...I used to work on the trunk because for all the projects I worked on, it's either I was the sole developer or the team ensured that everyone code check-in has passed the local tests. Otherwise, we created (we still) branches for bug fixes, large code for new features, etc.

About 2 months ago, I had a short git session with Kamal and he shared with me the idea of story/branch. And as my team started to grow with more dev guys, I feel the need of encouraging more branching and now this has become a rule. For a project with automated tests defined with CI set up, a stable trunk is guaranteed and this practice can fit very well into it.

We don't use git but Subversion because that's how we started and we are still comfortable with it now (most of the time)...

http://www.ericsink.com/scm/scm_branches.html

This is part of an online book called Source Control HOWTO, a best practices guide on source control, version control, and configuration management...

...Eric's Preferred Branching Practice ...Keep a "basically unstable" trunk. Do your active development in the trunk, the stability of which increases as you approach release. After you ship, create a maintenance branch and always keep it very stable...

...In the next chapter I will delve into the topic of merging branches...

http://marc.info/?l=forrest-dev&m=112504297928196&w=2

Starting mail of the thread discussing branching strategies for Apache Forrest project

note currently the project appears to use unstable trunk model with release branches:

"Development work is done on the trunk of SVN... There are "release branches" of SVN, e.g. forrest_07_branch." (project guidelines)

"Building the release candidate packages... 17. Create a maintenance branch in SVN..." (How to release)

O'Reilly CVS branching docs:

http://commons.oreilly.com/wiki/index.php/Essential_CVS/Using_CVS/Tagging_and_Branching#Basically_stable

...The basically stable branching philosophy states that the trunk should contain project data that is always close to being ready for release...
  ...More lenient variations of this philosophy allow anything that passes developer unit-testing to be merged into the trunk. Such a relaxed approach requires a release candidate to be branched off and put through a full QA analysis before publication...

...The basically unstable philosophy states that the trunk should contain the latest code, regardless of its stability, and that release candidates should be branched off for QA.

  ...More lenient variations also allow branching for experimental code, refactoring, and other special-case code. Merging of a branch back into the trunk is done by the managers of the branch. ...

Note above resource did not appear in any of the searches I performed (CVS related guidelines aren't popular anymore?)

Best practices in SCM (perforce article) at

http://www.perforce.com/perforce/papers/bestpractices.html

...six general areas of SCM deployment, and some coarse-grained best practices within each of those areas. The following chapters explain each item...

Workspaces, Codelines, Branching, Change Propagation, Builds, Process...

Title: To branch or not to branch?


问:
How to organize Javascript and AJAX with PHP?
My javascript is getting out of hand for my PHP application. I have 20  tags that link to various javascript files in a javascript folder.
Each javascript file basically controls one element on the DOM. And, if the javascript file uses AJAX, then it will have a corresponding PHP file that the AJAX will call.

For example, a js file might control a button on the page:

```<code>$(document).ready(function () {
  $("#button").live('click', function() {
    $.ajax({
      type: "POST",
      data: ...
      url: "button_click.php",
    });
  });
});
</code>```

As you can see, this gets out of hand. What is the best way to organize all of the javascript?

答:
One trick I picked up from a JavaScript library I've been using is to write all my code in separate files but then use a separate "build" script (they used PHP, I use Python, whatever) to "compile" your separate files into a single file and run a minimizer on it.

At first this felt pretty hack-ish, but after just a little while it became quite comfortable. While developing I point the page to the single non-minimized script so that I'll see line numbers while debugging, and then I deploy the minimized script.

ContentLicense: CC BY-SA 3.0


问:
Have objects delivered in terms of code reuse?
I have often heard it said that objects have not delivered in terms of code reuse. Do you agree? If you believe that they haven't, why not?</p>

答:
No, not necessarily.

Objects deliver better semantics, organization of code/functionality and, possibly, ease-of-use.

Well designed libraries deliver on the promise of code reuse, not objects per se.

ContentLicense: CC BY-SA 2.5


问:
What core skills does a new Computer Science Graduate need to be employable?
A computer science degree (like any undergraduate degree) does not prepare you to be productive immediately. And my sense is that employers are less and less willing to provide that initial training. (Or at least if you DO have those core skills*, you have a broader selection of "first jobs" to choose from).

What skills should a senior focus on to make him/her self more employable?
And how might you get those skills?

*EDIT: I'm not talking about experience/mastery of technology. I'm talking about core skills like Source Control (not mastery of a particular SC, but just being able to use one an understanding the concepts) and Unit Testing (having written Unit Tests using at least some famework), etc.

答:
One way to set yourself apart from other new graduates, other than GPA and being able to demonstrate good general problem solving skills during an interview, is a presentable breadth of appropriate experience (even if not as an employed professional).  There are multiple options, not limited to:

Rent a VM in the cloud, install the complete server stack, write and deploy some application, stick it on your web page, and keep it running.

Business plan, design, code, debug/test an attractive and functional iOS or Android app, get it in the app store, market it, and provide customer support.

Build, program and compete in some robotics contest.

Some well written addition to an OSS project that's popular on Github, et.al.

Etc.

e.g. Take the initiative, and do something other than schoolwork that an interviewer in your business category of choice will recognize as closer to real work versus homework.


问:
With agile, what do when a user story doesn't get completed in an iteration?
Do you just move the story to a new iteration, or delay the next iteration?

It gets a bit tricky when you use something like Jira when you have to copy or move around stories between iterations as it effects calculations of velocity/points etc.

Is there a best-practice?

答:
We do a variation on some of the answers given.

You estimate a sprint at a given amount of points, let's say 34.  If after we reach the designated end point for the sprint and we have not finished, we go into a remedial sprint.

What this means is:

We get credit for the 34 points.

We have to finish the story that we were working on.  It was the
highest priority on the backlog at the time of assignment, so it
maintains that priority.

We task and work on the given story until we meet our definition
of done.  This amount of time is assigned 0 story points.  This serves to adjust our velocity.

OwnerDisplayName: codecompleting


问:
How should I communicate the specifics of cloud computing (as compared to other)
A meeting today went well where I explained that cloud computing which one of the persons recognized was something else than a traditional RDBMS and I said that cloud computing is that everthing is software. It didn't seem like "Aha!" when I said it so I wonder what I should say. I thought the main specifics of cloud computing are integrated services, no traditional RDBMS and resources are allocated as software and payment model is pay per usage instead of pay per hardware. And/or should I stress the concept of PaaS i.e. that it is a platform?

Wikipedia says the distinction is between products and services but that we said about web services 15 years ago.

Thanks in advance for you answers

答:
The term "cloud" has a high emotional content and little well defined, specific informational content.

If you're trying to explain things, avoid the use of the term "cloud". You may look up and use  the definition of terms like IaaS, PaaS, SaaS, depending on what you mean when you say "cloud".

If you're trying to sell things, you should definitely say "cloud" as often as possible.


问:
Why are interfaces useful?
I have been studying and coding in C# for some time now. But still, I can't figure the usefulness of Interfaces. They bring too little to the table. Other than providing the signatures of function, they do nothing. If I can remember the names and signature of the functions which are needed to be implemented, there is no need for them. They are there just to make sure that the said functions(in the interface) are implemented in the inheriting class.

C# is a great language, but sometimes it gives you the feeling that first Microsoft creates the problem (not allowing multiple inheritance) and then provides the solution, which is rather a tedious one.

That's my understanding which is based on limited coding experience. What's your take on interfaces? How often you make uses of them and what makes you do so?

答: Interfaces by themselves are not very useful. But when implemented by concrete classes you see that it gives you the flexibility to have one or more implementations. The bonus is that the object using the interface do not need to know how the details of the actual implementation go - that's called encapsulation.</p>

Title: Why are interfaces useful?


问:
Most useful features of VIM that aren't standard in a IDE
I'm considering whether I should start using VIM again instead of an IDE. What are the most useful features of VIM that aren't standard in an IDE?</p>

答:
Table Column Select

This doesn't seem to be in the popular IDEs, and if it is they keep it well hidden. This is really handy for testing regex against a column in CSV data file.


问:
Is it worth evaluating compiler optimization on trivial cases?
I'm currently testing Visual C++ 10 on some trivial pieces of code. For example, like this one (taken from here):

```<code>int main()
{
    int i;
    clrscr();
    for(i=0,i++,i<=5;i++,i<=2;i=0,i<=5,i+=3){
        printf("%d ",i);
    }
    return 0;
}
</code>```

For the code above the compiler emits machine code that in effect does this:

```<code>clrscr();
printf("%d ",2);
return 0;
</code>```

and this makes me happy. Sometimes the compiler emits really dumb code and then I file a Microsoft Connect feedback item.

I have the following concern. Is testing a compiler on trivial code worth it?

On one hand, we want real code to be compiled as good as possible, not some stupid sample snippets.

On the other hand, compiler optimization is recursive in sense that if code B follows code A and the compiler can see that code B does nothing it can eliminate code B and eliminate whatever connected A and B logically and thus optimize (and maybe eliminate) code A better. And if the compiler fails to optimize away code B it will likely not be able to optimize code A either. So every improvement of generated code matters - better code at some point can mean better code elsewhere and this is beneficial.

Is it worth testing compilers on trivial samples or are only tests on "real code" worthy?

答:
The optimizations you need a compiler to do are for the kinds of code that take time in practice.
So it's a waste of time to try to find little weird cases that it does or doesn't do.

In fact, in some kinds of applications, compiler optimizations make no difference whatever, such as nearly every Windows app.
If you take stack samples of such an app, as I do regularly, you find at nearly any random instant of time the call stack is at least several layers deep.
The tip of the stack is either in some blocked system call, or executing instructions somewhere in the sub-basement of a system library.

In other words, in this type of app, it's almost impossible to catch the IP in code that your compiler compiled, and that's the only time the cycle-squeezing could even matter.

ADDED: Don't get me wrong. These apps can certainly be optimized. It's just that you can't expect the compiler to do it.
This is the method I use.


答:
A real world implementation:

You can cast an object as the Interface type:

```<code>IHelper h = (IHelper)o;
h.HelperMethod();
</code>```

You can create a list of an interface

```<code>List<IHelper> HelperList = new List<IHelper>();
</code>```

With these objects you can access any of the interface methods or properties. In this manner you can define an interface for your part of a program.  And build the logic around it.  Then someone else can implement your interface in their Business objects.  If the BO's change they can change the logic for the interface components and not require a change to the logic for your piece.

Title: Why are interfaces useful?

Body:
I have been studying and coding in C# for some time now. But still, I can't figure the usefulness of Interfaces. They bring too little to the table. Other than providing the signatures of function, they do nothing. If I can remember the names and signature of the functions which are needed to be implemented, there is no need for them. They are there just to make sure that the said functions(in the interface) are implemented in the inheriting class.

C# is a great language, but sometimes it gives you the feeling that first Microsoft creates the problem (not allowing multiple inheritance) and then provides the solution, which is rather a tedious one.

That's my understanding which is based on limited coding experience. What's your take on interfaces? How often you make uses of them and what makes you do so?

Body:
A real world implementation:

You can cast an object as the Interface type:

IHelper h = (IHelper)o;
h.HelperMethod();

You can create a list of an interface

List<IHelper> HelperList = new List<IHelper>();

With these objects you can access any of the interface methods or properties. In this manner you can define an interface for your part of a program.  And build the logic around it.  Then someone else can implement your interface in their Business objects.  If the BO's change they can change the logic for the interface components and not require a change to the logic for your piece.


问:
Is there a freelance website dedicated to high-end work, like writing compilers?
I've read through the previous posts on freelance websites and used most of them. I'm looking for a website dedicated to high-end professionals and high-end work. Such as writing software compilers, designing database engines, etc.

Probably no such website exists (there would have to be some kind of moderation), but I'm really hoping there is one, both as an employer and as a developer.

答: Unfortunately, I don't think a such thing exists. This may (or may not) be due to the fact that most of these technologies are either a) open source and thus driven by the OS community (not freelancing), or b) are driven by large corporations who covet their IP and sharing it with a freelancer would be the last thing on earth in their minds (other than hiring a consultant for a contract, but that would be done directly through the company and not a freelance system).</p>


问:
Extracting user requirements from a person who does not know how to express himself
I had an interview yesterday with a member of our organization who wanted to create a system to help him to do his job, the problem I had with him was that he had only a general idea about what he want. I tried to get more information from him by asking him specific questions which he had no answer to, such as what he expects to see in the first page when he opens the system..I told him that we will meet again in a few days because I wanted to think of a different approach to get clear requirements of him.

My question is what type of questions should I ask to get what he exactly wants, is there a guide that can help me go through this successfully?

答:
If holding him by the ankles and shaking firmly doesn't work, you can try writing the entire application then showing it to him and having tell you why most of it is wrong.  It's usually a lot easier for people to say why the don't like something than to tell you what they do want (which would be a lot more helpful to you).

If that takes too long, mocking it up in the simplest possible way that answers your questions and having him agree in writing that it's everything he wants might work.  Hopefully your mockup is informed by an understanding of what he's trying to accomplish.

He most likely will want to make all kinds of changes, but at least you will be able to justify that the reason it's taking so long is that he's feeling his way through what he wants and making you change it as he does so.  Stick with mockups as long as you can to minimize wasted time.

You can look up agile development (a giant topic) for further ideas - its a method that assumes everybody doesn't know up front everything they want to do.


答:
There are a couple of different ways I'd suggest approaching this:

Job shadowing -> This is basically watching him do his job so that you know what he is doing and what connections are there between the systems and processes he uses to get his job done.  This is totally observation from your end where questions may be asked but only to get a general idea of what something is.

Prototyping -> Try to walk through a paper-based version of how he would interact with the system.  What parts does he do and what does he expect the system to do automatically?

In both cases you are trying to collect information from watching the experience of what is happening rather than asking him questions.  There are a variety of reasons why he may not be able to answer your questions:

Lack of self-awareness - perhaps he can't observe himself that well and thus doesn't know all that he does.  For example, some people may be able to get from A to B but they couldn't give you directions because they don't know the streets or distances they drive before each turn.

Lack of articulation - perhaps he can't articulate the process and thus while he knows what he does, he can't put it words well.

Lack of structure - perhaps he can't put all the pieces together to answer your question.

Title: Extracting user requirements from a person who does not know how to express himself

Body:
I had an interview yesterday with a member of our organization who wanted to create a system to help him to do his job, the problem I had with him was that he had only a general idea about what he want. I tried to get more information from him by asking him specific questions which he had no answer to, such as what he expects to see in the first page when he opens the system..I told him that we will meet again in a few days because I wanted to think of a different approach to get clear requirements of him.

My question is what type of questions should I ask to get what he exactly wants, is there a guide that can help me go through this successfully?


答:
I blogged about this last week. This can be very frustrating sometimes.

I'd start by asking questions like...

What would make your job easier?

What don't you like about how you do your job?

Fill in the blanks... If I could to blank instead of blank it would make my work a lot easier.

You may have to have him show you what he's talking about. If that's the case then go visit him in his surroundings (it's more comfortable for him). Have him show you what he does and what he's like to do instead. Listen, I mean really listen. Try to understand as much about what he's doing without offering up changes or solutions or criticisms.

Once you have established a rapport with him he's more likely to open up and discuss what he really needs.

Then you can have him work backwards from what the expected output he wants and how to go about creating that output for him.


答:
Ask them how they do their job now. Presumably they know that. From their description of their job, listen for clues that they collect information from someone. They might currently be writing in on post it notes, remember it in their head or if you're lucky, filling in an existing paper form, or if you are really lucky, into an existing computer system.

Much of what they do has nothing to do with information management, such as judging when a hair cut is done.  But some of it will pertain to information, such as putting the money in the cashbox when the customer leaves (which is the same as filling in the amount received box and then inserting data in the  receipts table).

Requirements gathering is an unsolved problem in computer science. Most advice is a sham, where we are imaging that typical line of business application consumers are capable of doing low level specifications just by asking them.

Another idea is to present a variety of options based on your own fuzzy understanding, and then once the customer has something to look at (drawn on paper of course, it's too soon to write substantial code) get some feed back and iteratively try to go from their. Again, depending on your customer, they might not do a good job of imagining themselves using the application, so be wary of thinking that even then that their feedback is final or an accurate representation of what they want.


答: You can always take a fast first pass at it, maybe with some mockups. A lot of times that will get people going... it's easier for them to point at something and say yes or no.</p>


答: The . command. It repeats the last command.

Title: Most useful features of VIM that aren't standard in a IDE

Body: I'm considering whether I should start using VIM again instead of an IDE. What are the most useful features of VIM that aren't standard in an IDE?</p>


问:
Is programming a profession not for a person with speech impairment?
My friend has 15 years of programming experience and Ph.D. in mathematics. He has also cerebral palsy with speech impairment. Because of his handicap, he chose to being a software developer after his Ph.D. As far as I can see, he is still an excellent c# developer.

Nowadays, however, he has hard time to find a job for himself because most of developer jobs require good communication skills. Looking at him struggling so much, do I have to advise him software industry is not suitable for him any more? It will be extremely difficult for me to do that to the friend but I think it would be better than making him wasting his time.

What do you think?

Update: Thanks a lot for your excellent answers. I can see most answers recommend against my advice and I really really hope you guys are right. In reality, however, he has been rejected in 100 or so phone interviews. That's where I want to be a potential bad adviser rather than a politically right friend.

答:
In reality, however, he has been rejected in 100 or so phone
  interviews.

Perhaps what he needs to do is tell people up front that he has a speech impediment and that it would be better to do the intial screening in person.


答: I'm sure the speech impediment is making things harder for him in his job search (especially interviewing). However I think software development is still where he belongs (I mean, 15 years experience!) so I wouldn't advise him to try elsewhere; I would just commiserate with him over the definitely tough job market.</p>

Title: Is programming a profession not for a person with speech impairment?

Body:
My friend has 15 years of programming experience and Ph.D. in mathematics. He has also cerebral palsy with speech impairment. Because of his handicap, he chose to being a software developer after his Ph.D. As far as I can see, he is still an excellent c# developer.

Nowadays, however, he has hard time to find a job for himself because most of developer jobs require good communication skills. Looking at him struggling so much, do I have to advise him software industry is not suitable for him any more? It will be extremely difficult for me to do that to the friend but I think it would be better than making him wasting his time.

What do you think?

Update: Thanks a lot for your excellent answers. I can see most answers recommend against my advice and I really really hope you guys are right. In reality, however, he has been rejected in 100 or so phone interviews. That's where I want to be a potential bad adviser rather than a politically right friend.


答:
Interfaces are to coding objects like a plug is to household wiring. Would you solder your radio directly to your house wiring? How about your vacuum cleaner? Of course not. The plug, and the outlet it fits into, form the "interface" between your house wiring and the device that needs the power from it. Your house wiring needs to know nothing about the device other than it uses a three-prong grounded plug and requires electrical power at 120VAC <=15A. Conversely, the device requires no arcane knowledge of how your house is wired, other than that it has one or more three-prong outlets conveniently located that provide 120VAC <=15A.

Interfaces perform a very similar function in code. An object can declare that a particular variable, parameter or return type is of an interface type. The interface can't be instantiated directly with a new keyword, but my object can be given, or find, the implementation of that interface that it will need to work with. Once the object has its dependency, it doesn't have to know exactly what that dependency is, it just has to know it can call methods X, Y and Z on the dependency. Implementations of the interface don't have to know how they will be used, they just have to know they will be expected to provide methods X, Y and Z with particular signatures.

Thus, by abstracting multiple objects behind the same interface, you provide a common set of functionality to any consumer of objects of that interface. You don't have to know the object is, for example, a List, a Dictionary, a LinkedList, an OrderedList, or whatever. Because you know all of these are IEnumerables, you can use the methods of IEnumerable to go through each element in these collections one at a time. You don't have to know that an output class is a ConsoleWriter, a FileWriter, a NetworkStreamWriter, or even a MulticastWriter that takes other types of writers; all you have to know is that they're all IWriters (or whatever), and thus they have a "Write" method that you can pass a string into, and that string will be output.

Title: Why are interfaces useful?


答:
I always explain "the cloud" by analogy to the electrical grid.

With "the grid", you don't need to run a generator or power plant. You don't need to buy fuel directly. You simply pay someone to keep electricity going to you. When you need electricity, you flip a switch and take what you want. You don't have to think about where the electricity is being produced or how it is getting to you -- that's the electric company's problem. They bill you every month for what you use.

The downsides are much the same too. If the grid has a failure, you go dark. And there's not much you can do about it except complain.

To some extent, you can think about it as "storage as a service".

Title: How should I communicate the specifics of cloud computing (as compared to other)

Body:
A meeting today went well where I explained that cloud computing which one of the persons recognized was something else than a traditional RDBMS and I said that cloud computing is that everthing is software. It didn't seem like "Aha!" when I said it so I wonder what I should say. I thought the main specifics of cloud computing are integrated services, no traditional RDBMS and resources are allocated as software and payment model is pay per usage instead of pay per hardware. And/or should I stress the concept of PaaS i.e. that it is a platform?

Wikipedia says the distinction is between products and services but that we said about web services 15 years ago.

Thanks in advance for you answers


问:
How can I advocate unit testing on private code?
I'm trying to advocate unit testing in my workgroup, but an objection I often get is that it should be used only for externally exported API (which is only a minimal and non critical part of our system), and not on internal and private code (which now has only functional testing).

While I think that unit test can and should be applied to all the code, how can I persuade my coworkers?

答:
The reasons for using unit tests on internal/private code are precisely the same as for externally supported APIs:

They prevent bugs from recurring (unit tests form part of your regression test suite).

They document (in an executable format!) that the code works.

They provide an executable definition of what "the code works" means.

They provide an automated means of demonstrating that the code does indeed match specs (as defined by the point above).

They show how the unit/class/module/function/method fails in the presence of unexpected input.

They provide examples on how to use the unit, which is great documentation for new team members.


答:
It is my general experience that end users don't know what they want. They know what they like and what they don't like. They know what is hard and what is easy, but the don't actually know what they want and don't want.

Start by asking them about the current way they do things. Ask what they like about this way and what they don't like. Ask what is the hardest part of the current system. Ask what shortcuts they currently use to make the current system more manageable.

Next ask what they have to do every time they do a process. Is there a form they have to look at every time? Is there some data they have to look up before they start? What metrics are most important to them.

Sit down and watch them actually go through the current system while they do a few tasks. Ask questions.

Finally, sit down and mock something up. Some screen shots or if you can a dummy page that doesn't actually do anything but allows the user to seen interactions and such. Get the user to look at it and use it. They will tell you what they like and what they don't like. They will ask you questions why things are where they are. Ask them questions to get better feedback.

I really find showing the user something gives them something to talk about. It makes sure everyone is mostly on the same page, and it helps you know that you are making something they can use.


问:
Io (Language) IDE/Compiler
Can you recommend a free compiler/IDE for writing some simple Io programs?

I want to learn the language at home in my spare time.

答:
You should be able to download the compiler and runtime environment from the link you provided. I don't think there are any pre-packaged versions of the compiler/runtime environment , so you'll likely have to build/compile it yourself. Check out the documentation here: http://www.iolanguage.com/scm/io/docs/IoGuide.html for build/install instructions.

AFAIK, IO doesn't currently have a nice graphic UI like you might see in Smalltalk or Self. You'll most likely find yourself editing scripts in your favorite text editor, and then running them from the command line.

Title: Io (Language) IDE/Compiler


问:
Next in Concurrency
For past year I have been working a lot on concurrency in Java and have build and worked on many concurrent packages. So in terms of development in the concurrent world, I am quite confident. Further I am very much interested to learn and understand more about concurrent programming.

But I am unable to answer myself what next? What extra should I learn or work on to inherit more skills related to Multi-core processing. If there is any nice book (read and enjoyed 'concurrency in practice' and 'concurrent programming in java') or resource's related to Multi-core processing so that I can go to the next level?

答:
The D programming language provides two paradigms for concurrent programming, both of which have their uses and are rather interesting.

std.concurrency provides message passing with no default memory sharing.  All global and static variables in D are thread-local by default and spawn and send do not allow sending messages that contain mutable pointer indirection.  Limited sharing can be obtained via the shared keyword, which entails additional checking by the type system.  Outside the safe dialect of the language you can force classic C/Java-style global/shared variables using the __gshared keyword, but all bets are off then as far as race safety.  This model is detailed in a free chapter of Andrei Alexandresu's book "The D Programming Language".

std.parallelism is less safe but in some ways more flexible than std.concurrency and is geared specifically towards multicore data and task parallelism for increasing data processing throughput rather than general-case concurrency.  It features a parallel foreach loop, asynchronous function calls, parallel reductions, etc.  It provides mechanisms to make it easier to write race-safe code but doing so still requires some degree of discipline.

A more thorough discussion about the two major multithreading paradigms in D can be found in my recent article on the subject.

Title: Next in Concurrency


问:
Does TDD's "Obvious Implementation" mean code first, test after?
My friend and I are relatively new TDD and have a dispute about the "Obvious Implementation" technique (from "TDD By Example" by Kent Beck). My friend says it means that if the implementation is obvious, you should go ahead and write it - before any test for that new behavior. And indeed the book says:

How do you implement simple operations? Just implement them.

Also:

Sometimes you are sure you know how to implement an operation. Go ahead.

I think what the author means is you should test first, and then "just implement" it - as opposed to the "Fake It ('Till You Make It)" and other techniques, which require smaller steps in the implementation stage. Also after these quotes the author talks about getting "red bars" (failing tests) when doing "Obvious Implementation" - how can you get a red bar without a test?.

Yet I couldn't find any quote from the book saying "obvious" still means test first.

What do you think? Should we test first or after when the implementation is "obvious" (according to TDD, of course)? Do you know a book or blog post saying just that?

答:
I agree with your interpretation - it is still Red Green Refactor, only with the Refactor bit left out ;)

So, write a failing test first, then implement the obvious solution instead of slowly building up a design of "the simplest possible" one.


答:
Do you know a book or blog post saying just that?

I would argue that Beck's book says just that.

He goes on to say

However, by using only Obvious Implementation, you are demanding perfection of
  yourself. Psychologically, this can be a devastating move.
  What if what you write isn't really the simplest change that could get the test to pass?
  What if your partner shows you an even simpler one? You're a failure! Your world
  crumbles around you! You die. You freeze up.

How can you get the test to pass by writing the code if it doesn't exist before the code does?

Title: Does TDD's "Obvious Implementation" mean code first, test after?

Body:
My friend and I are relatively new TDD and have a dispute about the "Obvious Implementation" technique (from "TDD By Example" by Kent Beck). My friend says it means that if the implementation is obvious, you should go ahead and write it - before any test for that new behavior. And indeed the book says:

How do you implement simple operations? Just implement them.

Also:

Sometimes you are sure you know how to implement an operation. Go ahead.

I think what the author means is you should test first, and then "just implement" it - as opposed to the "Fake It ('Till You Make It)" and other techniques, which require smaller steps in the implementation stage. Also after these quotes the author talks about getting "red bars" (failing tests) when doing "Obvious Implementation" - how can you get a red bar without a test?.

Yet I couldn't find any quote from the book saying "obvious" still means test first.

What do you think? Should we test first or after when the implementation is "obvious" (according to TDD, of course)? Do you know a book or blog post saying just that?


答:
It sounds like you're trying to get him to describe the solution rather than the problem.  Non-programmers have a very difficult time thinking about software that way.  To them, it's an unchangeable product rather than a flexible collection of components.

What you need at this point is a thorough problem description.  He has no idea what the opening screen should look like as long as it solves his problem and doesn't introduce new ones.

For example, my wife told me she was looking for new budget software because with our current software she never knows how much money is really available.  This surprised me because our current software is always synced with the bank and breaks things into nice categories, notifying us when we get too close to the budgeted amount.  I asked why that wasn't enough, and she said it's too much work to keep up with entering receipts that haven't cleared yet, which often are for significant amounts, and there's no way to forecast based on transactions planned in the future.  By the time transactions clear the bank it's too late to be useful in planning.

Notice she's describing the problem, not the solution.  Part of the solution she didn't know she needed was a smartphone app with an ultra simple interface to quickly view the available budget by category and enter receipt amounts at the point of sale, and which automatically syncs the transactions to a more full featured application for use at home.  As soon as I presented that to her, she said it fit her requirements perfectly, but she said she would have never thought of it on her own.

In other words, you need to gather requirements from the customer's point of view of the problem that needs solving, and leave the design details to the software professional.  On the occasions when customers do care about the details, they usually have no problem letting you know.  It's your job to present the design incrementally enough to allow them to provide feedback without causing yourself too much potential rework.


问:
Integration tests across a 3-tier .NET solution
I have a 3-tiered .NET solution.

Database (SQL SERVER 2008)

Web Service (SOAP Service - *.asmx)

WPF Client

I am comfortably writing Unit Tests within (3) The Client.

I am currently working on writing tests between (1)Database & (2)Service.

My question is, what are some useful ways to run integration tests across all 3 tiers.  I would like this to run locally in my Test Runner, as well as part of the integration test.

Primarily, I am stuck on how to have a transient (setup-teardown-able) (2) Web Service & (1) Database that can be tested with (3) Client code as part of a full integration test.

答:
Depending on your tooling this can be quite easy, but not very 'textbook'.

We use:

VS

Microsoft Test Manager

SCVMM + Lab Management features of MTM

In our case (I'm an SDET in QA), our application takes roughly 30 minutes to install, and we have a similar architecture (DB, App Tier, Presentation Tier - web and applications). Because a whole install/config would be intractable for testing, we have an installation/configuration test suite which is essentially OrderedUnitTests that will spin up a VM, confirm pre-reqs, install the product and configure everything.

From there we have the test suites. Some are targeted at the app tier (services) where it's a normal "unit test" (VS parlance, actual unit tests are part of the build and doesn't even go to QA unless they pass) that creates does whatever setup is necessay, calls the service(s) and asserts results - cleaning the DB changes in teardown as usual.

For the Presentation Tier we have webtests that will run or codedui tests that will start whatever app or site is under test, perform the actions, assert the results and then close everything back down to the desktop.

It's pretty straight-forward and works well.


答:
Obviously there are no hard and fast rules here, were being agile after all so we can and should adapting as we iterate :)

Partly it will depend on the simple operation, and as you practice TDD more and more you will regularly find stuff you tested badly or actually didn't really test at all, it's all part of the learning curve.

Also don't forget that TDD allows you test the interface and the implementation before committing it to live code.

You may know how to implement something but how often do you write a perfect class/method etc. first time without some tweaks along the way or stepping through the code once or twice and six-months later when you change something you can do so with more confidence and again in the sandbox of the tests.

Of course, tests don't mean you write the code any more correctly first time but your changes are driven by the test and tests become the first client of the code and as tests are very low-cost and more importantly no-risk to change you have more confidence and freedom whilst developing.

If your really trying to get good coverage and higher quality then err on the side of more tests to start with, as you practice TDD more and more you will develop you own sense of the level of coverage you need.


问:
What are the benefits of using comments
I just accepted a new job. Our application is in the 50,000 lines of code area. None of which is commented. I am finding it difficult to understand how the application works. Id like to prevent this for the next person that joins the project by getting the team to start to use comments.

Forget about if you support comments or consider them code duplication. What are some of the benefits of using comments that I can use as reasons for the team to start using them. What arguments are there in favor of comments (Not looking for opposing arguments). Are there any publications or studies done that show that using comments improves code quality or something like that?

答:
Clean Code has a whole chapter on comments, when they're good and when they're not.  Also a lot of practical advice on how to write code that doesn't need so many comments.

Edit: Anna asked for a summary, and since you were asking only for pro-comment reasons, the table of contents level summary of good reasons to use comments from the book includes:

Legal notices, like copyrights

When you can't use a function name to explain something

Your intent behind a decision

Clarification of code you can't alter, like library call results

Warning of consequences

TODOs (to a reasonable degree)

Amplify the importance of something seemingly inconsequential

Javadocs in public APIs

There's a couple paragraphs or more on each of those topics, with actual code samples included for illustration.  It really is a worthwhile read.

Title: What are the benefits of using comments


答:
Useful points of comments:

Identify why there is a method to do X.

Identify what are the inputs/outputs of a method so that it is clear if parameters should be tweaked,e.g. if passing in a number of milliseconds or seconds there may be adjustments to make.

Identify side effects of a method,e.g. are there other things it does that one may want to know besides its initial intentions?  (This should be rare of course)

Put a note in the code that something has a "code smell" and is worth considering refactoring somehow.

Put a note in the code to explain why a kludge was shoved into the place that it is, which is rather similar to the previous point.

Title: What are the benefits of using comments

Body:
I just accepted a new job. Our application is in the 50,000 lines of code area. None of which is commented. I am finding it difficult to understand how the application works. Id like to prevent this for the next person that joins the project by getting the team to start to use comments.

Forget about if you support comments or consider them code duplication. What are some of the benefits of using comments that I can use as reasons for the team to start using them. What arguments are there in favor of comments (Not looking for opposing arguments). Are there any publications or studies done that show that using comments improves code quality or something like that?


问:
SQL: empty string vs NULL value
I know this subject is a bit controversial and there are a lot of various articles/opinions floating around the internet. Unfortunatelly, most of them assume the person doesn't know what the difference between NULL and empty string is. So they tell stories about surprising results with joins/aggregates and generally do a bit more advanced SQL lessons. By doing this, they absolutely miss the whole point and are therefore useless for me. So hopefully this question and all answers will move subject a bit forward.

Let's suppose I have a table with personal information (name, birth, etc) where one of the columns is an email address with varchar type. We assume that for some reason some people might not want to provide an email address. When inserting such data (without email) into the table, there are two available choices: set cell to NULL or set it to empty string (''). Let's assume that I'm aware of all the technical implications of choosing one solution over another and I can create correct SQL queries for either scenario. The problem is even when both values differ on the technical level, they are exactly the same on logical level. After looking at NULL and '' I came to a single conclusion: I don't know email address of the guy. Also no matter how hard i tried, I was not able to sent an e-mail using either NULL or empty string, so apparently most SMTP servers out there agree with my logic. So i tend to use NULL where i don't know the value and consider empty string a bad thing.

After some intense discussions with colleagues i came with two questions:

am I right in assuming that using empty string for an unknown value is causing a database to "lie" about the facts? To be more precise: using SQL's idea of what is value and what is not, I might come to conclusion: we have e-mail address, just by finding out it is not null. But then later on, when trying to send e-mail I'll come to contradictory conclusion: no, we don't have e-mail address, that @!#$ Database must have been lying!

Is there any logical scenario in which an empty string '' could be such a good carrier of important information (besides value and no value), which would be troublesome/inefficient to store by any other way (like additional column). I've seen many posts claiming that sometimes it's good to use empty string along with real values and NULLs, but so far haven't seen a scenario that would be logical (in terms of SQL/DB design).

P.S. Some people will be tempted to answer, that it is just a matter of personal taste. I don't agree. To me it is a design decision with important consequences. So i'd like to see answers where opion about this is backed by some logical and/or technical reasons.

答:
While agreeing with the above comments, I would add this argument as a primary motivation:

It is obvious to any programmer looking at a database that a field marked NULL is an Optional field. (i.e. the record doesn't require data for that column)

If you mark a field NOT NULL, any programmer should intuitively assume that it is a Required field.

In a field that allows nulls, programmers should expect to see nulls rather than empty strings.

For the sake of Self-Documenting Intuitive Coding, use NULL instead of empty strings.

Title: SQL: empty string vs NULL value


问:
Why is the 'final' keyword used so little in the industry?
Since I discovered the powers of the final keyword in Java a few years ago, it helped me to make my codes a lot more readable, since people can easily see what are read-only variables. It may also provide a little boost to the JIT, and while that's a very limited one, it can't harm, especially when targeting embedded devices such as android platforms.

But more than everything, it contributes to make a design more robust to changes, and guide other committers when they need to modify the code base.

However, while browsing some of the JDK source code, I never stumbled upon this keyword, either for classes, methods, or variables. The same applies for various systems I had to review.

Is there a reason? Is it a common design paradigm to let everything mutable from the inside?

答:
The problem with using final to convey that something is read-only is that it only really works for primitive types like int, char etc. All objects in Java are actually referred to using a (kind of) pointer. As a result, when you use the final keyword on an object, you are only saying that the reference is read-only, the object itself is still mutable.

It might have been used more if it did actually make the object read-only. In C++ that's exactly what const does and as a result it is a much more useful  and heavily used keyword.

One place I use the final keyword heavily is with parameters to avoid any confusion created by things like this:

```<code>public void someMethod(FancyObject myObject) {
    myObject = new FancyObject();
    myObject.setProperty(7);
}
...
public static void main(final String[] args) {
    ...
    FancyObject myObject = new FancyObject();
    someOtherObject.someMethod(myObject);
    myObject.getProperty(); // Not 7!
}
</code>```

In this example it seems obvious why this doesn't work but if someMethod(FancyObject) is big and complicated confusion can ensue. Why not avoid it?

It's also part of the Sun (or Oracle now I guess) coding standards.

OwnerDisplayName: Aurélien Ribon

Body:
The problem with using final to convey that something is read-only is that it only really works for primitive types like int, char etc. All objects in Java are actually referred to using a (kind of) pointer. As a result, when you use the final keyword on an object, you are only saying that the reference is read-only, the object itself is still mutable.

It might have been used more if it did actually make the object read-only. In C++ that's exactly what const does and as a result it is a much more useful  and heavily used keyword.

One place I use the final keyword heavily is with parameters to avoid any confusion created by things like this:

public void someMethod(FancyObject myObject) {
    myObject = new FancyObject();
    myObject.setProperty(7);
}
...
public static void main(final String[] args) {
    ...
    FancyObject myObject = new FancyObject();
    someOtherObject.someMethod(myObject);
    myObject.getProperty(); // Not 7!
}

In this example it seems obvious why this doesn't work but if someMethod(FancyObject) is big and complicated confusion can ensue. Why not avoid it?

It's also part of the Sun (or Oracle now I guess) coding standards.


问:
Where can I find high-quality resources for programmers who are not-English speakers?
I've recently reviewed a resume for a very promising student who is not a native English speaker (I believe his native language is Bengali).

His academic record has some gaps, too - he could use a couple of solid data-structure and algorithms type courses.

Where would you advise this student to look, in order to find programming/training resources that are likely to be good quality, and in his native tongue? He is far from fluent, and has indicated that the language barrier is too high for him to try a course that's taught in English.

Is it even possible for him to both study English and fill in the gaps in his training at the same time, or would you advise that he just do the two serially?

答:
Is it even possible for him to both study English and fill in the gaps in his training at the same time, or would you advise that he just do the two serially?

Not only possible, but based on my experience I strongly recommend to do that concurrently. I wasted 10+ years at courses and such (not quite wasted but pretty close) until I was forced to dig through programming manuals - which magically made it all to me.

Another advice I'd pass to this guy - if he has some kind of hobby or I dunno some non-programming topic he's interested in (travel? books? kids? religion? whatever) - by all means find some English-speaking resources / forums / clubs / whatever to participate. To me, this made a tremendous boost in studying the language


答:
To the maximum extent possible, code should be self-describing.  That is, it should be written clearly enough to be understandable without comments.  This results in code that is more maintainable by others, and eliminates the redundancy that comments cause (when you change the code, you also have to update the comments).

However, comments are critical for describing the relationships between code objects and different parts of the system, and how to properly use your code  once it is written. In other words, how all the pieces of your application or library work together.  Developers who advocate writing no comments at all build large, opaque, indeciperable systems because they don't fully appreciate this point.

Uncle Bob Martin, in his book Clean Code, advocates using comments for the following purposes:

Explanation of Intent

Clarification

Warnings

Amplification

TODOs

At a minimum, comments should describe what each public member does and how to use it, and explain all parameters and return values with acceptable ranges (e.g. between 1 and 1000) for each.

Title: What are the benefits of using comments


答:
At least in my experience, I dislike training materials or textbooks written in my native language. Often it's bad translation, and most English words seems to be common usage in the field (ie. I've always says linker even when talking in Portuguese, never montador which is a term most people never heard actually and it's only used in old textbooks).

A few universities offer intensive language studies courses and, in my experience, if you find yourself immersed in other culture you pick up the language fairly quickly.

Is he going to be "graded" (or measured in any way) by his  academic performance in the "gap filling" courses? If yes, then do it serially. It would be unfair to him, since for part of the course his capabilities to understand are going to be impaired due to the language barrier. If not, do it simultaneously. Being immersed is the best way to learn a language. (I never took a formal course in English and while I know my English is not that good, most native speakers seems to be able to understand what I'm saying. And in the end, that's what matters most.)

Title: Where can I find high-quality resources for programmers who are not-English speakers?

Body:
I've recently reviewed a resume for a very promising student who is not a native English speaker (I believe his native language is Bengali).

His academic record has some gaps, too - he could use a couple of solid data-structure and algorithms type courses.

Where would you advise this student to look, in order to find programming/training resources that are likely to be good quality, and in his native tongue? He is far from fluent, and has indicated that the language barrier is too high for him to try a course that's taught in English.

Is it even possible for him to both study English and fill in the gaps in his training at the same time, or would you advise that he just do the two serially?


答:
I suspect that the reason you don't see it is because the JDK is designed to be extended (it is the base from which all of your programs are built on). It wouldn't be uncommon at all for application code to make use of it. I also wouldn't expect to see a lot of it in library code either (as libraries are often designed for extension as well).

Try taking a look at some good open source projects and I think you'll find more.

By contrast to what you're seeing in Java, in the .NET world, I've heard the argument many times that clases should be sealed (similar to final applied to a class) by default, and that the developer should explicitly un-seal it.

Title: Why is the 'final' keyword used so little in the industry?

Body:
Since I discovered the powers of the final keyword in Java a few years ago, it helped me to make my codes a lot more readable, since people can easily see what are read-only variables. It may also provide a little boost to the JIT, and while that's a very limited one, it can't harm, especially when targeting embedded devices such as android platforms.

But more than everything, it contributes to make a design more robust to changes, and guide other committers when they need to modify the code base.

However, while browsing some of the JDK source code, I never stumbled upon this keyword, either for classes, methods, or variables. The same applies for various systems I had to review.

Is there a reason? Is it a common design paradigm to let everything mutable from the inside?


问:
Tdd on a datadriven webapp
How would one go about to use tdd/bdd on a mostly data driven webapp? For example a blog or a forum?</p>

答:
The traditional approach would be to use the Repository pattern.

The very short version is you use collections for tables in your testing environment where as the production implementations access the database tables or persists the changes to the collections to the database.

You don't mention which environment/language your using but there are plenty of examples and frameworks/tools around for helping with all the plumbing.

Title: Tdd on a datadriven webapp


问:
Computer Science and other advance topics taught in javascript
I'm an 'okay' Javascript developer working on browser javascript and node.js. However because I'm self taught, starting from copying and pasting jquery, there are a lot of holes in my programming/CS education.

I don't really have the time to devote myself to fully learning all the CS concepts that might be taught in a real college program, and learning C or Scala or whatnot, I'm just too addicted to hacking and making things that work. On some level studying CS seems to be 'premature scaling' in Hacker News parlance.

But every so often I get struck by the thought that maybe there is something that I should really really learn to take my skills and productivity to the next level.

Is there a book, a list of concepts or things that I can study and learn in my 'down time' that would see reasonable returns on my productivity and ability in 1 - 2 months?

Thanks!

And yes, the only language I know and use is Javascript, though I have tinkered with Python (High School), Ruby (RoR), PHP (Drupal), and Assembly (Making Diablo 2 Mods) in the past.

Please note that a book like O'Reilly's JavaScript Web Applications is too easy for me and not really what I'm talking about.

答:
I'm a self-taught too and I started with Basic on a C64 in the 80es. Today, I am as well paid as any M.S. and I did not attend any CS classes apart from a single C++ course for electrical-engineers (while studying civil engineering that I soon gave up for programming).

I can't recommend a quick fix for your problem because I believe there isn't any. Build on what you already have - if you really understand assembly, you are more than ready for C. Teach yourself how to do pointer arithmetic, kill some time debugging memory allocation problems and reference counting before you move on to higher level (especially garbage collected) programming languages. The skills and discipline that you collect during hacking C/C++ will serve you exceptionally well no matter what fancy new languages may come into demand or in what industry you will be working in the decades ahead.

I appreciated that you didn't ask on how to become a better JavaScript hacker, and just want to encourage you to look even further - let JavaScript be to you what the 10 GOTO 20 stuff was for us old farts - a door opener to a wider sky.


答:
Have you thought on using Javadoc (or doxygen, or any other similar tool)? If so, you can use (also) the argument that it can generate an easy to consult reference of the applications APIs (and even diagrams) in HTML, that is accessible to everyone.

Also, unit testing and patterns to name methods, variables and others helps a lot.

Title: What are the benefits of using comments

ContentLicense: CC BY-SA 4.0


问:
What pattern helps to compose nested views at runtime?
Are there any design patterns to compose views within a parent view during runtime? Say we are composing the views in a workflow tab and views in the tabcontrol depend on the country, store type and/or other conditions.

This is a MVP, WPF, PRISM application.

答:
Would a some form of Factory suffice?

I'm thinking something along the lines of

```<code>    var dynamicView = ViewFactory.CreateView(countryCode, storeType, otherConditions);
    Render(dynamicView);
</code>```

or

```<code>    var countryView = CountryViewFactory.Create(countryCode);
    var storeTypeView = StoreTypeViewFactory.Create(storeType);
    var otherView = OtherViewFactory.Create(otherConditions);
    RenderPartial("CountrySection", countryView);
    RenderPartial("StoreTypeSection", storeTypeView);
    RenderPartial("OtherSection", otherView);
</code>```

Body:
Would a some form of Factory suffice?

I'm thinking something along the lines of

    var dynamicView = ViewFactory.CreateView(countryCode, storeType, otherConditions);
    Render(dynamicView);

or

    var countryView = CountryViewFactory.Create(countryCode);
    var storeTypeView = StoreTypeViewFactory.Create(storeType);
    var otherView = OtherViewFactory.Create(otherConditions);
    RenderPartial("CountrySection", countryView);
    RenderPartial("StoreTypeSection", storeTypeView);
    RenderPartial("OtherSection", otherView);


问:
Why is the dollar sign used to abbreviate the description of a cache?
What's the historical significance of abbreviating say, an L1 cache as L1$?</p>

答: I suppose that's not obvious for non-native speakers, but as mentioned in the comments, the dollar sign is representative of money, synonymous with the word "cash", which is a homophone for "cache".</p>


答:
Use Null.

There's no point to storing a value of '', when simply making the field in the table nullable will do. It makes queries more obvious too.

Which SQL query is more obvious and readable if you wanted to find users with an email address?

SELECT * FROM Users WHERE email_address != ''

SELECT * FROM Users WHERE email_address IS NOT NULL

SELECT * FROM Users WHERE email_address != '' and email_address IS NOT NULL

I would say 2 is.  Although 3 is more robust in the cases where there's bad data stored.

For the case of the email address on the form, which is optional, it should be reflected in the table too. In SQL, it's a nullable field, which means it's not known.

I can't think of any reasonable business value in storing an empty string in a table other than simply bad design. It's like storing a string value of 'NULL' or 'BLANK', and having developers assume that it's null or a empty string. To me, that's bad design. Why store that when there's NULL??

Just use NULL, and you'll make everyone a little bit more happy.

MORE INFO:

SQL uses a three valued logic system: True, False, and Unknown.

For a better and more detail explanation, I recommend developers to read: SQL Queries – beyond TRUE and FALSE.

Title: SQL: empty string vs NULL value

Body:
I know this subject is a bit controversial and there are a lot of various articles/opinions floating around the internet. Unfortunatelly, most of them assume the person doesn't know what the difference between NULL and empty string is. So they tell stories about surprising results with joins/aggregates and generally do a bit more advanced SQL lessons. By doing this, they absolutely miss the whole point and are therefore useless for me. So hopefully this question and all answers will move subject a bit forward.

Let's suppose I have a table with personal information (name, birth, etc) where one of the columns is an email address with varchar type. We assume that for some reason some people might not want to provide an email address. When inserting such data (without email) into the table, there are two available choices: set cell to NULL or set it to empty string (''). Let's assume that I'm aware of all the technical implications of choosing one solution over another and I can create correct SQL queries for either scenario. The problem is even when both values differ on the technical level, they are exactly the same on logical level. After looking at NULL and '' I came to a single conclusion: I don't know email address of the guy. Also no matter how hard i tried, I was not able to sent an e-mail using either NULL or empty string, so apparently most SMTP servers out there agree with my logic. So i tend to use NULL where i don't know the value and consider empty string a bad thing.

After some intense discussions with colleagues i came with two questions:

am I right in assuming that using empty string for an unknown value is causing a database to "lie" about the facts? To be more precise: using SQL's idea of what is value and what is not, I might come to conclusion: we have e-mail address, just by finding out it is not null. But then later on, when trying to send e-mail I'll come to contradictory conclusion: no, we don't have e-mail address, that @!#$ Database must have been lying!

Is there any logical scenario in which an empty string '' could be such a good carrier of important information (besides value and no value), which would be troublesome/inefficient to store by any other way (like additional column). I've seen many posts claiming that sometimes it's good to use empty string along with real values and NULLs, but so far haven't seen a scenario that would be logical (in terms of SQL/DB design).

P.S. Some people will be tempted to answer, that it is just a matter of personal taste. I don't agree. To me it is a design decision with important consequences. So i'd like to see answers where opion about this is backed by some logical and/or technical reasons.


答:
I agree that the final keyword improves readability.  It makes it much easier to understand when an object is immutable.  However, in Java it is extremely verbose, particularly (in my opinion) when used on parameters.  This is not to say that people shouldn't use it because it is verbose, but rather they don't use it because it is verbose.

Some other language, such as scala, make it much easier to make final declarations (val).  In these languages, final declarations can be more common than variables.

Note that there are many different uses of the final keyword.  Your post mostly covers items 2 and 3.

final Classes (JLS 8.1.1.2)

final Fields (JLS 8.3.1.2)

final Methods (JLS 8.4.3.3)

final Variables (JLS 4.12.4)


问:
Why are interfaces useful?
I have been studying and coding in C# for some time now. But still, I can't figure the usefulness of Interfaces. They bring too little to the table. Other than providing the signatures of function, they do nothing. If I can remember the names and signature of the functions which are needed to be implemented, there is no need for them. They are there just to make sure that the said functions(in the interface) are implemented in the inheriting class.

C# is a great language, but sometimes it gives you the feeling that first Microsoft creates the problem (not allowing multiple inheritance) and then provides the solution, which is rather a tedious one.

That's my understanding which is based on limited coding experience. What's your take on interfaces? How often you make uses of them and what makes you do so?

答:
The following is pseudocode:

```<code>class MyClass{

    private MyInterface = new MyInterfaceImplementationB();

    // Code using Thingy

}

interface MyInterface{

    myMethod();

}

class MyInterfaceImplementationA{ myMethod(){ // method implementation A } }

class MyInterfaceImplementationB{ myMethod(){ // method implementation B } }

class MyInterfaceImplementationC{ myMethod(){ // method implementation C } }
</code>```

The last classes can be completely different implementations.

Unless multiple inheritance is possible, inheritance imposes the implementation of the parent class making things more rigid. Programming against interfaces on the other hand can allow your code or a framework to be extremely flexible. If you ever come accross a case where you wished you could swap around classes in an inheritance chain you'll understand why.

For example, a framework that provides a Reader originally intended to read data from disk could be re-implemented to do something of the same nature but in a totally different way. Like interpret Morse code for example.

Title: Why are interfaces useful?

Body:
The following is pseudocode:

class MyClass{

    private MyInterface = new MyInterfaceImplementationB();

    // Code using Thingy

}

interface MyInterface{

    myMethod();

}

class MyInterfaceImplementationA{ myMethod(){ // method implementation A } }

class MyInterfaceImplementationB{ myMethod(){ // method implementation B } }

class MyInterfaceImplementationC{ myMethod(){ // method implementation C } }

The last classes can be completely different implementations.

Unless multiple inheritance is possible, inheritance imposes the implementation of the parent class making things more rigid. Programming against interfaces on the other hand can allow your code or a framework to be extremely flexible. If you ever come accross a case where you wished you could swap around classes in an inheritance chain you'll understand why.

For example, a framework that provides a Reader originally intended to read data from disk could be re-implemented to do something of the same nature but in a totally different way. Like interpret Morse code for example.


问:
Examples of composition in software engineering?
In programming, various terms like abstraction are mentioned quite heavily. What, however, is composition? What is a basic but effective example of composition at play to result in good quality code (good quality meaning easy to understand, short and concise, etc).</p>

答:
Composition is simply when you have multiple objects compose one more complex object.  Example:

```<code>class Person {
    string FirstName { get; set; }
    string LastName { get; set; }
}
</code>```

Person is composed of a FirstName and LastName

OwnerDisplayName: dotnetdev

Body:
Composition is simply when you have multiple objects compose one more complex object.  Example:

class Person {
    string FirstName { get; set; }
    string LastName { get; set; }
}

Person is composed of a FirstName and LastName

OwnerDisplayName: Kyle W


答:
In the functional programming sense, a composition is:

if a function f takes a foo and returns a bar, and
   if a function g takes a bar and returns a blah,
   then there is a function h which takes a foo and returns a blah, such that:
   h(foo) = g(f(foo))

That is, if f is "take the length of a string" and g is "double the size of an integer" then there is a composed function h that takes the length of a string and doubles it.

In the object oriented programming sense a composition is: a class C may contain fields of classes D and E.  C is a class which composes a D with an E.

Title: Examples of composition in software engineering?

Body: In programming, various terms like abstraction are mentioned quite heavily. What, however, is composition? What is a basic but effective example of composition at play to result in good quality code (good quality meaning easy to understand, short and concise, etc).</p>


答:
Although the term composition can refer to many aspects of programming such as multiple objects within a class, the term when speaking about abstract programming typically means executing multiple functional lines of code within a single statement.  Think of f(g(x)) in mathematical terms.

The most common method of composition I can think about in real-world programming is defining pre-processor directives in say C++ or C.

```<code> #define getmax(a,b) a>b?a:b
</code>```

the above defines an if/then function returning max of 2 different integers that can then be used within other lines of code thus creating a composition.

If you have ever heard the term public and private keys when speaking of cryptography, this is a classic example of composition algorithms where f(g(x)) and x is typically your private key.

Body:
Although the term composition can refer to many aspects of programming such as multiple objects within a class, the term when speaking about abstract programming typically means executing multiple functional lines of code within a single statement.  Think of f(g(x)) in mathematical terms.

The most common method of composition I can think about in real-world programming is defining pre-processor directives in say C++ or C.

 #define getmax(a,b) a>b?a:b

the above defines an if/then function returning max of 2 different integers that can then be used within other lines of code thus creating a composition.

If you have ever heard the term public and private keys when speaking of cryptography, this is a classic example of composition algorithms where f(g(x)) and x is typically your private key.


答: It depends what you mean by composition, which is used for various things.  I first think of the composite pattern, which is widely used.  Handling data in a tree structure is a simple example of a composite pattern, and allows easy recursion through the nodes.</p>