问:
How to avoid shooting yourself in the foot when using closure in JavaScript
The closure feature is widely used in JavaScript and make it quite difficult for programmer who was used to program in a no-closure language. So what is the best practice about using closure and how to avoid shooting yourself in the foot. </p>

答:
Understand what a closure is

A closure is a first class function which captures lexical bindings in it's environment.  This prevents the garbage collector from free'ing the space until all references to the closure are gone.

Understand how the closure will grow

You can easily create a memory leak with a closure because the only interface to the allocated memory is through the closure (typically).  You should make sure your closure will not grow unbounded.

Watch out for capturing references

This is more of standard gotcha, but it's even more important when dealing with closures.  A closure will capture lexical variables including ones that contain references.  This means whatever those references point to will continue stick around as long as the closure is around, unless they are explicitly weak refs.

Don't close over variables you don't need to close over

It's wasteful, bad code and makes it more likely you'll introduce a memory leak.

Make the functions that will become closures as simple as possible

The bigger, more complex the function that will become a closure, the more likely you are to have a bug which may lead to a memory leak.

Don't create closures when they aren't needed

See: common sense


问:
Research on software defects
There is a chapter in "Making Software: What really works and why we believe it" By Andy Oram and Greg Wilson about software defects, and what metrics can be used to predict them.

To summarize (from what I can remember), they explained that they used a C codebase that was open source and had a published defect tracking history. They used a variety of well known metrics to see what was best at predicting the presence of defects. The first metric that they started with was lines of code (minus comments), which showed a correlation to defects (.i.e. as LOC increase so do defects). They did the same for a variety of other metrics (don't remember what off the top of my head) and ultimately concluded that more complex metrics were not significantly better at predicting defects than simple LOC count.

It would be easy to infer from this that choosing a less verbose language (a dynamic language?) will result in less lines of code and thus less defects. But the research in "Making Software" did not discuss the effect of language choice on defects, or on the class of defects. For example, perhaps a java program can be rewritten in clojure (or scala, or groovy, or...) resulting in more than 10x LOC savings. And you might infer 10x less defects because of that.

But is it possible that the concise language, while less verbose, is more prone to programmer errors (relative to the more verbose language)? Or, that defects written in the less verbose language are 10x harder to find and fix? The research in "Making Software" was a fine start, but it left me wanting more. Is there anything published on this topic?

答:
The only interesting paper that I found was Comparing Observed Bug and Productivity Rates for
Java and C++ (ACM membership required), published in 1999. The author used a modified Personal Software Process to gather productivity and defect information. The author found that a C++ program contained 2-3 times more defects than a Java program, C++ generated 15-30% more defects per line, and Java was 30-200% more productive in lines of code produced over time. Since only a single programmer was used, and this individual was experienced in C++, but only learning Java, it's not definitive and an experienced Java programmer would be more proficient. However, this study was notable because it provides a methodology for measuring productivity of a programming language.

I would like to point out a few possible issues though...

Lines of code is a shaky measurement, at best. It's easy to count using various tools, and these tools often have configurable rules so that you can get the optimal counts for your organization's coding style. However, a line of Python is not the same as a line of C - you can do a lot more in a line of Python than a line of C.

The metric they discuss in Making Software, defects/SLOC, is called defect density. It's a fairly common metric, but because it's based on SLOC, it suffers from the same problems as any SLOC-based metrics. You need to have a standardized method of counting and use this consistently. You also can't easily compare defect density across programming languages with any value.

Also, simply comparing programming languages isn't necessarily a fair comparison. You also need to compare available tools and resources. For example, using static analysis and code reviews are known to reduce defects. Different languages have varying support for static analysis, unit testing, and you might not have access to people proficient enough in the language to conduct a code review.

Ultimately, I think that talking about verbosity versus defects is the wrong thing to do. It's better to look at techniques and processes to reduce defects to an acceptable level for your product. That includes your choice of programming language, with regards to productivity given your team and supporting tools.

ContentLicense: CC BY-SA 3.0

Title: Research on software defects


问:
Interactive training site for Javascript complete with code challenges
A few months ago I discovered a cool course called Rails for Zombies. This is a great site that allows us to write code and see the results. It takes us through the paces to get us up to speed with Rails. You have to pass each level (including code challenges) before being taken to the next level, and it gets you grounded in the fundamentals of Rails.

I'm wondering if an interactive tutorial site exists for Javascript? One that will walk me through the paces of writing better Javascript, and challenge me along the way.

答:
The following answer might not help you with general Javascript, but it might. And it'll definitely help with jQuery.

From the makers of Rails for Zombies, I present to you, jQuery Air: Captain's Log and jQuery Air: First Flight.

Yes, I know. Its jQuery. But I guarantee you it will help at least a bit...


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

ASP.NET MVC is not a replacement for WebForms.

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

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

答:
My experience:

Wrote CakePHP projects for one year.

Completed a medium sized Webforms project over six months.

Worked on a Windows Forms project for three years.

After that experience, I tried writing another app using webforms, and got frustrated after struggling for about a day with how webforms attempts to shield the developer from the reality that they're developing an application which uses html, javascript and css.

I then tried MVC out, and having more direct control over the output (and some experience with the MVC paradigm from CakePHP) I was able to complete that simple app exactly the way I wanted it in about 1/2 a day.

The availability of powerful UI frameworks like jQuery very much eliminates the appeal of giving up direct control of the output in favor of using often bulky pre-built UI components.

Title: When to favor ASP.NET WebForms over MVC


答:
Some languages have shorter programs because the provide pieces of  implementation for the programmer. If the coder doesn't have to implement something, they can't very well introduce defects into it. If I were to implement a hash-map in C, I'd probably make mistakes and defects. In python, I wouldn't because I already have a hashmap.

Other languages are shorter because they allow the programmer to write less text to get the same program. Compare C++:

```<code>for(int x = 0;x < 10;x++)
{
    std::cout << x << std::endl;
}
</code>```

and Python:

```<code>for x in range(10):
    print x
</code>```

You can see even on such a simple example that python takes way less characters then C++. But its not about the amount of characters you have to type, but rather the number of things you could have gotten wrong. The python simply has less possible mistakes to make then the C++ version.

All else being equal, I think more conciseness leads to less bugs because they are simply less things to get wrong. But all else may not be equal. The verboseness could be useful for other reasons and thus pay for itself.

Title: Research on software defects

Body:
There is a chapter in "Making Software: What really works and why we believe it" By Andy Oram and Greg Wilson about software defects, and what metrics can be used to predict them.

To summarize (from what I can remember), they explained that they used a C codebase that was open source and had a published defect tracking history. They used a variety of well known metrics to see what was best at predicting the presence of defects. The first metric that they started with was lines of code (minus comments), which showed a correlation to defects (.i.e. as LOC increase so do defects). They did the same for a variety of other metrics (don't remember what off the top of my head) and ultimately concluded that more complex metrics were not significantly better at predicting defects than simple LOC count.

It would be easy to infer from this that choosing a less verbose language (a dynamic language?) will result in less lines of code and thus less defects. But the research in "Making Software" did not discuss the effect of language choice on defects, or on the class of defects. For example, perhaps a java program can be rewritten in clojure (or scala, or groovy, or...) resulting in more than 10x LOC savings. And you might infer 10x less defects because of that.

But is it possible that the concise language, while less verbose, is more prone to programmer errors (relative to the more verbose language)? Or, that defects written in the less verbose language are 10x harder to find and fix? The research in "Making Software" was a fine start, but it left me wanting more. Is there anything published on this topic?

Body:
Some languages have shorter programs because the provide pieces of  implementation for the programmer. If the coder doesn't have to implement something, they can't very well introduce defects into it. If I were to implement a hash-map in C, I'd probably make mistakes and defects. In python, I wouldn't because I already have a hashmap.

Other languages are shorter because they allow the programmer to write less text to get the same program. Compare C++:

for(int x = 0;x < 10;x++)
{
    std::cout << x << std::endl;
}

and Python:

for x in range(10):
    print x

You can see even on such a simple example that python takes way less characters then C++. But its not about the amount of characters you have to type, but rather the number of things you could have gotten wrong. The python simply has less possible mistakes to make then the C++ version.

All else being equal, I think more conciseness leads to less bugs because they are simply less things to get wrong. But all else may not be equal. The verboseness could be useful for other reasons and thus pay for itself.


问:
Is there a personalizable programming language you can use to convert to others?
Is there a programming language in which you can set your own syntax configurations and it would convert the code to a language you choose?

For instance, you would choose specific configurations like "Python's indexed blocks", [a,b,c] initializes arrays, ^ for exponentiation and others. A script would convert it to your choice language's equivalent.

答:
Not to my knowledge.

I don't think it would be a particularly good idea either - one of the main benefits of a standard language syntax is that many people can read it, and if everyone invented their own syntax then nobody would be able to understand anyone else's code..... so this language might be fun for a hobbyist but not much use for anything practical.

The closest thing that exists would probably be Lisp, where the macro system lets you write your own new language constructs in a very flexible way. Normally you would still stick with Lisp syntax, but you can effectively redefine everything if you really want to.

As a result, Lisps tend to be particularly popular for implementing DSLs. A nice example is this data access DSL in Clojure (Korma) which takes care of all the boilerplate code required for database access.


问:
Choosing the right branching strategy for releases
Starting with a new dev team on a new project and we have to define our Branching strategy for our source repository (e.g. Microsoft Team Foundation Server 2010). We've run into a sticky discussion over whether or not to...

A. Have one Release branch from which we do production builds and then Label when something is actually released

OR

B. Have a new Release branch for each new Release into production (Ex. Version 1, 2, 3, etc...)

Option A seems pretty straight-forward but we're not sure if this will lead to problems in the long run. Option B seems like it just creates lots of one-time long-lived branches that just pile up over time.

Does anyone have any experience either way that could help us decide? Specifically, I'm looking to hear where the pain-points are for any one choice. Feel free to provide specific experience relative to TFS and/or Release-Management implications.

答:
I prefer option A.  Develop on the trunk and branch releases when they are stable.  This significantly limits the work in integrating hot fixes applied to production release.

I have been contracted to help a team that attempted option B get back on track.

A few things to consider.

Migrate hotfixes forward through all active code branches.  This can be done by merging, patching, and/or redevelopment.  These should be fully managed to ensure a fix gets applied to all appropriate releases, then to trunk.

Consider feature branches to enable developing features in isolation from the main code stream.  These are advised for experimental changes.  Feel free to abandon feature branches if the feature doesn't work out.

Tag and track your merge points.

Branch your releases when required.  I find this is normally when the release is ready for release candidate builds.  In some cases introducing incompatible changes to trunk may force and early branch.  Consider a feature branch.


答:
It would be easy to infer from this that choosing a less verbose
  language (a dynamic language?) will result in less lines of code and
  thus less defects. But the research in "Making Software" did not
  discuss the effect of language choice on defects, or on the class of
  defects. For example, perhaps a java program can be rewritten in
  clojure (or scala, or groovy, or...) resulting in more than 10x LOC
  savings. And you might infer 10x less defects because of that.

no no no :-) There is no way to infer from the fact that more lines of C code correlate with more defects that a language that is more expressive will have less defects for the same problem.  The first is a no brainer, for a given developer, given langauge, more lines of code will have more bugs.

But is it possible that the concise language, while less verbose, is
  more prone to programmer errors (relative to the more verbose
  language)? Or, that defects written in the less verbose language are
  10x harder to find and fix? The research in "Making Software" was a
  fine start, but it left me wanting more. Is there anything published
  on this topic?

It's definitely possible.  Maybe it's less readable?  Maybe it has functions names and operators that are hard to remember and easy to confuse?  Take C and rename printf() to p(), sin() to s(), cos to c().  Shorter code, right?

Studying this sort of stuff is extremely tricky.  Think about all the variables you need to control for.  Experience, size of project, application area, lanuage, enviornment, management.  Maybe this works for numerical analysis but doesn't work for web development?  Maybe you can show it for students but not for senior developers?  Perhaps it's true for a developer sitting in an open space but not in an office?  Maybe it's true for Americans but not for Japanese?  Maybe it's true for open source but not for commercial developers?

There are numerous studies on the productivity of programming languages, e.g.:

Haskell vs. Ada vs. C++ vs. awk vs.... an experiment in software prototyping productivity

Back in the day when people were pushing for Ada there was a few studies showing how better it is in terms of defect rates and productivity.  Ada is an example of a language designed towards the goal of eliminating defects.

This question reminds me of this blog post Hume, Causation & Science

My suggestion is to find out what works for you given your strenghts and application area.  Don't look for studies to tell you what to do, a study can give you some good ideas but you need to understand the limitations of these studies.

Here's a personal observation:  You can train yourself to lower your defect rate.  I found that doing TopCoder competitions where you get immediate feedback for defects will train you pretty quickly to eliminate some common defects and think about corner cases (which is where a lot of defects are found).  This sort of stuff will make an interesting study...

In terms of predicting defect rate I read a paper a while back on correlation between static analysis results and defects: The Effectiveness of Automated Static Analysis Tools for Fault Detection and
Refactoring Prediction (tl;dr not exactly correlated but bad code tends to have more issues though the defects may not be identified).

Title: Research on software defects


答: AFAIU you are looking for languages that can help you to write your own DSL (Domain Specific Language). There are many good candidates. Personally I would recommend Ruby or Io, because they offer 1) easy operator overloading, 2) meta-programming, and 3) fallback mechanisms like method_missing that you can use to create your own API. For example, take a look in sqldsl, a DSL written in Ruby that generates SQL by reading Ruby code.

Title: Is there a personalizable programming language you can use to convert to others?

Body:
Is there a programming language in which you can set your own syntax configurations and it would convert the code to a language you choose?

For instance, you would choose specific configurations like "Python's indexed blocks", [a,b,c] initializes arrays, ^ for exponentiation and others. A script would convert it to your choice language's equivalent.


答:
Edit: I've rearranged my answer because I want to emphasize a different point.

Verbosity can sometimes help to make defects easier to detect and fix. Consider the quadratic formula (positive root only for simplicity's sake):

```<code>float quad(float a, float b, float c)
{
   return (-b + sqrt(b*b - 4*a*c)) / (2*a);
}
</code>```

And this equivalent implementation:

```<code>float quad(float a, float b, float c)
{
    float discriminant = b*b - 4*a*c;
    float numerator = -b + sqrt(discriminant);
    float denominator = 2*a;
    float root = numerator/denominator;
    return root;
}
</code>```

The latter, while somewhat extreme, is a common style that makes stepping in the debugger easier, and also reduces the risk of mis-bracketing -- a common mistake. Compound expressions, while obviously a common feature in high-level languages, aren't ubiquitous, and they do often make bugs harder to find.

It's perfectly conceivable that a math library written by someone who prefers the former style might be 3KLOC, and a math library written by someone who prefers the latter might be 10KLOC -- and that the latter has less defects.

The research in "Making Software" was a fine start, but it left me wanting more. Is there anything published on this topic?

I don't think sheer LOC is a good estimate of the number of bugs in many (most) languages, even if it happens to be an effective measure in C. Constraints will often increase LOC while reducing defects. There are many kinds of constraints, including many which are language features not available in C:

Proper-English naming conventions

Unit tests/TDD

Runtime assertions

Type-safety

Pre/post-conditions

Invariants

Units of measure (arguably a type of type-safety)

But according to this study, TDD can nearly double LOC but reduce bugs. (I don't believe that this is a result of TDD so much as it is a result of unit testing, but that's another story.)

No, TDD is not a language feature, and no, I don't think unit test code should count towards LOC directly, but it is very much another form of constraint, and it shows that constraints, even if they increase code, work to reduce bugs.

Also, if for instance all languages supported units of measure except one language, all else being equal, that language would be more concise, and programs in that language would have more bugs, including ones that can crash spaceships.

Title: Research on software defects

Body:
Edit: I've rearranged my answer because I want to emphasize a different point.

Verbosity can sometimes help to make defects easier to detect and fix. Consider the quadratic formula (positive root only for simplicity's sake):

float quad(float a, float b, float c)
{
   return (-b + sqrt(b*b - 4*a*c)) / (2*a);
}

And this equivalent implementation:

float quad(float a, float b, float c)
{
    float discriminant = b*b - 4*a*c;
    float numerator = -b + sqrt(discriminant);
    float denominator = 2*a;
    float root = numerator/denominator;
    return root;
}

The latter, while somewhat extreme, is a common style that makes stepping in the debugger easier, and also reduces the risk of mis-bracketing -- a common mistake. Compound expressions, while obviously a common feature in high-level languages, aren't ubiquitous, and they do often make bugs harder to find.

It's perfectly conceivable that a math library written by someone who prefers the former style might be 3KLOC, and a math library written by someone who prefers the latter might be 10KLOC -- and that the latter has less defects.

The research in "Making Software" was a fine start, but it left me wanting more. Is there anything published on this topic?

I don't think sheer LOC is a good estimate of the number of bugs in many (most) languages, even if it happens to be an effective measure in C. Constraints will often increase LOC while reducing defects. There are many kinds of constraints, including many which are language features not available in C:

Proper-English naming conventions

Unit tests/TDD

Runtime assertions

Type-safety

Pre/post-conditions

Invariants

Units of measure (arguably a type of type-safety)

But according to this study, TDD can nearly double LOC but reduce bugs. (I don't believe that this is a result of TDD so much as it is a result of unit testing, but that's another story.)

No, TDD is not a language feature, and no, I don't think unit test code should count towards LOC directly, but it is very much another form of constraint, and it shows that constraints, even if they increase code, work to reduce bugs.

Also, if for instance all languages supported units of measure except one language, all else being equal, that language would be more concise, and programs in that language would have more bugs, including ones that can crash spaceships.


答:
Sounds like concept programming.

I'm not familiar with it, but XL is a language designed specifically for it.

XL features programmer-reconfigurable syntax and semantics. Compiler plug-ins can be used to add new features to the language.

Lisp and Forth also support concept programming, although less than XL. I suggest Lisp as it is very practical and effective. The most important thing is a clear and flexible syntax, not notation, which Lisp provides.

For instance, you would choose specific configurations like "Python's indexed blocks", "[a,b,c]" initializes arrays, "^" for exponentiation and others.

You may be interested in a language like Haskell which has a very flexible yet uniform syntax.


问:
Dual licensing with GPL library
I have a question concerning derivative works of GPL'ed software. Imagine the following situation: A company writes a software (A) using a library (B) which is released under the terms of the GPL. Now of course, software (A) has to be released under a compatible license to the GPL. But what about dual-licensing? If software (A) is released under two licenses, GPL and a commercial one, is this in violation with the terms of library (B)?

To rephrase the question, does the GPL force exclusivity for derivative works?

答:
If you created a derived work of a lib you received under the GPL then your lib is GPL.

If you paid them for a commercial license then the derived work is under whatever the terms are for that license

OwnerDisplayName: lucas clemente

Title: Dual licensing with GPL library


问:
Why does DirectX use a left-handed coordinate system?
I considered posting on Stack Overflow, but the question strikes me as being far too subjective since I can't think of a reasonable technical explanation for Microsoft's choice in this matter. But this question has bugged me for so long and the issue keeps coming up in one of my projects, and I have never actually seen an attempt at explaining this:

OpenGL uses a right-handed coordinate system, where the +Z part of the world coordinate system extends toward the viewer.

DirectX uses a left-handed system where the +Z part of the world coordinate extends into the screen, away from the viewer.

I never used the Glide API, so I don't know how it worked, but from what I can gather, it uses a left-handed system as well.

Is there a technical reason for this? And if not, is there some conceptual advantage to a particular handedness of a coordinate system? Why would one choose one over the other?

答:
There is no technical advantage to either handedness, it's completely arbitrary.  Both work fine as long as you're consistent.

Because of the advantages of consistency, ideally one should just "use what everybody else is using"—but that's quite difficult in many cases, because there's no overwhelmingly "preferred" convention in practice either: both handednesses are widely used.  At best, there's some consistency within certain communities (e.g. OpenGL).

So I think the basic answer to this question is:  They chose what they chose because it felt right (no doubt they had some previous experience with that handedness) and there was little reason not to.

In the end it makes little difference—anybody who seriously wants to exchange assets/code with other systems/communities is going to have to be prepared to deal with handedness conversion anyway, because it's a fact of life in 3D graphics.


问:
Conflicting Java Styles within a Team
I am part of a Java development team with a 6 week deadline. This necessitates writing a good deal of code very very quickly. However our development team has different styles of coding. Everything from name conventions to methods of abstraction differ among our team. Does anyone know of any documents that dictate "standards" for java?

To clarify, I was wondering if there was an organization that would dictate proper naming convention for variables and functions for example. This is paramount as with such a short deadline we can't afford to spend time trying to comprehend each others code.

答: There is such an organization: Sun/Oracle itself. The document is called Code Conventions for the Java Programming Language, and it describes most of the conventions you need. Just have everyone agree to read it and follow its recommendations.</p>

Title: Conflicting Java Styles within a Team


答:
I'm really tagging on to Andres's answer, and focusing on the aspect uniformly formatting the java code.

If you are using Eclipse, you can set its Java formatter to automatically format to the Java standard.  The Eclipse formatter also has other helpful settings, such as the characters per line (i.e. how many characters per line before it breaks to a new line), and many others.  Standardizing characters per line makes it easier to diff code written by different developers without having a lot of differences just from spacing and line breaks.

Finally, with Eclipse, after you have set all the settings you want, then export your formatter as a file which can be imported by every member of the team. So if you are using Eclipse, I highly recommend fully exploring all the options it will auto-format and code edit for you, and then sharing the settings with the entire team.

I would assume the other major java IDEs (IntelliJ and Netbeans) have a similar feature for exporting the format settings.

Title: Conflicting Java Styles within a Team

Body:
I am part of a Java development team with a 6 week deadline. This necessitates writing a good deal of code very very quickly. However our development team has different styles of coding. Everything from name conventions to methods of abstraction differ among our team. Does anyone know of any documents that dictate "standards" for java?

To clarify, I was wondering if there was an organization that would dictate proper naming convention for variables and functions for example. This is paramount as with such a short deadline we can't afford to spend time trying to comprehend each others code.


问:
System Decoupled in the Wrong Places: Meta-Problem?
At a meta level, I often find that when I grow a codebase organically, parts of the system that I eventually find need to know about each other (at least through some interface) have been mercilessly decoupled.  This often occurs in research prototype code, where one tends to frequently think of tweaks and small improvements that weren't planned for in the original codebase.

Usually, some setting or piece of data needs to be plumbed through about 15 zillion layers of function calls in ways that I never anticipated when I designed the code.  This leads to a very ugly dilemma:

Use an ugly hack.  This can be yet another global variable, bolting the data onto a class that it clearly doesn't belong in, putting a bunch of print statements in the middle of code that previously had nothing to do with I/O logic, doing a seemingly straightforward task in a very roundabout way to make it fit in my original codebase, etc.

Shotgun surgery refactoring.  This almost never gets done in practice because the code will likely have to be rewritten anyhow if it is to become production quality, was hard to get working the first time, is hard to test, or I just plain have higher priorities than writing clean, maintainable code when either I have a deadline or I know it's just a prototype for now.  Furthermore, the next tweak may break whatever nice abstractions I come up with.

Are there any good meta-tips or design principles that will help me avoid situations like this in the first place?  I am NOT looking for answers that simply recommend refactoring after the fact, as a nightmarish shotgun surgery refactoring session is exactly the kind of thing I'm trying to avoid.

答:
Three things that I find useful, but some people dislike:

Consider early prototype code - if you are doing something very different than what you have done in the past the first go of it is likely to teach you that you should have done it differently early on - work out your ideas then start fresh

Minimize early decoupling - to me it is far easier to refactor something out of a coupled scenario once I have good reason than to juggle the bits across an arbitrary early decoupling border.

Consider having fewer tiers or allowing functions to skip tiers.  In some projects the latter can approach a necessity at times.

ContentLicense: CC BY-SA 2.5


答:
Now of course, software (A) has to be released under a compatible
  license to the GPL. But what about dual-licensing?

Software A can be released under any number of licenses as long as they are all compatible GPL.

If software (A) is released under two licenses, GPL and a commercial
  one, is this in violation with the terms of library (B)?

No. It seems unlikely (though not impossible) to create a commercial license which is also compatible with GPL.

Understand that you may charge (on any account) while distributing the software under GPL is not an issue. But wrapping it under close source will remain definitely in-compatible to GPL.

Title: Dual licensing with GPL library

Body:
I have a question concerning derivative works of GPL'ed software. Imagine the following situation: A company writes a software (A) using a library (B) which is released under the terms of the GPL. Now of course, software (A) has to be released under a compatible license to the GPL. But what about dual-licensing? If software (A) is released under two licenses, GPL and a commercial one, is this in violation with the terms of library (B)?

To rephrase the question, does the GPL force exclusivity for derivative works?


问:
Do coding puzzles make good interview questions
I am interviewing candidates for Java programmer positions.

My colleague insists in filling more than half of the interview with java coding puzzles.His view is that, if candidates are able to navigate through the loops, then they must be good.

One such example of coding puzzle is

```<code>        i=0;
        for( i=1 ; i< 10 ;i++)
        {
                if(i%3 ==0) i++; break;
                if(i%2 ==0) i++;

         }
          print(i);
</code>```

Follow up: what happens if break is removed ?

答: If you're looking to hire someone good at puzzles then yes, it is a good approach. If you are looking to hire a good programmer you might want to take the approach laid out by Joel.</p>


答:
I haven't actually used it per se, but if I recall correctly, TXL is specifically designed for translating source code.  As such you should be able to use it to specify how to translate from your language and/or language extensions to any target real language.

It does appear to have a grammar available for Javascript.  But, not having used it before, I'm not sure exactly how that would help you.


问:
How to stop dwelling on problems rather than tasks?
I can't say I am a good programmer but I've been earning money for programming last decades. I've thought I was born for programming and people said I was very good at it - at some point.

But after 10 years of programming, I feel my programming efficiency is not as good as others. Of course, CS education is way better now and many young programmers are smarter than me.

But one of my problem is that when I am executing a task, I tend to dwell on specific problems I am facing with the task rather than focusing on completion of the task. I understand to keep thinking about it does not solve the problem. But I habitually do that and easily become exhausted. I hope I am not the only one feeling in this way.

Did you feel the same feeling? If so, how did you get rid of this terrible habit?

答:
One word; done. Focus on it, strive towards it, understand that it is what matters.

Preparing for the ifs will generally equate to unneeded perceived value that allows the programmer to feel better about a situation but it unfortunately in no way delivers additional value.

Always remember that done equates to immediate value and focusing on anything less than moving towards done is a waste of time, effort, and energy.


答:
What kind of developer are you looking for:

One who can take a set of requirements written as a riddle, and create code that solves the riddle?

One who can debug code that looks like a riddle?
or

One who can talk to the users, and the ones who write the requirements; then create code that solves the problem, and meets the requirements?

I have never been asked to solve a riddle, or to write code as part of an interview. Most of the time the job has been as a solo programmer; other times it has been to take on a technology that the company is unfamiliar with; either way there is no easy way to construct and evaluate a riddle.

Title: Do coding puzzles make good interview questions

Body:
I am interviewing candidates for Java programmer positions.

My colleague insists in filling more than half of the interview with java coding puzzles.His view is that, if candidates are able to navigate through the loops, then they must be good.

One such example of coding puzzle is

```<code>        i=0;
        for( i=1 ; i< 10 ;i++)
        {
                if(i%3 ==0) i++; break;
                if(i%2 ==0) i++;

         }
          print(i);
</code>```

Follow up: what happens if break is removed ?


问:
HTML 5 Double-Helix/DNA
What would be the most cross browser friendly (IE9, Chrome, FF, Safari, Opera) way to code an animated, interactive double-helix?

HTML 5/JavaScript is fine.  Flash or Java is not.

I am unsure if canvas or svg or pure css should be considered as graphics aren't typically my thing.  In fact, I really don't know where to start here, so I probably just need a nudge in the right direction.

Any advice is appreciated!

答: If you are doing 3D, you can use HTML5 Canvas and WebGL to generate such a rendering and so forth. Interaction with the window would likely accomplished through Javascript though HTML5 may be up to that task as well.</p>

Title: HTML 5 Double-Helix/DNA


问:
Who does test-driven development?
I've been working in the enterprise space for the past 4½ years and have noticed that generally speaking, enterprises are not conducive environments for the test-first style of development. Projects are usually fixed-cost, fixed-timeline and waterfall style. Any unit testing, if done at all, usually comes after development in the QA phase and done by another team.

Prior to working for an enterprise, I consulted for many small to medium sized companies, and none of them were willing to pay for a test-first style of development project. They usually wanted development started immediately, or after a short design stint: i.e., something more akin to Agile, though some clients wanted everything mapped out similar to waterfall.

With what types of shops, companies, and clients does test-driven development work
best? What types of projects tend to be conducive to TDD?

答:
I do it.  The progress of our user stories is tracked on a Kanban board, which has a "Has a Test?" column to the left (upstream) of Development.

This somewhat unusual layout makes one policy explicit: a failing automated acceptance test (usually, a few of them) must exist.  It must be traceable to a customer requirement.  The acceptance tests arise from conditions of satisfaction, which result from conversations that begin with a story card.  I facilitate regular workshops where we brainstorm requirements, identify gaps, and figure out the key acceptance tests that ensure user value is delivered when they pass (the definition of done).  It's a collaborative activity involving programmers, business analysts and sometimes testers.

The acceptance-testing feedback loop is kind of long: it may take several days to complete the story.  The development has its own, shorter TDD feedback loops.

"[...no test-first style...]  More akin to Agile...."

This is a complete misrepresentation of Agile.  Definition of done is a key component of Agile and one of the pillars it rests upon is the automated acceptance testing (what I described above is one way to do it.)  If extreme programming (XP) is used as an Agile implementation method, then ATDD/BDD and TDD are prescribed.

Title: Who does test-driven development?


答:
Scala is often used in this way to create DSLs, Domain Specific Languages.

Mainly this is because Scala has no operators, and the Scala method calling syntax can be abbreviated. For instance:

5 is an Integer object. To calculate 5 plus 7 you could write

val ans = 5.add(7) except that the addition method is actually named "+" so you would write:

val ans = 5.+(7) but in Scala, you do not need to include the "." in method calls or the parentheses "()" around arguments so to call the + method on the object 5, you would write

val ans = 5 + 7 which works perfectly because Scala has no operators to interfere with your clever method naming scheme. Now extend that idea to your own classes and objects, including the fact that you can "override" methods like + as well as create your own methods named >>> or ::! or @*@ or just plain text names like fancify.


答:
Many folks have difficulty focusing on tasks, and I am one also.  Unfortunately, this question may not receive a good answer on a venue such as this, where I suspect most people reading this cannot really understand.  Furthermore, this seems to need expertise in psychology, and I doubt that very many people here have such expertise.

That said, I'd like to point toward the work of PJ Eby, a programmer turned "Mind Hacker".  He says that people are "naturally successful" or "naturally struggling".  His goal is to help naturally struggling people become naturally successful.  Some of Eby's work can be found at:

http://dirtsimple.org/

http://thinkingthingsdone.com/

Google for other places he posts, including Twitter.  Unfortunately, it seems that PJ isn't updating these sites much anymore; presumably he's busy helping his paying customers.  However, you can learn a bit from the writings that remain on line.  (Note:  I'm not PJ Eby, nor do I know him personally or derive any income from posting this.  However, I post anonymously due to my earlier statement about having difficulty focusing myself and not wanting to leave such breadcrumbs for possible future employers to follow.)

Finally, if reading and self work doesn't lead to improvement, seeking professional help, whether from a personal coach or psychologist, might be helpful here.

Title: How to stop dwelling on problems rather than tasks?

Body:
I can't say I am a good programmer but I've been earning money for programming last decades. I've thought I was born for programming and people said I was very good at it - at some point.

But after 10 years of programming, I feel my programming efficiency is not as good as others. Of course, CS education is way better now and many young programmers are smarter than me.

But one of my problem is that when I am executing a task, I tend to dwell on specific problems I am facing with the task rather than focusing on completion of the task. I understand to keep thinking about it does not solve the problem. But I habitually do that and easily become exhausted. I hope I am not the only one feeling in this way.

Did you feel the same feeling? If so, how did you get rid of this terrible habit?


问:
How can a large, Fortran-based number crunching codebase be modernized?
A friend in academia asked me for advice (I'm a C# business application developer).

He has a legacy codebase which he wrote in Fortran in the medical imaging field. It does a huge amount of number crunching using vectors. He uses a cluster (30ish cores) and has now gone towards a single workstation with 500ish GPUS in it.

However where to go next with the codebase so:

Other people can maintain it over next 10 year cycle

Get faster at tweaking the software

Can run on different infrastructures without recompiles

After some research from me (this is a super interesting area) some options are:

Use Python and CUDA from Nvidia

Rewrite in a functional language. For example, F# or Haskell

Go cloud based and use something like Hadoop and Java

Learn C

What has been your experience with this? What should my friend be looking at to modernize his codebase?

UPDATE: Thanks @Mark and everyone who has answered. The reasons my friend is asking this question is that it's a perfect time in the projects lifecycle to do a review.  Bringing research assistants up to speed in Fortran takes time (I like C#, and especially the tooling and can't imagine going back to older languages!!)

I liked the suggestion of keeping the pure number crunching in Fortran, but wrapping it in something newer. Perhaps Python as that seems to be getting a stronghold in academia as a general-purpose programming language that is fairly easy to pick up.

See Medical Imaging and a guy who has written a Fortran wrapper for CUDA, Can I legally publish my Fortran 90 wrappers to Nvidias' CUFFT library (from the CUDA SDK)?.

答:
Python is indeed gaining a lot of traction in the scientific computing community (for a somewhat outdated view, see volume 9 number 3 of CiSE).  I think a Python/Fortran hybrid is an excellent way to go.  In order to take advantage of all those GPUs, you could use PyCUDA or PyOpenCL.

I'm a mathematician who analyzes and writes numerical solvers for partial differential equations.  I was recently in a similar situation to your friend's; the Fortran 77 code in question is the well known Clawpack software.  We rewrote the top level code (all the parts that don't need to be fast) in Python and used f2py to automatically wrap the low-level parts.

The really powerful result of this is that we were then able to almost trivially connect the hybrid Python/Fortran code (dubbed PyClaw) with the parallel library PETSc, creating for the first time a scalable parallel version of Clawpack that performs well on 65K cores.  All of the parallel code that we had to write is contained in less than 300 lines of Python.  We're now solving problems that couldn't possibly have been tackled just with the legacy code.  Just as importantly, it's now much easier for new users to pick up the code, since Python is such a friendly language and almost everything can be modified at run-time rather than compile-time.

If you want to see more details of our approach and results, we have a paper on the arXiv.

Apologies for the self-advertisement, but it seemed that my personal experience would be relevant here.  If you would like to hear many more ideas, you could post this also on the new http://scicomp.stackexchange.com.


问:
Are there any formalized/mathematical theories of software testing?
Googling "software testing theory" only seems to give theories in the soft sense of the word; I have not been able to find anything that would classify as a theory in the mathematical, information theoretical or some other scientific field's sense.

What I'm looking for is something that formalizes what testing is, the notions used, what a test case is, the feasibility of testing something, the practicality of testing something, the extent to which something should be tested, formal definition/explanation of code coverage, etc.

UPDATE: Also, I'm not sure, intuitively, about the connection between formal verification and what I asked, but there's clearly some sort of connection.

答:
One mathematically-based approach is all pairs testing.  The idea is that most bugs are activated by a single configuration option choice, and most of the remainder are activated by a certain pair of options taken simultaneously.  Thus most can be caught by testing "all pairs".  A mathematical explanation (with generalizations) is here:

The AETG system: an approach to testing based on combinatorial design

(there are many more such references)


答:
It would depend on how complicated the animation is.

If your cross browser compatibility requirement includes IE, WebGL is not an option. Your best bet is to use Canvas & Javascript.

Title: HTML 5 Double-Helix/DNA

Body:
What would be the most cross browser friendly (IE9, Chrome, FF, Safari, Opera) way to code an animated, interactive double-helix?

HTML 5/JavaScript is fine.  Flash or Java is not.

I am unsure if canvas or svg or pure css should be considered as graphics aren't typically my thing.  In fact, I really don't know where to start here, so I probably just need a nudge in the right direction.

Any advice is appreciated!


答:
I am currently in the process of updating an old FORTRAN95 codebase to be used on modern industry environments as the previous version will only run on Windows2000 machines at the latest. The FORTRAN codebase itself performs a large amount of number crunching involved with irrigation simulations.

So what I am doing is instead of re-writing the FORTRAN in a more modern language I am simply using a commercial compiler called Silverfrost FTN95 to compile the FORTRAN codebase to a .Net 4.0 library which I am using as the backend of a WPF application. This way I do not run the risk of bringing knew bugs into the simulation code and I am modernizing it by moving the codebase to the .Net 4.0 framework so it will run on more modern environents.

But depending on how big your simulation is you might want to just simply re-write the whole thing in a more modern language such as C#, i myself am planning to do this once I have a running version of the simulation to compare output with.

Hope my expieriance helps,
Thanks,
Alex.

Title: How can a large, Fortran-based number crunching codebase be modernized?

Body:
A friend in academia asked me for advice (I'm a C# business application developer).

He has a legacy codebase which he wrote in Fortran in the medical imaging field. It does a huge amount of number crunching using vectors. He uses a cluster (30ish cores) and has now gone towards a single workstation with 500ish GPUS in it.

However where to go next with the codebase so:

Other people can maintain it over next 10 year cycle

Get faster at tweaking the software

Can run on different infrastructures without recompiles

After some research from me (this is a super interesting area) some options are:

Use Python and CUDA from Nvidia

Rewrite in a functional language. For example, F# or Haskell

Go cloud based and use something like Hadoop and Java

Learn C

What has been your experience with this? What should my friend be looking at to modernize his codebase?

UPDATE: Thanks @Mark and everyone who has answered. The reasons my friend is asking this question is that it's a perfect time in the projects lifecycle to do a review.  Bringing research assistants up to speed in Fortran takes time (I like C#, and especially the tooling and can't imagine going back to older languages!!)

I liked the suggestion of keeping the pure number crunching in Fortran, but wrapping it in something newer. Perhaps Python as that seems to be getting a stronghold in academia as a general-purpose programming language that is fairly easy to pick up.

See Medical Imaging and a guy who has written a Fortran wrapper for CUDA, Can I legally publish my Fortran 90 wrappers to Nvidias' CUFFT library (from the CUDA SDK)?.


问:
Why do so many programmers absolutely hate object prevalence layers?
Prevalence is a simple technique to provide ACID properties to an in-memory object model based on binary serialization and write-ahead logging.  It works like this:

Start with a snapshot.  Serialize the object model and write it to a file.

Create a journal file.  For every call into the object model, serialize the call and its arguments.

When the journal gets too big, you're shutting down, or it's otherwise convenient, perform a checkpoint: write a new snapshot and truncate the journal.

To roll back or recover from a crash or power hit, load the last snapshot and re-execute all the calls recorded in the journal.

The precautions needed to make this work are:

Don't let mutable object references escape or enter the prevalence layer.  You need some sort of proxy or OID scheme, as if you were doing RPC.  (This is such a common newbie mistake it's been nicknamed the 'baptism problem'.)

All the logic reachable from a call must be completely deterministic, and must not perform business-logic-meaningful I/O or OS calls.  Writing to a diagnostic log is probably OK, but getting the system time or launching an asynchronous delegate is generally not.  This is so that the journal replays identically even if it's restored on a different machine or at a different time.  (Most prevalence code provides an alternate time call to get the transaction timestamp.)

Writer concurrency introduces ambiguity in journal interpretation, so it is prohibited.

Is it because ...

people developed a bad taste for them after trying to use one on a project that wasn't well suited* to it?

Klaus Wuestefeld's strident advocacy turned people off?

people who like the imperative programming model dislike separating I/O from calculation, preferring instead to interleave computation with I/O and threading calls?

prevalence layers are so conceptually simple and so intimately bound to the characteristics of the framework they inhabit that they're usually custom-rolled for the project, which makes them too alien/nonstandard/risky?

it's just too hard to keep straight what you have to be careful not to do?

newbies' heads just seem to explode when faced with something that isn't the same kind of two-tier database-driven app they learned to write in school? ;)

*The entire data set fits in RAM, you don't need writer concurrency, and you don't need to do ad-hoc queries, reporting, or export to a data warehouse.  With apologies to SQLite, prevalence is an improvement on save-files, not a replacement for Oracle.

答:
I think some of the problem is that they have a VERY specific use case (your not suited reason).  I have built and worked on systems that use this approach and when you have a problem that is actually this problem it can be a wonderful solution.

Another part is that it looks a whole lot like some of the more painful bits of custom data storage you used to find a lot of 10+ years ago and has some of the same pitfalls (think batch updated btreive for example) which brings in your "too custom" point, but also makes it difficult to find off the shelf parts that work politely with it.

The last part is that they can be damn difficult to query against in many cases and folks in general are pretty accustom to being able to get their answers right now.


答:
Of course you can't ask only puzzles, and "gotchas" that revolve around language trivia are not very useful. But some kind of programming exercise is a virtual necessity if you use a staffing agency or recruiters, or if you keep hiring people who are good at faking their level of competence.

Asking the right kinds of questions can help gauge how familiar programmers are with common algorithms and how to apply them to problems. It can also tell you whether they look for multiple approaches and choose the best one, or just pick one that they know will work. In the latter case they may be aware that there is a better way but would need to look it up to get it right, which is fair enough -- working, if less than maximally efficient, code is better than code that doesn't work, and just knowing there's a better way is more than half the battle.

An example of a decent place to start is a problem I had in a programming competition back in 1985-ish, when I was a young Applesoft BASIC hacker. The problem was to print all perfect squares between 1 and 1000. Of course, there are two approaches to solving this:

Iterate through all the integers between 1 and 1000. Take the square root of each and see if this is equal to the truncated-to-integer result of the same calculation. (No modulo operator in Applesoft BASIC!) If so, print the number.

Iterate through all the integers between 1 and SQR(1000). Print the square of each.

Obviously the second is far more efficient than the first, and as a bonus it will print all the right answers, while the first, due to rounding errors in the Apple's SQR() implementation, actually missed one or two. However, most of the solutions turned in used approach #1. (These were high school students, after all, and the problem was posed in such a way that the reader would gravitate toward the first option.)

A discussion around a modern-day problem of this sort could reveal whether a candidate is a aware that there are two approaches, can tell which is better, and understands the limitations of binary floating-point math. In fact, I would say that someone who couldn't tell you why the second approach is better would be a poor candidate -- basically on the level of a high school student from 1985. This problem is only slightly more complicated than "fizzbuzz" -- and much less complicated than anything they're likely to actually be working on!

My point is to know what you expect to learn from such a question, and to not set them as pass/fail questions but to use them as jumping-off points for probing the limits of a candidate's knowledge. You can ask a series of increasingly difficult questions and see where they begin to have trouble.

You might ask, how do I tell from a series of programming exercises whether someone is smart enough to work on my team? And the answer is: you don't, you rank them in order of smartness and hire the smartest you can afford, assuming he or she is smart enough.

ContentLicense: CC BY-SA 4.0


答: Personally I find TDD helps with this: The test first approach puts emphasis on the usage and reason d'être for the production code, and doesn't let you stray away from the task at hand. </p>


答:
As mentioned by others here, you can search online for 1 of the few popular 'style guides' for Java and persuade everyone in the team to stick to them. Some code checking tools in your favourite IDE might help to remind you when you aren't doing so.

However, sometimes politics is involved. I'm once in a situation before where the most senior developer in the team continues to do it his way even after someone mentioned a need to standardise. In such a situation, it maybe be better to observe his code style and follow him since he probably has the most knowledge about the code base and requirements and you may not want to waste time stepping on his toes even though he is being difficult. Which is what the rest of us did in that particular situation and I reluctantly follows.

So it's important to consider your situation as well.

Title: Conflicting Java Styles within a Team


问:
What do I need to consider when using code under the Apache License in an application submitted to Mac App Store?
First off, I am new to licenses and app stores.

There is an example app on a framework that has a Class file with much of the functionality I'll need for my own app. It's less than 1000 lines of code and distributed under the Apache License 2.0.

As far as I know I can use/modify the code and just acknowledge the developer and include the license, but does this mean my whole project will be distributed under the Apache License 2.0 or just does it just apply to that source file?

Once my project is done, would I be able to publish my app in the Mac App Store? Would I be able to sell it there?

The file is from an example project that pretty much demonstrates all which is possible in the framework, and using it in my project would save me a ton of time. However, if this is not possible I guess I'll just have to code it myself.

答:
but does this mean my WHOLE project will be distributed under the
  Apache License 2.0 or just does it just apply to that source file?

No. I think you can distribute your project in any form you like. Even if it is not open source that is okay - as long as you are giving due credit to the author who's class you are using.

I don't know if mac store would have other requirement -but it is perfectly legal on your part to publish your work with just the acknowledgement.


答:
I wouldn't call this a classic puzzle, as discussed e.g. in this question. I would call it a code reading exercise. Almost everyone agrees that puzzles only measure if a candidate has seen this kind of puzzle before. But code reading exercises can make sense, IMHO, developers spend a large amount of their time reading code, after all.

But personally, I would use code that's a bit more realistic. For example, I have a function somewhere in my codebase that breadth-first traverses a tree. If you strip the name, a reasonably experienced programmer should still be able to figure out what said function does. And answer questions like "what will happen if that data structure is a graph with cycles instead of a tree?" or "what would you have to change to get depth-first search?".


答:
The Sun Java CC mentioned above not only is 13 years old and some of its rules are outdated (like 80 characters per line), but also it does not define naming conventions, except for the most general ones (camel casing for classes, block capitals for static final variables and the like).

You need to define your own standards for different types of classes, like DAOs, EJBs, entities, whatever you use. The Sun Java CC is like an abstract base class meant for extending :)

Title: Conflicting Java Styles within a Team


答:
The key to doing TDD is to just do it as part of writing your code, and if necessary, you do not tell anyone you're doing it.  It's not necessary to explain everything you're doing.  Your end result is working code.

If you explain "I am writing tests," then The Powers That Be can say "Oh, we can eliminate that!"  But if you tell no one, then you still have the tests as residue of the coding process.

Programming is more than typing in working statements into an editor.  If people can't handle that, then shield them from this truth until they are ready to handle it.  "Ready to handle it" in this case means when you have a completed project or two, done on time with solid, reliable code, and oh yeah, look, you have unit tests for it, too.

Title: Who does test-driven development?

Body:
I've been working in the enterprise space for the past 4½ years and have noticed that generally speaking, enterprises are not conducive environments for the test-first style of development. Projects are usually fixed-cost, fixed-timeline and waterfall style. Any unit testing, if done at all, usually comes after development in the QA phase and done by another team.

Prior to working for an enterprise, I consulted for many small to medium sized companies, and none of them were willing to pay for a test-first style of development project. They usually wanted development started immediately, or after a short design stint: i.e., something more akin to Agile, though some clients wanted everything mapped out similar to waterfall.

With what types of shops, companies, and clients does test-driven development work
best? What types of projects tend to be conducive to TDD?


问:
Are enforced Professional Development Plans useful?
Many companies, especially larger ones have mandatory professional development plans for their employees. Employees and managers set out a personalized professional development plan and follow up on the progress every so often.

As a developer, do you find such PDPs useful, do you follow through with your commitments?

As a manager, do you think such PDPs bring value to the company and improve the overall quality of the employees?

It seems that good developers will continue to educate themselves and strive to be better regardless of companies' procedures while bad ones won't.

Are there benefits of having PDPs or is it just something managers feel they need to do?

答:
I think it's mostly catering for the not-so-good developers (and other staff). Interested, passionate people will generally take care of themselves. I've found "personal development" is often a euphemism for "moving to management", which is of course the only career goal any of us should have....

That said, it's good to talk about what you want to achieve so that opportunities are made available to you. It can also help narrowly-focused tech heads to take a step back and think beyond the current project/technology. If the only way an organisation can get those talks to happen is via enforced PDPs, then I guess they're useful.


问:
After writing code, why do I feel that "I would have written better" after some time?
I have been working on my hobby project in C++ for more than 2 years. Whenever I write a module/function, I code it with lot of thinking. Now see the problem,

```<code>do {
  --> write the code in module 'X' and test it
  --> ... forget for sometime ...
  --> revisit the same piece of code (due to some requirement)
  --> feel that "This isn't written nicely; could have been better"
} while(true);
</code>```

Here 'X' is any module (be it small/large/medium). I am observing that, this happens no matter how much effort I put while coding. So mostly, I refrain myself from seeing a working code. :)

Is this a common feeling for many people ? Is this language specific phenomena ? (Because in C++ one can write the same thing in different ways).

What should I do, if I get this re-factoring feeling for a real world production code, where changing the working code will not earn me much accolades but rather it may invite troubles if it fails.

答:
This phenomenon is very common and not specific to programmers. Whenever you perform an intellectual task, you will notice dozens of places where you could have improved -- after you got some distance. Ask any wise (wo-)man who ever wrote a thesis, and they'll tell you one thing: "Don't look at it. You will find an error on the first glance."

There are basically two things to avoid the refactoring loop:

While writing and designing, try to get the distant perspective as early as possible. Have a colleague look at your design/code. Look again after a weekend. Look at it when drunk or high (but beware: don't change anything until sober).

Live with imperfection. If it is merely not pretty, but works well (read: does a good job at fulfilling all requirements, including extensibility and readability), let it stand and be content with the good work you did, not striving for the perfect work.


答: Every module/function is born and evolves in a world of priorities. Once it suffices to serve the outer worlds goals it is often left to stagnate. Its all ultimately scaffolding in service to the higher purpose. Yes, we need to be obsessive about code, and yes that can cause us to stagnate too. Maybe it would be a good move for you to shift your focus away from the code itself a bit, and ponder more on the processes that go on inside you, the producer of the code.</p>

Title: After writing code, why do I feel that "I would have written better" after some time?

Body:
I have been working on my hobby project in C++ for more than 2 years. Whenever I write a module/function, I code it with lot of thinking. Now see the problem,

```<code>do {
  --> write the code in module 'X' and test it
  --> ... forget for sometime ...
  --> revisit the same piece of code (due to some requirement)
  --> feel that "This isn't written nicely; could have been better"
} while(true);
</code>```

Here 'X' is any module (be it small/large/medium). I am observing that, this happens no matter how much effort I put while coding. So mostly, I refrain myself from seeing a working code. :)

Is this a common feeling for many people ? Is this language specific phenomena ? (Because in C++ one can write the same thing in different ways).

What should I do, if I get this re-factoring feeling for a real world production code, where changing the working code will not earn me much accolades but rather it may invite troubles if it fails.


问:
What constitutes "distributing" for LGPL v3
I am considering basing some new software on a LGPL web application. I want to utilize this new software for creating one website for my employer, and we do not intend to sell or distribute the software itself to anybody. Does publishing web pages from LGPL software constitute "distributing" in the license, so I would have to publish our changes to the LGPL code as well?

I understand that none of you are lawyers so IANAL is implied. I also understand that I could contact the developers of the LGPL software and ask for a different license.

答:
No.

"Distribution" always implies that the source is in usable form. In fact I was searching for something that explains this clearly, and the Javascript Trap article gave an excellent pointer. Even from very Richard Stallman's point of view, just because javascript gets downloaded in your browser doesn't mean it is open - it is still close. Now he goes on ranting about close web applications, indirectly providing an argument that web site downloading doesn't qualify as distribution if it is within a context of application.

Another good example is GitHub, which obviously uses git (pure GPL). But it is using git! Even if they have modified git to fit their purpose, it is not necessary to publish it back.

Given the above arguments, it is very clear that almost all of SaaS, and providing hosted services is using than distributing the application.

On the contrary if you are creating a package which allows people to create websites. that clearly falls under distribution - but this is not the case with you.

So I think you are safe. However, it is a very strong argument to defend on court. Because the very word distribution has different meaning in laws in different locales. Getting permission from the original author is your best bet.


答:
This [different styles of coding] is paramount as with such a short deadline we can't afford to spend time trying to comprehend each others code.

Actually.  It's not paramount.

After 30 years as a consultant, I've read a lot of code from a lot of customers.  It's important to note that every customer (and often within a customer's organization) there are varying styles.

After reading so many styles, I've learned this.

Style Doesn't Matter

Please focus on writing code that always works, and writing unit tests that prove that it always works.

After you've shipped working code, you can dress it up if you've run out of bugs to fix and enhancements to install.

Title: Conflicting Java Styles within a Team


答:
Is this a common feeling for many people? Is this language specific phenomena?

That means you are expanding your knowledge and views.

If you have no tasks of higher priority, you should always go back and improve your code.


答:
It sounds like you are experiencing a degree of the "all for naught" fear, the fear of being torpedoed. I don't mean to imply this is an aberration, it is build into us by evolution and it serves its purposes -- after all, it is central to risk mitigation. You try to tackle the biggest threat to success first.

But the danger is that it can be paralyzing. You need to manage your morale and confidence by sprinkling in tasks you can complete.

For instance, if I am writing a function or module where I don't really know how to go about what I am about to do, I don't fret about the best way or the big picture -- I let the problem tell me what its about in little steps. So I just keep coding until I have enough framework to detect how it REALLY needs to be, then start refactoring and implementing that.

You just allow yourself to think-in-code... you are sketching out things and you have to have faith that all the messiness will eventually align and collapse into the formalized solution.


问:
Is there a personalizable programming language you can use to convert to others?
Is there a programming language in which you can set your own syntax configurations and it would convert the code to a language you choose?

For instance, you would choose specific configurations like "Python's indexed blocks", [a,b,c] initializes arrays, ^ for exponentiation and others. A script would convert it to your choice language's equivalent.

答: There is a nice preprocessor out there called PPWizard, quite powerful. Once you learned its syntax you could create macro defs to target different languages -- not that it would be foolproof or fun for that matter, but it is a useful tool.</p>


问:
Is Usage Tracking esoteric or state of the art?
There are several products for tracking the usage of your application. I know at least 10 offers. They tell you which features were used more often than others. Thus, you can identify features that may not make into new versions.

While with Google Analytics, or similar tools, this a standard tool for the web at the "page-level". I just wonder who is already using this analysis for desktop applications?

Big companies like Microsoft of course do it, but do ISVs and small vendors (perhaps < 50 employees) use such tools?

I currently don't know anybody, so I'm really curious about it: Is Usage Tracking esoteric or state of the art?

答:
It is not state of the art, since it is seldom needed:

If you have developed a certain functionality, why should you remove it, even if it is rarely used? Maybe your menus are too big, making it hard to find the often used things? But then you have several opportunities, like enabling some options only via a config file, let the user switch to an expert mode, where he can unhide some options.

Sometimes, the options might increase the complexity, so that you have to maintain many things, and with 4 options of type A, and 3 options of type B, you end in 3*4 functions to write, while 3*3 or 3*2 functions would be much less code.

But you have to be aware, that many functions might be used rarely, but can be important nonetheless. Maybe you have 100 users, which all use 90 functions. And every user uses one more function, for which he is the only user. But removing this function might render the whole program useless.

If your concern isn't so much the cost of development, or the user experience, but the size your program occupies in RAM, you might use plugins and lazy initialization to reduce it.

If big parts can be used independently of others, you could extract the rarely used parts, and provide 2 or more programs, each one smaller as the combination of both.


答:
It depends what you use the puzzle for.

If you use it as a starting point, to see how a candidate approaches a problem and to fire up a discussion about programming techniques, style, and philosophy, then good.

If you use it as a black/white test, where the fastest candidate to solve the puzzle gets the job, then you're doing it wrong.

You want to evalute a candidate on a wide range of aspects: communication, out-of-the-box thinking, code comprehension, problem solving skills, general attitude towards coding, social skills, strengths and weaknesses, and whether they're a good fit for the team. Reducing all these to a single boolean "solved the puzzle" is never good enough.


问:
Should one use pseudocode before actual coding?
Pseudocode helps us understand tasks in a language-agnostic manner. Is it best practice or suggested approach to have pseudocode creation as part of the development lifecycle? For instance:

Identify and split the coding tasks

Write pseudocode

Get it approved [by PL or TL]

Start Coding based on Pseudocode

Is this a suggested approach? Is it practiced in the industry?

答:
For myself and the people I have worked with for the last few years pseudocode has pretty much turned into not entirely perfect real code.  unless you work with many languages at the same time, most people seem to start thinking in the general pattern of their main language.  I have worked in .net shops for a while so most people's whiteboard scribbles around the office tend to look like vb or c# with some of the punctuation missing.

The exercise is still valuable when debating options and such, but the language agnostic bit tends to drift away as you spend more time with a few languages.


答:
Not saying you should use it as it is still mostly experimental, but one interesting recent programming paradigm is Language Oriented Programming (LOP).

The concept of Language Oriented Programming takes the approach to
  capture requirements in the user's terms, and then to try to create an
  implementation language as isomorphic as possible to the user's
  descriptions, so that the mapping between requirements and
  implementation is as direct as possible.

Sergey Dmitriev explains it in more detail.

That's the ideology of it, but practically it boils down that it supports the behavior you are asking for. You can:

Extend an existing language.

Compose different languages.

Use an existing 'transformation language' in order to convert your newly defined keywords to a base language.

The most active programming environment I know of following this paradigm is the free Meta Programming System (MPS) by JetBrains.

It's actually starting to be used in commercial software as well, so perhaps it's starting to get out of it's 'experimental' phase:

Realaxy is an actionscript editor built entirely on top of MPS. Using the power of LOP they were able to implement e.g. closures for AS3.

mbeddr C is an extensible C language based on MPS.


答:
Usage tracking is far more popular on web applications for a variety of reasons:

Web applications share a common client side, mostly made out of standard technologies (HTML, CSS, Javascript). It is a lot easier to build analysis tools, when what you are analyzing is pretty much standardized and publicly available.

Evolutionary prototyping is a fairly standard approach in web development, and usage tracking is especially helpful.

Feature bloat hurts more on web applications. A feature that requires a 40K Javascript library hurts every user's experience, and it's fairly important to know how many of your users actually use it.

That said, usage tracking is or should be important to every application, but is not as easy to implement, or valuable, on desktop applications. An example of traditional usage tracking is Firefox's TestPilot add on.

What's a bit more interesting though, is an emerging set of technologies that are grouped under the buzzword Runtime Intelligence:

The term runtime intelligence (RI) refers to technologies, managed services and practices for the collection, integration, analysis, and presentation of application usage levels, patterns and practices. RI is a discipline within both business intelligence (BI) and software development lifecycle (SDLC) management that focuses on precision method-level monitoring within applications and macro-level monitoring across populations of applications, platforms and domains.

And the most representative example I know of is the feature level application monitoring of Dotfuscator Software Services CE:

Beyond Obfuscation

Dotfuscator CE combines its trusted obfuscation technology with injection technology to provide near real-time views into application deployment, stability, and usage. In addition to obfuscation, Dotfuscator CE offers a new category of detective control to better monitor, manage, and protect your applications.  Dotfuscator CE can:

Provide a near real-time view into application integrity and activity at runtime.

Instrument applications to detect if they have been tampered with and if so, optionally send a message to the Runtime Intelligence Service.

Instrument applications with expiration, de-activation, and notification logic that reacts to application expiration by exiting the application and/or sending a Runtime Intelligence Services message.

In this instance, the runtime serves as the common ground, in similar manner as the common client side of web applications.

In any case, usage tracking is not a replacement of requirements specification, it's role is complementary. If it shows that you are getting it wrong more times than you are getting it right, then the problem is deeper...

Body:
There are several products for tracking the usage of your application. I know at least 10 offers. They tell you which features were used more often than others. Thus, you can identify features that may not make into new versions.

While with Google Analytics, or similar tools, this a standard tool for the web at the "page-level". I just wonder who is already using this analysis for desktop applications?

Big companies like Microsoft of course do it, but do ISVs and small vendors (perhaps < 50 employees) use such tools?

I currently don't know anybody, so I'm really curious about it: Is Usage Tracking esoteric or state of the art?


答:
I always though that a person takes a math class to strengthen their skills in the previous class. Algebra seemed hard, until you took Algebra II; Then the skills you learned in Algebra became useful. It is the same thing in programming, writing, woodworking, or anything else.

When taking a programming course you learned about If-then-else, which did a lot of things until you learned about switches. When you are learning anything new you go through this progression, everybody does.


问:
Personal Software Process (PSP1)
I'm trying to figure out an exercise but it doesn't really makes to much sense.. I'm not asking someone to provide the solution. just to try and analyse what needs to be done in order to solve this. I'm trying to understand which PSP 1.0 1.1 process I should use. PROBE? Or something else? I would greatly appreciate some help on this one from someone that has experience with the Personal Software Process Methodology..

Here is the question.

For the reference case (“code1.c”), the following s/w metrics are
  provided:

man-hours spent in implementation phase (per-module): 2,7 mh/file

man-hours spent in testing phase (per-module): 4,3 mh/file

estimated number of bugs remaining (per-module): 0,3 errors/function, 4 errors/module (remaining)

Based on the
  corresponding values  provided for the reference case, each of the
  following tasks focus on some s/w metrics to be estimated for the test
  case (“code2.c”): [25 marks]

(estimated) man-hours required in implementation phase (per-module)  [8 marks]

(estimated) man-hours required in testing phase (per-module)  [8 marks]

(estimated) number of bugs remaining at the end of testing phase (per-module)  [9 marks]

Tasks 4 through 6 should use the data provided for the reference case within the context of Personal Software Process level-1 (PSP-1), using them as a single-point historic data log. Specifically, the same s/w metrics are to be estimated for the test case (“code2.c”), using PSP as the basic estimation model.

In order to perform the above listed tasks, students  are advised to consider all phases of the PSP software development process, especially at levels PSP0 and PSP1. Both cases are to be treated as separate case-studies in the context of classic s/w development.

答:
The use of Proxy-Based Estimation (PROBE) is indeed introduced at PSP 1.0. PROBE is also the recommended estimation technique, but from the standpoint of the PSP as a process improvement framework, it's not required. There are a number of other estimation techniques that can be applied. In a course about the PSP, however, I would recommend using PROBE where applicable.

I believe this passage from A Discipline for Software Engineering is applicable. This book is the traditional text for studying the PSP in an academic setting, and I believe a similar discussion can be found in PSP: A Self-Improvement Process for Software Engineers, which is the more applied discussion, geared for engineers in the workplace.

Another problem, particularly in the early stages of the PSP, is that you will have few historical data. To use the linear regression method, you must have at least three sets of historical data. This means that you cannot use the PROBE method as described here until you have at least three programs for which you have made object LOC estimates. Until you have this much history, you should calculate the Beta_0 and Beta_1 parameters from your actual object LOC and new and changed LOC data and use the averaging method to make your size estimates.

In Chapter 6 of A Discipline for Software Engineering, there are four planning methods presented. There are three questions that you need to ask:

Do I have historical data?

Do I have sufficient estimated object data?

Do I have sufficient data for regression analysis?

If the answer to 1 is no, you must use expert judgement as your estimation method.

If the answer to 1 is yes and the answer to 2 is yes, then you can use PROBE.

If the answer to 1 is yes and the answer to 2 is no, ask 3. If the answer to 3 is yes, use the estimated new and changed LOC coupled with actual development hours. It requires at least three projects to have measurable accuracy. If the answer to 3 is no, then use data on estimated or actual new and changed LOC and actual hours and only requires one prior project.

At this point, you now have the ability to estimate development time. For estimating other tasks, you have a decision between PROBE and intuitive expert judgement options. If you are estimating size, use PROBE. If you can't use size-based estimation methods, use expert judgement and comparison to other projects without the formal PROBE methodology. The previous data come from either your historical data (preferred) or from example cases that can be related.

Now that you know how to estimate within the context of the PSP, it becomes your responsibility to perform data analysis, create an appropriate estimate, and justify your answers by pointing to specific cases, examples, and historical data.

Title: Personal Software Process (PSP1)


问:
Choosing the right branching strategy for releases
Starting with a new dev team on a new project and we have to define our Branching strategy for our source repository (e.g. Microsoft Team Foundation Server 2010). We've run into a sticky discussion over whether or not to...

A. Have one Release branch from which we do production builds and then Label when something is actually released

OR

B. Have a new Release branch for each new Release into production (Ex. Version 1, 2, 3, etc...)

Option A seems pretty straight-forward but we're not sure if this will lead to problems in the long run. Option B seems like it just creates lots of one-time long-lived branches that just pile up over time.

Does anyone have any experience either way that could help us decide? Specifically, I'm looking to hear where the pain-points are for any one choice. Feel free to provide specific experience relative to TFS and/or Release-Management implications.

答:
I've worked for some number of years on a system that uses something somewhat between the two schemes you describe. The key is that there is a multi-level numbering scheme in use. The outer level is basically the API version, and that's managed on branches (with appropriate cross-merges when something needs to be fixed on multiple branches) and the inner level is the exact releases done, which is managed with tags.

In particular, if we know what exact version a customer has, we know exactly what source the code was built from and can make an exact duplicate so that we can see exactly what is going on. This is very important for support! Yet the outer level of branches, the API versions that we currently release, they do evolve over time (with the main trunk of development getting the majority of new features). Also, when we do a new major release of the API, we do a new branch for supporting that from (so the trunk can always be hard-core development oriented) and we consider whether we should end-of-life the current oldest support branch.

Thus I recommend something that's really a mixture of both A and B; both have good aspects, but neither is complete in itself. Use the best of both worlds.


答:
I would add that on mobile application (not mobile web app) usage tracking is also very important because:

It can help to have a view on what number of instance of your software is running

it give you visibility on which os these app are running on. This is key to know on which OS software version you want to maintain is

it can help you to understand usage pattern , conversion rate, etc...

Much of these feature are only available since rencently (less than 5 years) thanks to the availability of affordable data plans and of course to the deployment of the iphone, even if it was available before

Flurry does a very good job in this area

Title: Is Usage Tracking esoteric or state of the art?


答:
Domain-specific languages are quite commonly used in the Tcl community. For example, it's not at all uncommon to see a Tcl program that contains both C and SQL as embedded DSLs (via the Critcl and Sqlite packages). About the only restriction on an embedded DSL is that it is much better if the embedded language balances its curly braces, and that turns out to be a really non-onerous requirement in practice!

Another language which makes DSLs easy is Standard ML, which allows you to have access to raw tokens out of the generic system tokenizer (from before the point where identifiers are converted into keywords). This makes doing a wide class of DSLs easy — provided they obey some of the basic syntax rules of SML, especially in relation to comments, strings and token boundaries — and is in fact used heavily in a number of the key driving applications for the language (theorem provers, etc.)

Not all languages make this so easy. In particular, languages which automatically parse out the contents of braced terms (many many of them!) can't do this, so they require the DSL to be built by either overriding operators, through putting the sub-language inside a string, or by the use of a pre-processor which rewrites the DSL into something that can be handled inside the host language.


答:
May be what you are looking for is as compiler compiler. A compiler compiler takes a language definition written in a formal language and creates a compiler for this language.

Have a look at http://en.wikipedia.org/wiki/Compiler-compiler


问:
Confused About Virtual Memory for All Processes
I hope this is the right place. This is a homework assignment for my Operating Systems course and I have to implement a working virtual memory system in C++ so programming is directly involved.

I've read some sources about Paging and Virtual Memory now (Tanenbaum, What Every Programmer Should Know About Memory, etc) and noticed that everybody starts off with the phrase

Every process gets its own virtual memory.

Then off they go into a detailed analysis about page size, page replacement algorithms, the MMU and TLB, etc. Those things are actually quite fine in my mind, what doesn't make sense is the concept of virtual memory.

If I have four processes running simultaneously and each process uses it's own virtual address space, how is the physical memory protected? The MMU translated the virtual address 0 the same whether it comes from process one, two, three or four.

Let me give an example:

Every process has a 32-bit virtual address space that it can use. Every process starts off the same way

```<code>MOVI 10, 0  // r10 = 0
LOAD 11, 10 // r11 = MEM[r10]; value at address 0x00000000
</code>```

I just don't understand this concept of distinct virtual address space if every process tries to call the same virtual address which will be translated the same way by the MMU. So all four processes will receive the same data?

We have a page table which keeps an index of every mapped and unmapped page to a page frame. If each page entry is unique, then how can it account for the duplicated virtual address space that each process has?

I'm at the point where I have written design drafts for the MMU, TLB and the Page Table, but I can't continue until I properly understand how the heck virtual space is defined and used for each process.

答:
The MMU translated the virtual address 0 the same whether it comes
  from process one, two, three or four.

No it doesn't. The whole point of virtual addresses is that they go through another layer of indirection. Each process has an individual page table which tells the CPU (or OS, I forget) how to translate each virtual address. If there is no entry in the page table for the virtual address for that process, or the page doesn't have the requisite rights (RWX), then that is what an access violation/SIGSEGV is. Two processes can have two separate virtual addresses map to the same physical address for interprocess communication or code sharing, or even to something completely different, for example swap pages, guard pages, etc. However, as the OS has complete and total control over the page table, it is impossible for any application to access physical memory beyond what the OS has allowed, or the virtual memory of any other process.

The physical memory is protected because every access must go through the page table and the OS can control the entries just fine. You can't just make a random pointer and de-reference it because there will be no page table entry.


答:
Continuous refactoring is the way to go. Changing working code would not cause problems and it should be encouraged if done properly. If your code is fully unit-tested, you can re-factor your code with confidence.

The only thing you can predict about real-world production code is, that is WILL change. Don't try to guess at how it will change, what new techniques you will learn tomorrow. In short, don't make try to make your code "perfect". Just make it as good as you can with your present knowledge. Also, make sure your code is thoroughly tested and extensible.

I spend 20%-30% of my time refactoring existing code. I work in a tech company and the "management" has never complained about changing existing code. However, I realize that this can be a problem in some companies. Martin Fowler even has a section on it in his refactoring book.

In summary, it is a common feeling in my experience, but it is not a negative one.


答:
One common way of partially personalizing a programming language is to use a macro pre-processor.  For instance you could run "dokkat-lang" though the C preprocessor before putting the result where some javascript environment would download it.

How much you can do depends on the sophistication of your preprocessor.  Note that early versions of C++, Objective C, and various experimental languages were done by preprocessing the source code before feeding to a stock C compiler toolchain.


答:
I regard these as an organizational smell. That is they are not necessarily a red flag, but an indicator that you should be looking for red flags. PDP initially sounds good, but I've rarely seen any action really happen with them in the past. Usually, they are just a waste of the several hours it takes to fill them out, get them approved, etc.

I say they are a smell because these are part of that MBA/HR group of tools which includes Performance Objectives, Annual Reviews, PDP and "incentive" based pay (which is essentially a disincentive according to many including Joel Spolsky and Mary Poppendeick). All of these approaches put together encourage a me-first attitude and at best accidentally reward anyone for being a team player. This also usually means "we have a quota of Excellent, Above Average, Average, and Not Meeting Expectations performance grades that we will abide by regardless of actual performance" and thereby introduce competition instead of cooperation.

If I have to compete with my team members, am I going to share information with them? Am I going to risk falling behind on my tasks to help them out on theirs? The answer is "no".

Title: Are enforced Professional Development Plans useful?

Body:
Many companies, especially larger ones have mandatory professional development plans for their employees. Employees and managers set out a personalized professional development plan and follow up on the progress every so often.

As a developer, do you find such PDPs useful, do you follow through with your commitments?

As a manager, do you think such PDPs bring value to the company and improve the overall quality of the employees?

It seems that good developers will continue to educate themselves and strive to be better regardless of companies' procedures while bad ones won't.

Are there benefits of having PDPs or is it just something managers feel they need to do?


问:
Efficient graph clustering algorithm
I'm looking for an efficient algorithm to find clusters on a large graph (It has approximately 5000 vertices and 10000 edges).

So far I am using the Girvan–Newman algorithm implemented in the JUNG java library but it is quite slow when I try to remove a lot of edges.

Can you suggest me a better alternative for large graphs?

答:
Hierarchical Clustering

This was recommended to me by a friend. According to Wikipedia:

In this method one defines a similarity measure quantifying some (usually topological) type of similarity between node pairs. Commonly used measures include the cosine similarity, the Jaccard index, and the Hamming distance between rows of the adjacency matrix. Then one groups similar nodes into communities according to this measure. There are several common schemes for performing the grouping, the two simplest being single-linkage clustering, in which two groups are considered separate communities if and only if all pairs of nodes in different groups have similarity lower than a given threshold, and complete linkage clustering, in which all nodes within every group have similarity greater than threshold.

Markov Cluster

This is what I use in your situation. It is a very useful algorithm. I found a link to a nice PDF about the Algorithm. It is a great algorithm, and, for lack of a better term, extremely "powerful". Try it out and see.

Title: Efficient graph clustering algorithm


问:
Are certifications worth it?
I am finishing my college degree in programming soon and I'm exploring the next steps to take to further my career. One option I've been considering is getting a certification or a series of certifications in the area of development I want to work in.

Are these certifications worth the time and money? Do employers place a lot of value in them?

答:
One method that has worked previously (at least for a number of people I know) is to blog, answer questions on forums, speak at user groups and generally have a noticeable online presence.

Blogging regularly, even about topics that you're only just learning, can be a valuable insight to your passion, commitment and communication abilities when it comes to software development.

Title: Are certifications worth it?