问:
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?

答: One thing I haven't seen mentioned is not only the why you did something but a refernce to the bug tracking or project management system task number that made you make the change. Not for everything, but we have all been asked to make a change that there was a long involved decision making process (documented in the project management system) leading to what seems to to outsider to be an odd choice in the code but which the deverloper had complex reasons for doing that way or a change request we felt would come back to bite us later.  Knowing right up front the task number to look up in the PM or bug tracking system can help immensely when later to see if the requirement has really changed or if the new requirement isn't taking the old requierment into account. I've gotten several bad future changes turned off because I was able to quickly find the reasoning behind why the application operated the way it did.</p>

Title: What are the benefits of using comments


问:
Use-cases for node.js and c#
I do quite a bit of ASP.NET work (C#, MVC), but most of it is typical web development. I do Restful architecture using CRUD repositories. Most of my clients don't have a lot of advanced requirements within their applications.

I'm now looking at node.js and it's performance implications (I'm addicted to speed), but I haven't delved into it all that much.

I'm wondering if

node.js can realistically replace my typical web development in C# and ASP.NET MVC (not rewriting existing apps, but when working on new ones)

node.js can complement an ASP.NET MVC app by adding some async goodness to the existing architecture.

Are there use-cases for/against C# and node.js?

Edit

I love ASP.NET MVC and am super excited with where it's going. Just trying to see if there are special use cases that would favor node.js

答:
I'm now looking at node.js and it's performance implications (I'm addicted to speed), but I haven't delved into it all that much.

Profile, profile, profile. That's the only way to know that your speedups are having the proper affect. You can guess that it's fast enough. But most people like to prematurely optimize. That's worse than playing with yourself during a date.

I'm wondering if node.js can completely replace my typical web development in C# and ASP.NET MVC, if it's better as a complement to C# and ASP.NET MVC, or if there's some things that should just "leave well enough alone".

Are there use-cases for/against C# and node.js?

Sure, if you're in a shop that routinely writes code in C#, then you should use MVC (it's a lot better than WebForms, and is called WebPages). You're going to not lose a lot of time to tooling training, and it's something your workflows should already handle.

What you don't seem to indicate above is the reasons to choose each. You've given two current market options, one still in Alpha stages, the other on its full third year of platform release. I wouldn't want to compare the current testing model electric cars with the Honda hybrids that are already out on the market. They're in two different leagues.

Now, here's a reason for you to stay away from node.js, if you're nominally a C# shop.

You don't currently work in asynchronous evented i/o, you currently work in a procedural format.

That's the antithesis to what nodejs is going to do for you.

However, if you're frequently writing async code in C#, and you use it a lot in an evented style, then yes, node.js is for you to strongly consider.

Here's what you'll give up:

IIS - This is actually important to a lot of people. Things like native A/D integration are already done, and pretty bug-free. Actually node.js now integrates well with IIS.

Razor templating - If you've done any serious C# MVC, then you are using and loving Razor and how quickly you can churn things out. There are similar templates in node, and I'm certainly not knocking node, but the entire toolchain is already present in C#, and a lot of it is currently being built in node world. NB: a lot of this tooling is now rather mature_

compile-time building of dlls - node.js generally gets compiled on the fly, that is to say, not all paths are checked at startup. It's entirely possible to have really bad code in node that nobody ever touches, checks, or tests against.

All the tools currently built into VS that you use daily - There just isn't that much VS support for javascript. Partly because everything in javascript is so dynamic. NB: Microsoft is obviously working on tooling support for javascript_

Here's what you'll gain:

everything you develop will be in the same language, assuming you do client side scripting as well as serverside. (or why would you even consider javascript on the server)

So, since I seem to be bashing Node here entirely, let me point out that node is my play language at home, I love it, and I help people debug it sometimes on the stackoverflow chat servers (room 642). I see that it has great and stupendous potential in the future.

I'm just saying, don't throw out the baby and wonder why the bathwater is dirty.

You haven't given a reason why you should give up your years of experience and start on something new. Are either bad tools? Not at all. Both are great and make development a breeze.

Can node replace C#? Yes, quite certainly. So could PHP or Java or Ruby. You're not asking about those.

Here's how you know when you're ready to program node.js instead of C#:

You're considering writing a book to help other people "get javascript" instead of the boring old programs they've written before in C# and etc.

You've got problems with synchronous (blocking) I/O stopping your apps from doing actual work.

You aren't using ANY libraries in C# other than the default MVC and that just for routing, and you're pretty sure that you can do a better routing engine, and you're coding everything as close to the metal as you can.

Every data object you design you see as a hash instead of a strongly typed object.

ContentLicense: CC BY-SA 3.0

Title: Use-cases for node.js and c#


问:
Is there such a thing as a "when" statement?
Is there a language or language feature that can handle "when" cases? That is, whenever some condition becomes true, in any scope or context, that extra code could be specified to execute?

Note that this is different from a simple if, which must be in a particular scope and explicitly written. This when clause would almost be like an if that applied to every case in the execution of the program after it.

答: Well, you could write a bunch of parallel threads, each of which polls for its respective condition. I suppose that would be a rather low-performing application, but it's possible.</p>


问:
Alternatives to Professional Version Control
We're teaming up with some non programmers (writers) who need to contribute to one of our projects.

Now they just don't like the idea of using Git (or anything for that matter) for version controlling their work. I think this is because they just don't find it worthwhile to wrap their heads around the twisted concepts of version control. (when I first introduced them to branching and merging -- they looked like I was offending them.)

Now, we're not in a position to educate them or convince them to use it. We're just trying to find alternatives so that we get all their work versioned (which is what we need) -- and they get easy workflow and concentrate on what they do.

I have come up with some ideas...

tell them to save their work as a separate file every time they make some non-trivial change, and then use a diff on our side to just track changes.

write a program (in Python) that implements the "milestones" in CSSEdit in some way.

About the project:

It is a natural language processing system (written in C + Python). We've hired some writers to prepare inputs for the system in different languages. And as we evolve the software, we'd need those writers to make changes to their inputs (articles). Sometimes the changes are very small (a word or two), and other times big.

The reason we need to version control those changes is because every small/big change in the input has the potential to change the system's output dramatically.

答:
Google Docs

Google Docs might do what you want. File > See Revision History will let you keep track of changes.

You've also got the problem of handing files back and forth taken care of for free; just share the document amongst everyone.

Finally, it's easy to use; the writers don't even have to know that there is versioning happening.


答:
comments are not for how an application works, they are for why this function achieves its goals using X.  If the code is poorly written and doesn't have function names that describe what they do, then adding a line for each function to do so would be a worthwhile use of comments as a band-aid.  It sounds to me like you don't understand how to read the code if you can't understand how it works. If you meant what the code does, that should be explained in external documents like use cases or process flows and design diagrams. It also seems you are approaching learning the code from the wrong angle. Unless your code is in a single function that is 50000 lines long, length is irrelevant, it just gets you stuck on how big it is. You learn a large complex system in parts, pick a layer/class and learn what it does in relation to the project and how it works, then pick another and repeat. Its also helpful to work towards understanding the high level flow of what your app does, before trying to learn the low level implementation details.

Trying to enforce the use of comments for added code may end up being a worthwhile cause, but trying to go back and add comments to existing code is a pointless endeavor, it just doesn't work because the knowledge of what should be in those comments is gone because no one is in the mindset of the developer at that point in time.

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?


答:
OS Agnostic

Write a Python program that you can drag and drop a file onto, that program can then do the git add and git commit and what not and they never have to deal with it.

or

Use a WebDav based filesystem you can mount on their machine and have the server do the git stuff transparently.

OSX/Linux

Write a Python based FUSE plugin that takes the files and commits them to git. Then they can just open and save from the mounted filesystem transparently. There are some FUSE for Windows resources, but they are probably not even worth fooling with.

Windows

You might could write some code to use FileSystem Filter Drivers to transparently do the git stuff.

Title: Alternatives to Professional Version Control

Body:
We're teaming up with some non programmers (writers) who need to contribute to one of our projects.

Now they just don't like the idea of using Git (or anything for that matter) for version controlling their work. I think this is because they just don't find it worthwhile to wrap their heads around the twisted concepts of version control. (when I first introduced them to branching and merging -- they looked like I was offending them.)

Now, we're not in a position to educate them or convince them to use it. We're just trying to find alternatives so that we get all their work versioned (which is what we need) -- and they get easy workflow and concentrate on what they do.

I have come up with some ideas...

tell them to save their work as a separate file every time they make some non-trivial change, and then use a diff on our side to just track changes.

write a program (in Python) that implements the "milestones" in CSSEdit in some way.

About the project:

It is a natural language processing system (written in C + Python). We've hired some writers to prepare inputs for the system in different languages. And as we evolve the software, we'd need those writers to make changes to their inputs (articles). Sometimes the changes are very small (a word or two), and other times big.

The reason we need to version control those changes is because every small/big change in the input has the potential to change the system's output dramatically.


问:
How can you explain "beautiful code" to a non-programmer?
When speaking with a non-programmer friend, I happened to mention the concept of "beautiful code" and she wanted to understand what that meant, but I was at a bit of a loss as to how to explain it to someone who would have no context whatsoever.

When all code looks like gibberish to someone anyways, how can you explain what makes one piece of code prettier than another? Analogies could be useful too.

答:
Some aspects of good code is:

It has large number of small details that all point to same direction

it is consistent in structure, every part following the same pattern

but it does not repeat itself, instead every part is different

it also does not allow behaviour that is considered invalid

it has smallest possible number of different states

you can understand the whole behaviour of the code by reading function prototypes

it has no side effects

the execution of it is guaranteed to stop

it does not use any advanced features available in programming languages

it is not too complex compared to the complexity of the problem it solves

there is no errors or undefined behaviour in it

it can be compiled with compilers from several different vendors

it has no dependencies to code that is not used

ContentLicense: CC BY-SA 2.5


问:
Is using the new System.Tuple class bad design?
I like the concept of System.Tuple in that it allows me to return multiple parameters in a single function call without instantiating a new class, however does this defy any good programming practices such as Microsoft Patterns & Practices, SOLID Principles, etc.

I'm just trying to gauge how liberally I should use this feature or if I should only use it in edge case scenarios when necessary.

答:
The issue with using Tuple is that the generic type parameters do not convey meaning.

For readability you may want to consider using a custom class or even an anonymous type with named members.


问:
What's the best way to handle multiple simultaneous "streams" of development in version control?
My department is planning on working on our next several releases (spanning a year) simultaneously.  The powers that be are advocating we support this by refactoring all affected code into classes like AbstractGizmo, R1Gizmo, R2Gizmo, etc and use configuration (via Spring and/or ANT) to control which classes are used in a particular release.  Ostensibly this is to save us the work of merging changes into multiple branches, especially when the changes are in the common code.  However, I see this as a clear cases for branching and merging in version control (TFS, in our case).

However, I have very little experience on projects that have active streams of development like this.  I'm sure others have (like Microsoft, with Windows XP, Vista, and 7).  What's the best way to handle multiple simultaneous "streams" of development in version control?  Do you branch and merge changes in version control, try to develop everything in one branch and use configuration or build scripts to assemble the different version, or something else?

P.S. We use TFS right now, but our version control strategy may not be constrained by it.  A coworker of mine is pushing to switch to Git or Mercurial, and it seems like he's getting a bit of traction.

答:
As you suspect, this is a clear use-case for a VCS.  But... not all VCSs handle merging very well.  I can't speak to TFS, but Subversion's merge tracking leaves a lot to be desired.  The DVCSs such as Hg and Git handle merging much better.  Merges aren't always simple, and I've found that a lot of developers have trouble with even relatively simple merges.  If you have one or two people who are willing to get good at dealing with merges, that will help.

I would recommend that you test the merging of TFS with some trivial little example app, where you rename files and modify the same file in a different branch, merge multiple times from one branch to another, etc.

The multiple-versions-in-one-tree approach you describe seems like it would yield a real nightmare when you get close to your first release and realize that you're going to have to do some refactoring or significant interface change for your second release.  You're not going to want to make such drastic changes to the codebase close to a release, but you're not going to want to delay the change for the work you need for the second release.  If you aren't branching, it's going to be hard to make that live in the same tree of files.


问:
What should be included on an About page/form?
I was looking to add a simple form that states my project's build number on a form to quick identify what version I am running. Then I realized I'm not sure what fits on an about page.

In my highschool projects I would make silly splash screens with this info, with images and other unnecessary information.

What are standard/appropriate elements to include on an "About" page in an application?

答:
The only time I ever use About windows is to view the Version Number of the application, and possibly the application name to know what version of the application I'm running (eg. VS 2010 Express, Premium, Ultimate, etc)

So really I'd leave it at nothing more than a Logo/Name, and a Version Number. If you have a modular system, I'd have version numbers for each module loaded as well.


问:
Java Web Frameworks (JSF vs Wicket) Third-party component suites in Wicket?
A presentation linked in an answer here demonstrated a comparison of several web development frameworks.  It was a good comparison but caused me a little worry based on the technology stack that I have been pushing for awhile now at my current company.

While it seemed like the author was biased towards RoR, he pointed out some major pain points about JSF, which I am using right now and personally have no significant problems with.  It seems hip to hate JSF, and I would like to look into something different like Wicket.  The problem is that rich third-party component libraries like Primefaces have me hooked by the extreme convenience of throwing prebuilt web components onto a page with simple XHTML compliant markup.

Frameworks like Wicket are great because they merge the page with the View, and with Spring this is a powerful combination, but I can't help but wonder how long would it take me to implement the fully featured Primefaces Data Table component in a framework like Wicket?

Clearly JSF is a component based framework like Tapestry, but does Wicket have an answer to rapid component-based web development like JSF+Primefaces?

Further, I am aware of the major drawbacks of JSF, one of which being the level of effort and frustration it takes to develop a component, but with component suites in JSF becoming more stable and fully featured, is this a major issue for relatively simple web applications with loose open ended UI specifications?  If it doesn't have to look exactly like the spec visually, why would custom components need to be developed?

I know there is a lot of JSF hate out there... just mentioning it a developer conference causes people to break out into seizures from so much fail.  The web is littered with JSF Sucks blogs, but I have done some pretty cool things with it.  Any thoughts on this?

答:
JSF whether it is hated or not, it is a standard and that is what matters to projects managers.

I'm not aware of any components suite like RichFaces or PrimeFaces for Wicket, but long time Wicket users say it is easy to create your own components.

If you are happy and productive with JSF, then stick with it. No need to shop outside.


答:
One of the most important code qualities is readability. So ask yourself:

When I (i.e. in anybody else but you) look at the method signature, do I know what meaning the respective components of the Tuple have?

For example if the pair of floats you are returning is a set of polar coordinates, is this clear?

This is clear:

```<code>Tuple<Float, Float> getPolarCoords();
</code>```

This is misleading (because one would assume Cartesian coordinates):

```<code>Tuple<Float, Float> getCoords();
</code>```

And this is devoid meaning:

```<code>Tuple<Float, Float> getTuple();
</code>```

So generally speaking, you will have evaluate clarity on a per-case basis and refactor if necessary. If you represent the same kind of data as Tuple in many different places, then creating a class is definitely a good idea.

Title: Is using the new System.Tuple class bad design?

Body:
I like the concept of System.Tuple in that it allows me to return multiple parameters in a single function call without instantiating a new class, however does this defy any good programming practices such as Microsoft Patterns & Practices, SOLID Principles, etc.

I'm just trying to gauge how liberally I should use this feature or if I should only use it in edge case scenarios when necessary.

Body:
One of the most important code qualities is readability. So ask yourself:

When I (i.e. in anybody else but you) look at the method signature, do I know what meaning the respective components of the Tuple have?

For example if the pair of floats you are returning is a set of polar coordinates, is this clear?

This is clear:

Tuple<Float, Float> getPolarCoords();

This is misleading (because one would assume Cartesian coordinates):

Tuple<Float, Float> getCoords();

And this is devoid meaning:

Tuple<Float, Float> getTuple();

So generally speaking, you will have evaluate clarity on a per-case basis and refactor if necessary. If you represent the same kind of data as Tuple in many different places, then creating a class is definitely a good idea.


问:
In what types of programming environments is Reactive Management better than Proactive Management?
Most everyone seems to agree that Reactive Management is worse than Proactive Management; however, it seems that I am constantly seeing Reactive Management from development managers.

Logic would suggest that there is some benefit to Reactive Management, since it is seen so often. I tend to see nothing but negative issues coming from this type of management, but I may be naive. In what sorts of programming environments/situations would Reactive Management be advantageous?

答:
Never. Now that I have your attention, when it is a deliberate choice. But that makes it "Active management choosing to be Reactive". Why would anyone do that?

For the answer, look into the concept of initiative in combat. Many of the same concepts apply to good, active management. That is, instead of sitting and waiting for something to surprise you, you make a decision to wait and watch something before acting, instead of acting precipitously. This looks like reactive management, the same way a boxer taking blows in the corner looks like he is losing. It comes down to what is going on inside the person's head.

Panic? The boxer is letting things be done to him, and is on the way to a loss. Or a strategy? He's wearing out his opponent, and avoiding taking crippling damage while he waits for an opening.

I highly recommend the art of war for executives, as it is an easier read than the original, and it is applied to business. Sun Tzu has very good points on what is initiative, why it is vital, and many other things.

To quote him through the filter of translation:

Therefore the clever combatant imposes his will on the enemy, but does
  not allow the enemy's will to be imposed on him.

Previously, he states:

What the ancients called a clever fighter is one who not only wins,
  but excels in winning with ease.


答: Mostly the JSF hate blogs belong to 2009 and before, JSF 2.0 fixed many of the issues. I don't think it is popular just because of it's standard, remember that EJB 2.x was the standard then Spring came up. There are many web frameworks but JSF is still very popular. Also recent JSF Specs starting with 2.0 is designed according to user feedback acquired since JSF 1.x.</p>

Title: Java Web Frameworks (JSF vs Wicket) Third-party component suites in Wicket?

Body:
A presentation linked in an answer here demonstrated a comparison of several web development frameworks.  It was a good comparison but caused me a little worry based on the technology stack that I have been pushing for awhile now at my current company.

While it seemed like the author was biased towards RoR, he pointed out some major pain points about JSF, which I am using right now and personally have no significant problems with.  It seems hip to hate JSF, and I would like to look into something different like Wicket.  The problem is that rich third-party component libraries like Primefaces have me hooked by the extreme convenience of throwing prebuilt web components onto a page with simple XHTML compliant markup.

Frameworks like Wicket are great because they merge the page with the View, and with Spring this is a powerful combination, but I can't help but wonder how long would it take me to implement the fully featured Primefaces Data Table component in a framework like Wicket?

Clearly JSF is a component based framework like Tapestry, but does Wicket have an answer to rapid component-based web development like JSF+Primefaces?

Further, I am aware of the major drawbacks of JSF, one of which being the level of effort and frustration it takes to develop a component, but with component suites in JSF becoming more stable and fully featured, is this a major issue for relatively simple web applications with loose open ended UI specifications?  If it doesn't have to look exactly like the spec visually, why would custom components need to be developed?

I know there is a lot of JSF hate out there... just mentioning it a developer conference causes people to break out into seizures from so much fail.  The web is littered with JSF Sucks blogs, but I have done some pretty cool things with it.  Any thoughts on this?


答:
I agree with retracle, and to add some TFS experience. Merging can be painful so you need to do it as often as possible to reduce the number of simultanious conflicts. Don't save it up till one of your streams is nearly complete or you'll have a nightmare on your hands.

Read the ALM rangers guidance and you should be set. Hopefully you're using TFS 2010 as the merging is significantly better than earlier versions.

You might also find this blog interesting. Brian Harry compares the merging experience between git, TFS 2010 and TFS 11

Body:
My department is planning on working on our next several releases (spanning a year) simultaneously.  The powers that be are advocating we support this by refactoring all affected code into classes like AbstractGizmo, R1Gizmo, R2Gizmo, etc and use configuration (via Spring and/or ANT) to control which classes are used in a particular release.  Ostensibly this is to save us the work of merging changes into multiple branches, especially when the changes are in the common code.  However, I see this as a clear cases for branching and merging in version control (TFS, in our case).

However, I have very little experience on projects that have active streams of development like this.  I'm sure others have (like Microsoft, with Windows XP, Vista, and 7).  What's the best way to handle multiple simultaneous "streams" of development in version control?  Do you branch and merge changes in version control, try to develop everything in one branch and use configuration or build scripts to assemble the different version, or something else?

P.S. We use TFS right now, but our version control strategy may not be constrained by it.  A coworker of mine is pushing to switch to Git or Mercurial, and it seems like he's getting a bit of traction.

ContentLicense: CC BY-SA 4.0


问:
Is CRTP used much? and why it is/isn't?
I'm thinking about curiously recurring template pattern.

I find it quite useful, and it's pretty well adjustable for many tasks. But I have to admit, I don't see much of CRTP code in the wild.

Is it hard to grasp? Are virtual functions easier overall? Shouldn't it be used for 90% of cases where virtual keyword appears?

答:
Here's reasons why it's not used more widely:

It's a hack

As a hack, it's not guaranteed you don't run into trouble when you use it. The normal OO stuff has been used by large number of projects, and found to work properly/problems are well known, the CRTP is found in only small number of projects, and no data is available

there is no good reason to use it - most reasons sited are just not valid

it can make some things more complicated

Title: Is CRTP used much? and why it is/isn't?


答:
Logic would suggest that there is some benefit to Reactive Management

There is, It's Cheaper*

Consider the Following: You find corrupted data in the system

How you find the edge case that is causing and error? You need to first think of the edge case and\or go through all the code looking for possible edge cases that you may have missed. Imagine the man hours to
do this with a massive Code base. Often that is what takes to be proactive.

What does it take to be reactive?  Put in a logging mechanism, and wait for it to happen again.

Many argue that dealing with the bugs proactively is Cheaper in the long run. But in most cases its simply the case. Some bugs are just too difficult and time consuming to peg down and kill if you don't "Catch them in the act". So the decision is made to wait and see....

Title: In what types of programming environments is Reactive Management better than Proactive Management?

Body:
Most everyone seems to agree that Reactive Management is worse than Proactive Management; however, it seems that I am constantly seeing Reactive Management from development managers.

Logic would suggest that there is some benefit to Reactive Management, since it is seen so often. I tend to see nothing but negative issues coming from this type of management, but I may be naive. In what sorts of programming environments/situations would Reactive Management be advantageous?


问:
Moving legacy application to a testable framework?
We have a web application which contains a web service with over 50 methods.

The application is currently installed at a number of sites and is currently being maintained by one developer.

The application is currently a single user system where all the data is stored in XML files.

One of our main tasks is to make it a multi user system whilst at the same time put in a database (RDBMS or NoSQL, not decided yet).

In addition to other new features we want to get a team of developers (around 5) working on other new features.

From what I have seen, the application is not testable. There are no test units and all the code is pretty much in the web service methods.

I need to put a framework in place so that the other developers can simply start working on their features using TDD and then finally when we have the database in place we can switch that in at a later date.

I was thinking of first moving all the code into libraries and then introducing UNITY and test/mocking frameworks to provide some of the services that the other developers will need. That way via inversion of control they at least have interfaces they can work with.

I am not sure if this is the right way to go or whether I should focus on some other area.

I was thinking about putting unit tests around the original code but then all the code will change later so this may be pointless in the long run.

We have a period of about 6 weeks before we get the other developers involved.

Any help would be appreciated.

答:
I would consider setting up some acceptance level test up front, rather than unit tests. It's probably not practical cover all bases with acceptance tests up front, but you can probably cover the main use cases and some smoke testing for the secondary use cases within the six weeks. Theses acceptance tests should be setup to run in CI.
You also want to do a few integration and unit tests to get an infrastructure for that up and running. These should also be included in CI.
Lastly give the new devs arrive give the Michael Feathers: Working Effectively with Legacy Code and ask them to read as a homework assignment. Seriously. It's brilliant book on tackling this sort of thing in a sound and incremental fashion. The very basic gist of the books approach is what tuergeist outlines in his answer.</p>


答:
The simple fact is that many, if not most, C++ users can hardly grasp that vector is better than malloc and free, so the number who can not only appreciate but implement advanced template metaprogramming is not very high. This implies that even if it were good for 90% of situations, you'd see it in far less, simply because people don't know about it or how to use it.

However, virtual functions do have advantages, namely, virtual functions are much easier to use than the CRTP. C++ templates are notorious for being bitchy about virtually anything and everything, and the inclusion model sucks balls.

However, they [virtual functions] are distinctly slower and less powerful. For example, I right now am writing code using the CRTP, where you inherit operator overloads for use with expression templates. There's no way virtual functions could possibly make that work.

Title: Is CRTP used much? and why it is/isn't?

Body:
I'm thinking about curiously recurring template pattern.

I find it quite useful, and it's pretty well adjustable for many tasks. But I have to admit, I don't see much of CRTP code in the wild.

Is it hard to grasp? Are virtual functions easier overall? Shouldn't it be used for 90% of cases where virtual keyword appears?


问:
What are good techniques for keeping your place in code?
I understand using bookmarks to remember a single point in your code. However, how does one keep track of the flow of the code they are investigating? Eg: multiple bookmarks and the order in which they were made.

Example:

Bug report: "Collisions aren't working on the corners of walls"

Reproduction of the bug puts it down to certain polygons not colliding.

The collision code was written by an unavailable dev. So investigation goes something like:

During the investigation, especially when reviewing non-code items such as Google, one may reasonably be expected to loose their place in the code (Have I already looked at this code path? or Which code path was I investigating? There are multiple that lead to this function, etc).  The same goes for unavoidable interruptions (Boss: I need [Lengthy Pointless Report] NOW, etc)

It would be useful to have a resource of techniques or tools for providing a way to keep track of one's place in the code.

Edit: The above example is meant as a potential illustration, not as an actual problem that needs answering.

Another way to phrase this question is:

When learning a new system, how do you keep track of where you are up to in learning the code? It's not about understanding why the code does what it does (which is what comments should be for), but how it does it (which is only learned through reading the code, not comments).

答:
I use org mode for emacs, which is an uber-outlining tool. With it, I can write an outline which mimics the call stack of the code and include direct links to the source code itself (via org-store-link). You can include explanatory text, links to web pages, etc. (e.g. when you google for magic numbers)

It's not perfect. For example the outline structure doesn't have any notion of going back up a level, so it's difficult to trace an execution path, as opposed to just a stack. But it's the next best thing to diagrams on paper that I've found.

OwnerDisplayName: Jess Telford


问:
How can I integrate and store sessions in my database, as opposed to storing them in a cookie and file system?
I've never worked with sessions in a database before, and I'm a little unclear on how they work. I have a user class already designed which stores user information: username, password, email etc. I also have a session class which uses the user ID to store a session cookie in the user's browser so that when they return to the application, a method is invoked to check if:

```<code>isset($_SESSION['id']){ $this->userId=$_SESSION['id']}
</code>```

then take the user to the admin page. I've been reading that using the database is a more secure method of handling sessions, but I'm having a hard time wrapping my head around this concept. So say I wanted to store the session info in the database, and have access to that info so that if the user clicked on a link to their profile page, for example, I could use the session info to get their user info. How could I achieve this? Does it even make sense to use this approach?

答:
Sessions are based on the session identifier, a string that uniquely identifies a browser session via a cookie1 set on the client when session_start() is called. Since they are based on cookies, you should treat them as user input and you should never absolutely trust user input. Cookies can be stolen via XSS, and PHP cookies are not encrypted by default.

Sessions are stored in the %TEMP% directory, whichever that may be for your system. The save location can be changed from the session.save_path directive or by the session_save_path during runtime, but on a typical hosting environment2, it's generally considered easier to gain access to the filesystem than a database.

The various security concerns are addressed on the manual:

The session module cannot guarantee that the information you store in a session is only viewed by the user who created the session.

...

Assess the importance of the data carried by your sessions and deploy additional protections -- this usually comes at a price, reduced convenience for the user.

...

The session module cannot guarantee that the information you store in a session is only viewed by the user who created the session.

Session fixation is the commonly quoted buzzword, you can find a little more info on the Session Fixation Vulnerability in Web-based Applications article that's referenced on the manual.

The session_set_save_handler() function allows you to  transparently choose where sessions are saved:

session_set_save_handler() sets the user-level session storage functions which are used for storing and retrieving data associated with a session. This is most useful when a storage method other than those supplied by PHP sessions is preferred. i.e. Storing the session data in a local database.

After you build and set your handler, you can continue using sessions as usual. There are quite a few examples on the comments to the manual page on storing sessions to a database. Storing sessions in a database has an important disadvantage: if for any reason the database goes awol, then you've lost everything you've built around sessions too.

1 You can propagate the session id via a URL parameter, but that's more trouble than it's worth.

2 By typical I mean cheap shared hosting.


问:
Scrum - What and How meetings
My team and I are struggling with the what and how meetings.  It's hard for us to choose what to work on when we don't know how it is going to be done.  Our estimations may be way off when  pointing an estimated level of effort.

At this point it's being discussed if we should do the how before the what so that pbi's will be at least reasonably well estimated.

What are some other options that don't require changing the order of the accepted scrum practices?

答: IMHO, what is not "what to work on", rather it is "what need to be done". You need to identify the "what's" before you can determine the "how's".  Once that is complete you need to set a mark in the sand for your next release, and use the scrum plan to determine feature compatiblities that will fit within that timeframe, moving on from there the tool(s) should help you identify and better manage slippage.</p>

Title: Scrum - What and How meetings

OwnerDisplayName: BermudaLamb


答:
Do you simply not know what you're trying to accomplish?  How can you decide how to do something without knowing what it is that you're trying to achieve?

In my world, we define our tasks by what the end result of the work is, i.e. what is user visible.  We do not normally define tasks with implementation details (although sometimes fixes or refactors will mention them).  We don't really discuss how we're going to do it, we just say what we did yesterday (that was user visible), what we're working on today (that will be user visible), and identify anything that's holding us up (that is visible to the individual being blocked).  Sometimes we'll elaborate with a few implementation details as they can be interesting to team members (e.g. yesterday I was struggling with bugs in our memory manager), but strictly speaking that's not what I got done, that's an excuse for why I didn't get more done.

Estimations may be way off, especially when just getting started.  The more estimates you do, and the more you look at estimated time vs. actual time (e.g. by tracking velocity), the better your estimates will get.  On our team we have pretty consistently hit a velocity of 50%, so for our two week sprints we schedule 40 hours of work for each person.  We have not, as a group, endeavored to make our estimates any better since the consistency is working for us and we're ok with our velocity being consistently low.

The key to scrum, in my opinion, is feeding knowledge back into subsequent sprints.  You learn a lot during a sprint, so be sure to use that knowledge to make the next sprint better.  If something's not working out for you or your team, spend some time in the retrospective meeting to come up with changes that you can make to fix the problems.  We're pretty far off from "by the book" scrum but I would say we're still embracing the spirit; it works for us, we adapt to changes pretty easily, and we get the stuff we signed up for done by the end of the sprint.  Our variations come down to acceptance that fires will come up mid-sprint and we have a mechanism to deal with that that does not require the whole restart process.

Title: Scrum - What and How meetings

Body:
My team and I are struggling with the what and how meetings.  It's hard for us to choose what to work on when we don't know how it is going to be done.  Our estimations may be way off when  pointing an estimated level of effort.

At this point it's being discussed if we should do the how before the what so that pbi's will be at least reasonably well estimated.

What are some other options that don't require changing the order of the accepted scrum practices?

OwnerDisplayName: dash-tom-bang


问:
Is it better to target iOS 5 and ARC or an earlier version with MRC?
I personally don't know much about iOS 5, but it seems like with automatic reference counting (ARC), you get rid of much of the memory management issues of the previous operating systems.

So is it better to target iOS5 (and create apps that can only run on the newest iOS devices), or is it better for her to target iOS 4 or even iOS 3, so she understands the fundamentals of memory management in Objective-C? Are there any important aspects of iOS development that she might miss out on by jumping into iOS 5?

答:
Worrying about memory management

ARC is a godsend: it doesn't solve every problem, but it's much better than having to do it all yourself or the short detour into garbage collection with Mac OS X.

There are two things to keep in mind with it:

it's a compiler feature: Xcode provides ARC support for building to iOS 4 targets1.

It's optional, even targeting iOS 5. If you want to learn manual reference counting (MRC) just to make extra sure you know it, you can do it even targeting iOS 5.

But ARC doesn't take away the ability to understand how memory management works, it just removes the tedium of having to declare release and retain everywhere. Justin on Stack Overflow gave a good summary of the difference between ARC and manual reference counting (MRC):

If you don't want to learn MRC, then you may want to first try ARC. A lot of people struggle with, or try to ignore common practices of MRC (example: I've introduced a number of objc devs to the static analyzer). If you want to avoid those issues, ARC will allow you to postpone your understanding; you cannot write nontrivial objc programs without understanding reference counting and object lifetimes and relationships, whether MRC, ARC, or GC. ARC and GC simply remove the implementation from your sources and do the right thing in most cases. With ARC and GC, you will still need to give some guidance.

Beyond whether or not you should use ARC, you ought to consider support for the OS version: does it really make sense to focus on version-specific features (like zeroing weak references) when there aren't a whole lot of people using that version?

Or worse yet, if everyone's using iOS 3, how long do you have to wait until you can even start to use ARC?

This comes down to two things: device support and market share.

Device support

Thankfully, one of the benefits to developers with respect to iOS development is that the latest version of the software runs on older devices; generally going back at least 2 years.

So if you want to target iOS 5, you'll be able to target the following devices:

iPhone 4S (released October 2011)

iPad 2 (released March 2011)

iPod touch (4th generation, released September 2009)

iPhone 4 (released June 2010)

iPad (released April 2010)

iPod touch (3rd generation, released September 2009)

iPhone 3G S (released June 2009)

Which is a large set of options. If you target iOS 4.2, you can hit every device since iPhone 3G was released back in June 2008.

Market share

Which comes to the other question: should one spend time learning anything other than iOS 5 SDK: it depends on what you want to do.

If you want to just focus on the latest and greatest, use all the neat features available in the latest SDK, and damn market share (for now): by all means go for it.

If you want to maximize market share now, I'd hold off for a few more months.

Marco Arment, the creator of Instapaper (a really popular iOS app), publishes his usage stats from time to time and just released the latest report a few days ago. In it, he notes that iOS 5 has a 45.1/48% iPad/iPhone market share, while iOS 4.2 (needed for CDMA iPhone 4s that haven't upgraded to iOS 5 yet) has a 97/97.2% market share.

Generally, hitting 97% of the potential market is "close enough": I've seen it as a rule of thumb not just for iOS development, but for web development as well.

But one thing to consider is how long of a development cycle you're going to have. If you're not planning on launching for a few months, iOS 5 is not a bad choice, even if you're trying to hit a large portion of the potential market share.

iOS users tend to upgrade much quicker than on other platforms, for a variety of reasons, and there's no reason to believe the upgrade from iOS 4.x to iOS 5 will trend any differently. If you take iOS 4.2's market share as a baseline, it was only released a year ago. It's not unreasonable to assume that October of next year iOS 5 will be well into the 90% range.

Conclusion

Don't worry about memory management too much: ARC is a great convenience, but it's not a huge paradigm shift from earlier versions. Instead, worry about the other features and support issues. If you're launching today and need to hit the largest market share possible, target iOS 4 and consider using MRC. Otherwise, target iOS 5 and consider using ARC.

1caveat: you lose out on some features if you need to target < iOS 5, like zeroing weak references. If you want to go whole-hog into ARC, you're probably better off targeting iOS 5.


答: I'm surprised no one has mentioned the many tools that can create call-graph plots. I've found doxygen to be a great help. You don't even have to commit to using doxygen throughout your program, you can just tag the functions you are interested in tracing. </p>

Title: What are good techniques for keeping your place in code?

Body:
I understand using bookmarks to remember a single point in your code. However, how does one keep track of the flow of the code they are investigating? Eg: multiple bookmarks and the order in which they were made.

Example:

Bug report: "Collisions aren't working on the corners of walls"

Reproduction of the bug puts it down to certain polygons not colliding.

The collision code was written by an unavailable dev. So investigation goes something like:

During the investigation, especially when reviewing non-code items such as Google, one may reasonably be expected to loose their place in the code (Have I already looked at this code path? or Which code path was I investigating? There are multiple that lead to this function, etc).  The same goes for unavoidable interruptions (Boss: I need [Lengthy Pointless Report] NOW, etc)

It would be useful to have a resource of techniques or tools for providing a way to keep track of one's place in the code.

Edit: The above example is meant as a potential illustration, not as an actual problem that needs answering.

Another way to phrase this question is:

When learning a new system, how do you keep track of where you are up to in learning the code? It's not about understanding why the code does what it does (which is what comments should be for), but how it does it (which is only learned through reading the code, not comments).


问:
What are my options for selling software independently on Windows?
I am looking to port a tool from the Mac app store over to Windows, the platform where I spend most of my time these days. I've spoken with the author of the original app and we've begun talking about licensing options should I decide to sell the application, and it seems like it would be feasible.

I've never sold software independently, let alone on Windows. That I know of, there is not (yet) an equivalent app store for Windows (maybe one coming with Windows 8).

Assuming my product was done today and I was ready to go to market, what options do I have for selling software for Windows as an independent developer or Micro-ISV? I know can sell it through my own website and accept PayPal, but are there options that will offer more visibility, similar to that of the Apple app stores? Any options to avoid?

答:
Most Windows software is sold independently.  Though if you are new to selling software often its a good idea to start off with one of the original 'app stores' - otherwise known as shareware registration services or payment processors - if you dont want to manage the sales process and downloads yourself.

Depending on the nature of your software, there may be sites that sell products specific to the industry/interest your software serves who retail software.  That would give you very targetted exposure.


问:
Killer semi-unique programming language features
When learning a new programming language you sometimes come across a language feature which
makes you wish you had it in your other programming languages that you know.

What are some language feature which were at the time of learning very new to you and that you wish your other programming languages had.

An example of this is generators in Python or C#.
Other examples may include list comprehensions in Python, template in C++ or LINQ in .NET or lazy evaluation in Haskell.

What other semi-unique language features have you come across which were completely new and enlightening to you?  Are there other features of older programming languages which were unique and have fallen out of fashion?

答:
Practically anything in Haskell

Monads. Yes - the big scary word that makes increadibly easy parsers, IO, operations on Lists and other things so easy (once you notice common pattern)

Arrows. The same for advanced users ;)

Standard stuff like lambdas etc.

Currying functions

Algebraic data types

Pattern matching

And many more.

PS. Yes. I am Haskell fanboy if anyone asked.


问:
Choosing a licence for open source projects
I've done some open source projects, and I plan to do more in the future. So far, I've released all my code under GPL, but I've read a few articles which claim GPL is too restrictive for any code to be used in corporate environment. This, supposedly, reduces contributions.

Here's what I wanted to accomplish:

For full applications:

no commercial use with the exception of selling support for the application (i.e. the app cannot be sold, but everything around it can)

For libraries (components, plugins, ...):

can be included into commercial projects without modifications

any modification the the library/component must be open sourced (contributed back) - the rest of the project, commercial or not, is not affected

For applications, GPL still seems the logical choice. For libraries, my primitive understanding of licences makes me think that LGPL is a good match, but, I'm not sure. I've looked at MIT licence, and that seems too permissive.

Most of the time, I want people to use my code anywhere they want to, as long as any improvements are contributed back.

This brings me to my question(s): is LGPL a logical choice for open source libraries, components, plugins etc? Is there a better alternative? Is GPL a good choice for my applications or is there something better?

Update:

For those who are interested in my final decision, I've decided to release my libraries under multi-license scheme, MPL, LGPL and GPL. This enables virtually everyone to use my code with no obligations, unless they modify it under MPL, in which case it would have to be contributed back.

This means the code can be used by both FSF and proprietary software, but "bad" commercial exploitation is prevented (or so I'd like to think).

答:
If you want to prevent commercial use of your software, GPL won't cut it. GPL tends to be avoided by commercial enterprises in products they sell because of the requirement to redistribute the modified source, but they're free to use GPL software internally. That's not to say businesses aren't set up to sell GPL software, or build hardware around GPL software (LinkSys, for example), but most businesses would prefer not to share their product with competitors.

I don't know if the Creative Commons Attribution Non-Commercial No Derivatives license is what you want (the only restriction you mentioned is commercial use), but if not, you might need to have a license prepared for you by an attorney that contains the language granting rights you wish license holders to have.

Also, once you begin to include such restrictions as non-commercial use and non-modifiability, you may no longer meet the criteria for an open source license as defined by the Open Source Initiative. Their site also lists other approved OSS licenses. Perhaps there's one already that matches your goals.

And adequately defining your goals will be key before selecting the rights and limitations you place on users of your software. Is popularity more important than modifiability or distribution or usage or…? Think of your objectives in releasing the code to begin with, and in what spirit you do that or the terms under which you grant access may have the opposite effect.


问:
Writing to event log - best practice if log is full
I have an application that writes to its own Event Source.  The Event Source itself is created upon install to prevent user vs admin access issues at runtime.

Should writing to our own Event Source fail, the event is instead written to the Application log (two events actually, on for the original event data, and another saying 'Could not write to own event log because...' or something similar).

We've recently discovered a problem that when the Application event log is full, the exception is unhandled.  Now granted, I could just eat the exception (similar to what this answer says).

So what is the best behavior? The application is attempting to log the issue and attempting to log that there is a problem.  Should I eat the exception, let the logging operation fail silently and continue execution? Or should I let the exception bubble up the call stack so that user/developers know of the issue?

What's the recommended approach under these conditions?

答:
From your description it sounds like you should try to set up your own event log to overwrite earlier entries. But I am unclear as to why you log the events in the first place.

Just eating the exception, to me, indicates that you don't really want the log in the first place; it's a little like good ole VB's "On Error Resume Next". So if you're willing to eat the exception, you might be willing to just flush the log. If you don't - and continously eat the exception, the eventlog will be flawed as it will seem like no events have occured since the date it ran full.

If the exceptions are actually important, you should let them bubble up the stack so that a user/administrator will be forced to take action.

EDIT: I think if you have a machine where the user/administrator allows both your log and the event log to run full, while not allowing overwrites; (s)he probably doesn't really care. I think I wouldn't throw an error and halt execution - but rather try to notify more discretely - ie. activating a label or updating the status text or similar depending on your UI.

OwnerDisplayName: MoSlo


答: Use log4net with EventLogAppender. It can degrade gracefully and write to its internal logger why it has failed. You can easily forget worrying about maintaining your code that write logs to EventLogger.</p>

Title: Writing to event log - best practice if log is full

Body:
I have an application that writes to its own Event Source.  The Event Source itself is created upon install to prevent user vs admin access issues at runtime.

Should writing to our own Event Source fail, the event is instead written to the Application log (two events actually, on for the original event data, and another saying 'Could not write to own event log because...' or something similar).

We've recently discovered a problem that when the Application event log is full, the exception is unhandled.  Now granted, I could just eat the exception (similar to what this answer says).

So what is the best behavior? The application is attempting to log the issue and attempting to log that there is a problem.  Should I eat the exception, let the logging operation fail silently and continue execution? Or should I let the exception bubble up the call stack so that user/developers know of the issue?

What's the recommended approach under these conditions?

OwnerDisplayName: Raj


问:
Be liberal in what you accept... or not?
[Disclaimer: this question is subjective, but I would prefer getting answers backed by facts and/or reflexions]

I think everyone knows about the Robustness Principle, usually summed up by Postel's Law:

Be conservative in what you send; be liberal in what you accept.

I would agree that for the design of a widespread communication protocol this may make sense (with the goal of allowing easy extension), however I have always thought that its application to HTML / CSS was a total failure, each browser implementing its own silent tweak detection / behavior, making it near impossible to obtain a consistent rendering across multiple browsers.

I do notice though that there the RFC of the TCP protocol deems "Silent Failure" acceptable unless otherwise specified... which is an interesting behavior, to say the least.

There are other examples of the application of this principle throughout the software trade that regularly pop up because they have bitten developpers, from the top off my head:

Javascript semi-colon insertion

C (silent) builtin conversions (which would not be so bad if it did not truncated...)

and there are tools to help implement "smart" behavior:

name matching phonetic algorithms (Double Metaphone)

string distances algorithms (Levenshtein distance)

However I find that this approach, while it may be helpful when dealing with non-technical users or to help users in the process of error recovery, has some drawbacks when applied to the design of library/classes interface:

it is somewhat subjective whether the algorithm guesses "right", and thus it may go against the Principle of Least Astonishment

it makes the implementation more difficult, thus more chances to introduce bugs (violation of YAGNI ?)

it makes the behavior more susceptible to change, as any modification of the "guess" routine may break old programs, nearly excluding refactoring possibilities... from the start!

And this is what led me to the following question:

When designing an interface (library, class, message), do you lean toward the robustness principle or not ?

I myself tend to be quite strict, using extensive input validation on my interfaces, and I was wondering if I was perhaps too strict.

答:
As a counterpoint to Mason's example, my experience with the Session Initiation Protocol was that while different stacks would interpret the relevant RFCs differently (and I suspect this happens with every standard ever written), being (moderately) liberal in what you accept means that you can actually make calls between two devices. Because these devices are usual physical things as opposed to pieces of software on a desktop, you simply have to be liberal in what you accept, or your phone can't call another phone of a particular make. That doesn't make your phone look good!

But if you're writing a library, you probably don't have the problem of multiple parties interpreting a common standard in mutually incompatible ways. In that case, I'd say be strict in what you accept, because it removes ambiguities.

The Jargon File also has a horror story on "guessing" a user's intent.


问:
Is there a canonical book on design patterns?
I am interested in learning design patterns and would like to know what are considered top tier books in learning this subject.

Is there a book out there that's the de-facto standard for describing best practices, design methodologies, and other helpful information on design patterns? What about that book makes it special?

答: Yes, there is a well known book about design patterns: Design Patterns: Elements of Reusable Object-Oriented Software and the authors are often called "the Gang of Four" (GoF) and is referenced in almost all texts about design patterns.</p>


答:
Teams often struggle to change over from estimating based on detailed specifications to estimating based on light weight User Stories. There is comfort in the level of detail. Consequently they tend to spend a lot of time focusing on the What/How of the User Story and do not feel comfortable making estimates.

The process that I have seen teams move to with success is as follows:

Grooming meeting (prior to Planning)
Time box the discussion and planning poker for each User Story to between 10 to 20 minutes; depending on the complexity of the User Story. This requires a Leap of Faith from the team and needs to be back up with a Safe to Fail environment.

In Sprint Planning Part 1
Use commitment based planning to work out which User Stories the team can commit to in the sprint. This is a second Leap of Faith. At the end the Planning Part 1 the team informs the Product Owner of what they think they can accomplish this sprint. However they reserve the right to discuss this again after the results of Planning Part 2. Once used to this process Part 1 should take less then 30 minutes.

In Spring Planning Part 2
All of the User Stories are discussed further and split into tasks. A little bit of high level design / what are we building discussion can occur here. Each task is estimated in hours.

The team now totals up the estimated hours and compared that to how many working hours they have in the sprint. This comparison acts as a guide. If the team feels that they have over committed themselves, the Scrum Master can immediately go and discuss this with the Product Owner and de-scope User Stories from the sprint as appropriate.

Overall I have seen that this process gives the teams a good balance of knowing what they are doing and taking appropriate risks.
Good luck

Title: Scrum - What and How meetings


答:
Design Patterns: Elements of Reusable Object-Oriented Software comes very close to my definition of a canonical book on design patterns. According to its wikipedia article (emphasis mine):

The original publication date of the book was October 21, 1994 with a 1995 copyright, and as of July 2010, the book was in its 38th printing. The book was first made available to the public at OOPSLA meeting held in Portland, Oregon, in October 1994. It has been highly influential to the field of software engineering and is regarded as an important source for object-oriented design theory and practice. More than 500,000 copies have been sold in English and in 13 other languages.

Ward Cunningham, a design patterns pioneer, maintains an online catalog of the book's patterns on WikiWikiWeb. And according to the Wikipedia article on design pattern (again, emphasis mine):

Design patterns gained popularity in computer science after the book Design Patterns: Elements of Reusable Object-Oriented Software was published in 1994 by the so-called "Gang of Four" (Gamma et al.).

There are quite a few other books referenced in the same article  as notable in the genre:

Pattern-Oriented Software Architecture Volume 1: A System of Patterns, by Douglas Schmidt, Michael Stal, Hans Rohnert, and Frank Buschmann,

Patterns of Enterprise Application Architecture by Martin Fowler,

Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions., by Hohpe, Gregor and Bobby Woolf, and

Head First Design Patterns, by Eric T. Freeman, Elisabeth Robson, Bert Bates, and Kathy Sierra.

Of those I've read Fowler's book, it's highly influential and a good read. At certain points it's a little vague for my taste, but overall it's an enjoyable book. There's an online catalog of the patterns included in the book, with minimal descriptions.

I've also  skimmed through Head First Design Patterns, and if you have read any other book of the Head First series, it's of the same high quality and as enjoyable as most books in the series:

Head First is a series of introductory instructional books to many topics, published by O'Reilly Media. It stresses an unorthodox, visually intensive, reader-involving combination of puzzles, jokes, nonstandard design and layout, and an engaging, conversational style to immerse the reader in a given topic.

The term "design pattern" is somewhat vague, as every general reusable solution can be considered a design pattern. I've always noticed a tendency to apply the label on the solutions described in one of the notable books I've listed above, and more specifically the Gang of Four and Fowler books. Design patterns do not follow a unique development process, they are normal software solutions that happen to be immensely reusable and they are extremely hard to identify.

But if you compare the online catalogs for both books with the contents of language specific books you'll notice that they are often used as templates. So I'd say that both books are very close to being canonical references, with the GoF book being the more important one from a historical perspective, even though both books are limited to object oriented programming.

Title: Is there a canonical book on design patterns?

Body:
I am interested in learning design patterns and would like to know what are considered top tier books in learning this subject.

Is there a book out there that's the de-facto standard for describing best practices, design methodologies, and other helpful information on design patterns? What about that book makes it special?


问:
What limitation will we face if each user-perceived character is assigned to one codepoint?
What limitations will we have if Unicode standards had decided to assign one and only one codepoint to every user-perceived character?

Currently, Unicode has code-points that correspond to combining characters.  Such characters combine with a previous code-point (or sequence thereof) to present to the user what appears to be a single character.

From what I can see, the current standard is full of complexities. (We're not talking about   encoding issue here.  Even if we try to avoid any kind of complexities by using an encoding like UTF-32, the problem still persists.)

For example, in Unicode when a grapheme cluster is represented internally by a character sequence consisting of base character + accent, then when the user clicks the > button to skip to the next user-perceived character, we had to skip from the start of the base character to the end of the last character of the cluster.

Why does it need to be so hard? Why can't Unicode assign a single code point to every user perceived character such going to the user-perceived character is simply a matter of reading the next code point?

The unicode website seems to acknowledge this complexity:

In those relatively rare [not rare at all!] circumstances where programmers need to
  supply end users with user-perceived character counts, the counts
  should correspond to the number of segments delimited by grapheme
  clusters. Grapheme clusters may also be used in searching and matching

Diacritics are also the reason why things don't work as expected. For example, if I throw 2 ピ characters (japanese katakana PI using the unicode representation U+30d2 U+309a) into a String builder and reverse it, I would naturally expect the output to be 2 ピ characters (i.e. ピピ), but it gives an invalid output of ゚ピヒ !

If Unicode had assigned individual code points for each user-perceived character and scrapped the idea of grapheme clusters, this wouldn't have happened at all.

What I would like to know is, what exactly is wrong with representing every user-perceived character as one unicode codepoint? Is it likely that doing so would would exceed U+10FFFF possible code points (if it does exceed U+10FFFF code points I see no reason why they couldn't have set the limit to 2^32 in the first place), Even when there is so much spare space to include the whole family of Elf Languages ?

Unicode states:

If you wanted, for example, to give each “instance of a character on paper throughout history” its own code, you might need trillions or quadrillions of such codes;

But seriously that doesn't make sense at all. Where is the source for making such a claim? A trillion codes is quite an over-statement.

答:
it's because back in the olden days a unit of data was 8 bits, the widespread 32-bit architecture is younger than the old ASCII standard on which the UTF variants are based (for backwards compatibility)

besides programmers on those old (sizeof(int)== 16 bits) architectures never liked using more resources than needed (memory in particular remember that UTF32 takes 4 times as much memory than UTF8 for text only in the latin alphabet) as back in the day you only got a few hundred kilobytes at your disposal at best

that and you don't need any other characters than those in ASCII if you are only programming for the english speaking (or any language with no accents)

one big lesson you can here learn is: anything that grows towards changing requirements is rarely future proof against the next change in requirements and generally only good enough for the current requirements and if someone thinks of a solution that exceeds the requirements it will likely get shot down for various reasons (most common will be performance, memory use and compatibility)

also allow me to point you towards this xkcd comic that might shed some light on the situation


问:
Alternatives to Professional Version Control
We're teaming up with some non programmers (writers) who need to contribute to one of our projects.

Now they just don't like the idea of using Git (or anything for that matter) for version controlling their work. I think this is because they just don't find it worthwhile to wrap their heads around the twisted concepts of version control. (when I first introduced them to branching and merging -- they looked like I was offending them.)

Now, we're not in a position to educate them or convince them to use it. We're just trying to find alternatives so that we get all their work versioned (which is what we need) -- and they get easy workflow and concentrate on what they do.

I have come up with some ideas...

tell them to save their work as a separate file every time they make some non-trivial change, and then use a diff on our side to just track changes.

write a program (in Python) that implements the "milestones" in CSSEdit in some way.

About the project:

It is a natural language processing system (written in C + Python). We've hired some writers to prepare inputs for the system in different languages. And as we evolve the software, we'd need those writers to make changes to their inputs (articles). Sometimes the changes are very small (a word or two), and other times big.

The reason we need to version control those changes is because every small/big change in the input has the potential to change the system's output dramatically.

答:
I've had to work with non-programmers many times (mostly graphic artists, and if your writers have as little clue how to manage work files as artists then you are in for... h'mmm.... fun...). There are three possible approaches:

Pretend they are programmers, try to teach them how to use version control. This will not work and you will have constant fights.

Write them a very simple tool which just grabs the current version & sticks it somewhere so they can rewind to yesterday's files if necessary. This is possible, and I did this for a team of DVD creators (making menus, graphics, all sorts of things) many years ago with some success: the tool I wrote was a one-click wrapper to PkZip (you can see this was a while ago) and it just zipped up the work directory and named the archive for the date + time.

Take control of what they produce yourself. Make it clear that their files have to be delivered to a programmer and only become part of the project when the programmer accepts the files: the programmer then checks them into version control and the content is managed in a professional way.

Personally I think option 3 is the way to go. It means some pain & irritation for whoever has to take the file deliveries and get them checked in, but way less than any other option.

I would also say, be aware that non-programmers will deliver files with any old filename you can think of. Naming conventions are strangely alien to them. They will give you a file called "Picture" or something and then when you tell them the things that are wrong with it will give you a file called "Picture_Final", which has only correct about 3 of the faults. When you point this out you will get another file, called "Picture_NewFinal", and then (if you are lucky) "Picture_NewFinal2", although it is possible that they will at this point jettison any sense of historical development and call it "Spanner Icon thing".

Again you can try to enforce a naming convention, which means telling them in advance what every file is to be called, or you can spend hours unscrambling & renaming what they send you. Here I would say you want the spreadsheet for your own sanity anyway, so have a go at getting them to follow it: just don't be surprised when they don't.

Hope that helps -- have fun!


问:
What's the worst programming book you've ever read?
What's the worst programming-related or technical book you've ever read? This can be any book which one way or another can be connected to programming, as long as it's not fiction.</p>

答:
Verification of Sequential and Concurrent Programs, Second Edition, by Krzysztof R. Apt and Ernst-Rüdiger Olderog.

Maybe it was the subject matter, but I distinctly remember this as being the driest book I have ever read. Getting all the way to the end was a genuine soporific challenge.


答: If a script has M letters and N diacritics, then a precomposed representation requires up to M*N code points, while a decomposed representation requires only M+N.  Combining characters prevent Unicode from "running out of code points".

Title: What limitation will we face if each user-perceived character is assigned to one codepoint?

Body:
What limitations will we have if Unicode standards had decided to assign one and only one codepoint to every user-perceived character?

Currently, Unicode has code-points that correspond to combining characters.  Such characters combine with a previous code-point (or sequence thereof) to present to the user what appears to be a single character.

From what I can see, the current standard is full of complexities. (We're not talking about   encoding issue here.  Even if we try to avoid any kind of complexities by using an encoding like UTF-32, the problem still persists.)

For example, in Unicode when a grapheme cluster is represented internally by a character sequence consisting of base character + accent, then when the user clicks the > button to skip to the next user-perceived character, we had to skip from the start of the base character to the end of the last character of the cluster.

Why does it need to be so hard? Why can't Unicode assign a single code point to every user perceived character such going to the user-perceived character is simply a matter of reading the next code point?

The unicode website seems to acknowledge this complexity:

In those relatively rare [not rare at all!] circumstances where programmers need to
  supply end users with user-perceived character counts, the counts
  should correspond to the number of segments delimited by grapheme
  clusters. Grapheme clusters may also be used in searching and matching

Diacritics are also the reason why things don't work as expected. For example, if I throw 2 ピ characters (japanese katakana PI using the unicode representation U+30d2 U+309a) into a String builder and reverse it, I would naturally expect the output to be 2 ピ characters (i.e. ピピ), but it gives an invalid output of ゚ピヒ !

If Unicode had assigned individual code points for each user-perceived character and scrapped the idea of grapheme clusters, this wouldn't have happened at all.

What I would like to know is, what exactly is wrong with representing every user-perceived character as one unicode codepoint? Is it likely that doing so would would exceed U+10FFFF possible code points (if it does exceed U+10FFFF code points I see no reason why they couldn't have set the limit to 2^32 in the first place), Even when there is so much spare space to include the whole family of Elf Languages ?

Unicode states:

If you wanted, for example, to give each “instance of a character on paper throughout history” its own code, you might need trillions or quadrillions of such codes;

But seriously that doesn't make sense at all. Where is the source for making such a claim? A trillion codes is quite an over-statement.


答: Depending on your needs one option would be to utilize the Microsoft Enterprise Library Logging block. I have successfully used it to log to flatfiles as well as internal databases. You can set the size of the log files and the behavior when a given file reaches it's max size. It's a pretty flexible (open source) library at least worth a look.</p>


问:
Simulating Agile Software Development
Looking for a guide or example of where a group  facilitator walks a group through an agile software development cycle playing the role of both the event facilitator and the key stakeholder or project owner.</p>

答:
The Scrum Lego Game would be a great way to show the group, what Scrum is and more importantly what it feels like.

Here are two sets of detailed instructions

http://www.agile42.com/training/scrum-lego-city/

http://www.slideshare.net/krivitsky/lego-for-extended-scrum-simulation-1057214

Title: Simulating Agile Software Development


问:
Getting started with build tools
I am on my final year on CS, working on my first significant project, so I thought its about time to learn and use build tools.

I have read about Maven mainly and heard about Ant. I would like to know your opinion about which I should learn to use for a project that will be developed only by one person, keeping in mind the learning curve, and the functionality that will be useful in this case.

答:
I would have a go at Maven. It is the most popular build tool used with Java these days. It seems like pretty much every Java framework and library you can think of is built using it which means (at least) two things:

Going forward it is most likely a more desirable skill to have than Ant.

The dependency management built into Maven (a feature that Ant does not have) can be used to effortlessly include all those 3rd party libraries and frameworks in your project.

It also uses good philosophies like 'convention over configuration' which encourages consistent project structures in all the projects that use it (so when you see a Maven project, you immediately know where most things should be) and that your build configurations are nice and small and maintainable.

Neither tool is particularly difficult to learn. Learning Maven is more about learning concepts whereas learning Ant is more about learning individual commands.

EDIT: This is a really good doco on Maven: http://www.sonatype.com/books/mvnref-book/reference/

Title: Getting started with build tools


问:
Ordered enumeration: IEnumerable or Array (in C#)?
Typical context: I make an extension method for a collection which considers that the elements are ordered. The function starts at the beginning, at index 0, and the order has significance. Examples: Grouping by sequence or Indexes of an item.

However, I'm always stumped as to what to extend: IEnumerable<T> or T[]. My rationale was clarity of purpose: An array has a notion of ordering, whereas an IEnumerable is implemented by many generic collections, not all of which have a notion of order:

Dictionary - unordered

HashSet - unordered

LinkedList - ordered

List - ordered

Queue - ordered

SortedDictionary - sorted (not original order)

SortedList - sorted (not original order)

SortedSet - sorted (not original order)

Stack - reversed

As well as any other implementation which might or might not be ordered.

Also, I'm not certain if the enumerator is reset if an enumeration is not completed, so if that's a worry, then who knows at what point the enumeration would start? Enumerating an array would always start at the beginning.

So to me, it makes more sense to extend a T[]. But am I correct in thinking that? Am I worrying too much? What's the proper approach for ensuring "ordered" enumeration?

答:
IEnumerable declares that the collection you have can be enumerated; it doesn't imply anything about the content.  This isn't a bad thing -- containers can have additional capabilities and restrictions on top of individual interfaces.

(I don't see how an array is any better here -- it's indexable, as is an IList and other containers, but there is nothing about indexing that implies data order.  Your list is kind of odd -- some items are "ordered" in that they preserve insertion order, others are "ordered" as in they are sorted.  They are two different things.  Other than the SortedSet/SortedList/SortedDictionary, you shouldn't assume the data is in a particular order unless you handle that inside your own code.)

However, IEnumerable provides a LINQ extension that allows you to .OrderBy, so anything that is enumerable can be returned in an IOrderedEnumerable sorted order.  That's a LINQ-specific interface though (and not implemented by default by SortedSet/SortedList/SortedDictionary, so it might not make sense to extend that particular interface...)


问:
How can a PHP programmer best prepare for a C++ course?
I have never programmed in C++, but am going to be taking a class that involves programming in C++ in January. I want to be able to excel in the class, and looking for advice, as I come from a PHP background. How can I best prepare myself for success?</p>

答:
Your question is like asking, 'How can a baseball player prepare for a basketball match?'. Once a programmer learns a language, usually he/she has no problem learning a new language; same as a baseball player adapting to a basketball game.

The sportsman is fit, and the programmer has a basic understanding of language syntax and structure.

You will find several difference between C++ and PHP, yet a lot of time you will be thinking on how C++ is like PHP.

PHP is less strict than C++; C++ is what is considered a general-purpose programming language while PHP is a scripting language aimed at web development.

C++ process is different, a c++ program is converted into binary code, then loaded into memory and run directly.

If you really want to excel, then in my book you have to actually learn it on your own. I excelled in programming courses, because I knew most of the course beforehand. I see the best and most passionate programmers learning the language on their own.

If there is a book included with the course try to get your hands on it, and read it before the start of the course at least get ahead. Most of us don't have photographic memory and we can only learn by hearing something over and over again.

Learn it on your own and the course lecture would be the review. Warning: Following this advice might cause you to fall asleep in lectures.

Again start reading tutorials and books, start building things and you won't have problem excelling in your C++ class.

Books:

The C++ Programming Language

C++ Primer

Thinking in C++: Introduction to Standard C++

The C++ Standard Library

Extra:
THe New Boston - C++


答:
I find that proficiency at a given programming language is much like proficiency at any skill. While a good deal of study can help mitigate difficulties, the real "trick" is to practice1. And yes, some languages will be closer than others, just like certain disciplines will be easier to transfer than others — it is harder for a guitar player to learn viola than it is for a violinist to learn viola. The best thing you can do, then, is to focus on the major differences. And you'll definitely notice several major paradigm shifts between the two languages.

Here are some recommendations to help bridge that gap:

At a bare minimum, the idea of the PHP reference is very different from the C++ pointer. Considering its importance, you might want to consider studying that first.

After that, I would recommend learning first how to compile something larger than one or two files. While your at it, make sure you know the difference between #import <lib>; and
#import "lib";

Learn the importance (and the difference) between .h and .cpp files.

Pre-processor directives/macros. Learn them and be able to write them.

1. How do you get to Carnegie Hall? Put this into Google Maps: 881 7th Ave. New York, New York.

Title: How can a PHP programmer best prepare for a C++ course?

Body: I have never programmed in C++, but am going to be taking a class that involves programming in C++ in January. I want to be able to excel in the class, and looking for advice, as I come from a PHP background. How can I best prepare myself for success?</p>


答:
They both have their main strength and will both be sufficient to fill your needs.  Here is my own little  comparison with both hopefully will allow you to choose.

Maven

The more advanced of the two and certainly one of the most advanced build tool I have used.  But to call it a built tool is not truly describing it as one of the most innovative feature of Maven is about dependency Management.  In short it will handle all the mucking around with external libraries, it will download them for you it will validate that their dependencies are also resolved and downloaded, in short it will handle a lot of the greasy details of building a complex system.

Maven also relies heavily on conventions on how you layout your project's folders for source code, resources, tests etc.  Follow these conversions and it magically just work (tm).  Try to be smarter than them and it will give you pains beyond comprehension.  I exaggerated a bit here, V3 has gotten a lot more friendly than the previous ones but it will leave you sometimes scratching your head.

Still these convention make it possible to create a project very quickly and with a few declarations in your pom.xml (the build entry point) you will be able to build your project, run all your tests and package a jar file just by issuing a single command line statement (mvn clean package).  No scripting, no programming just follow convention.

Another side effect of these conventions is that all Maven projects are basically created the same so getting a new guy to join in or digging deeper in one dependency that is acting up is a breeze.

Magic is probably the worst aspect of working with maven.  If you are a control freak Maven will often throw you off balance.  But sticking to it and understanding the magic will richly reward you with overall greatly increased productivity.

Ant

Ant is more ancient than Maven and does not handle as much.  Ant will have pre-packaged a lot of task that you must manually assemble into a build script.  The script is a mix between declarative xml and scripting.  the Ant scripting is actually Turing complete  so you can do a lot with it but XML is not the best medium to write complex scripting logic.

Ant will leave you in control and will provide lots of canned stuff for you already.  However this control comes at a cost and you will have to get the ground work and frame your build environment.

Ant also does not, at least not naturally, handle dependencies.  to it it is just another classpath folder that you must populate manually.  there are ways to handle this though through other systems such as Ivy.

Ant with Ivy will provide almost all the power of Maven but will leave you much more control over your process.

That said once the build framing is done Ant is pretty easy to use and if you structured your build.xml files right is pretty easy to expand and scale.  frame your build wrong though and you find yourself having to re-write everything from scratch just to support that second project.

Best of both worlds

Go with Maven as it will demand just about the same amount of work to setup as a tool but will get you going much faster.

Do read the Maven book it has all you need to get started.  If at some point you need more control you can check out the Maven Antrun plugin.  It will allow you to execute arbitrary ant script while still have access to all the Maven environment and conventions.  That said, most likely you will not need it.  Personally I've been using Maven for 6 years and only once had to use it.

There are other build tools for Java but these two (along with Ivy to complement Ant) but I have not tried them so I cannot comment them here.

Title: Getting started with build tools

Body:
I am on my final year on CS, working on my first significant project, so I thought its about time to learn and use build tools.

I have read about Maven mainly and heard about Ant. I would like to know your opinion about which I should learn to use for a project that will be developed only by one person, keeping in mind the learning curve, and the functionality that will be useful in this case.


问:
Dynamically vs Statically typed languages studies
Do there exist studies done on the effectiveness of statically vs dynamically typed languages?

In particular:

Measurements of programmer productivity

Defect Rate

Also including the effects of whether or not unit testing is employed.

I've seen lots of discussion of the merits of either side but I'm wondering whether anyone has done a study on it.

答:
I honestly do not think that Static vs Dynamic typing is the real question.

I think that there are two parameters that should come first:

the expertise level in the language: the more experienced you are, the more you know about the "gotchas" and the more likely you are to avoid them / track them down easily. This is also true about the particular application/program you are working on

testing: I love static typing (hell I like programming in C++ :p) but there just so much that a compiler / static analyzer can do for you. It's just impossible to be confident about a program without having tested it. And I am all for fuzzy testing (when applicable), because you just can't think about all possible input combinations.

If you are comfortable in the language, you'll write code and you'll track down bugs with ease.

If you write decoupled code, and test each functionality extensively, then you'll produce well-honed code, and thus you'll be productive (because you cannot qualify as productive if you do not assess the quality of the product, can you ?)

I would therefore deem that the static vs dynamic debate with regard to productivity is quite moot, or at least vastly superseded by other considerations.


答:
I think that you want to combine 2 different concepts into 1. The data structure and its contents order are 2 separate things.

Ordering is a tricky subject. For example, what does ordering a list of persons mean? Even when order/sort key is defined, it has to have a direction and you have to decide what to do with nulls (if any), date issues, etc.

If data ordering is important to your method, then may be your method should be responsible for the ordering of the data as part of its set up instead of asking data to be ordered by the caller. A similar approach is used by some string match algorithms where a dictionary is built inside the search method from the passed string before the string is searched. I know this is not the exact case, but it is the closest example I could think of.

Title: Ordered enumeration: IEnumerable or Array (in C#)?

Body:
Typical context: I make an extension method for a collection which considers that the elements are ordered. The function starts at the beginning, at index 0, and the order has significance. Examples: Grouping by sequence or Indexes of an item.

However, I'm always stumped as to what to extend: IEnumerable<T> or T[]. My rationale was clarity of purpose: An array has a notion of ordering, whereas an IEnumerable is implemented by many generic collections, not all of which have a notion of order:

Dictionary - unordered

HashSet - unordered

LinkedList - ordered

List - ordered

Queue - ordered

SortedDictionary - sorted (not original order)

SortedList - sorted (not original order)

SortedSet - sorted (not original order)

Stack - reversed

As well as any other implementation which might or might not be ordered.

Also, I'm not certain if the enumerator is reset if an enumeration is not completed, so if that's a worry, then who knows at what point the enumeration would start? Enumerating an array would always start at the beginning.

So to me, it makes more sense to extend a T[]. But am I correct in thinking that? Am I worrying too much? What's the proper approach for ensuring "ordered" enumeration?


答:
Maven and Ant have been very popular build/project management tools, but they are not going to be around forever. If you want to try something that is on the bleeding edge these days, check out Gradle.

Gradle gives you the best of both (Ant & Maven) worlds.

Dependency management out of the box (Ant does not have this without Ivy and it is a bit cumbersome to set up)

A re-configurable/extensible project lifecycle. (You have the lifecycle with Maven but it is hard to reconfigure it)

No more XML. (When you write gradle scripts, you program in an actual language (groovy))

Multi-project build capabilities (Easier to have smaller more focused modules and to glue them together)

Integration with both Ant and Maven

(Just to mention some... for more, check out their website)

It might still be a good idea for you to learn about Ant and Maven, just because most places still use one of these two tools, so you can use it as an experience builder.

Title: Getting started with build tools


答:
C++ and PHP are worlds apart in terms of applications and usage patterns. Your PHP knowledge will help you by giving you a head start on basic programming concepts such as

Objects

Conditional Statements (If/Else)

Loops

etc...

As well as any program designing experience you may have picked up while developing PHP applications.

If you want to get the leg up in your course the best way is to start by ignoring your PHP background beyond the things outlined above and focus on some of the following:

Memory Management (Pointers, new/delete, Constructors/Destructors, RAII)

Differences between the PHP object model and the C++ object model

Basic Datastructures (Arrays, Trees, Linked Lists)

Basic Algorithms (Sorting, Searching and being able to determine the best algorithm for the job)

Another good resource is your teacher for the course. I'm sure if you send them an email they will be able to give you some resources to get started.