问:
Fast lookup hash map implementations
I'm in the process of implementing a programming language on top of LLVM. For my polymorphic system, I'm looking for suggestions for a ultra-fast dictionary. I am not concerned with insert time, as these maps are only written to a dozen times or so. But I'm looking for super fast lookup.

I did some research on the open addressing dict implementation in Python, and it seems pretty fast (a few shifts and bitmasks in the best case). However, I want to do my research. Does anyone know of a super fast dictionary/hashmap implementation?

In this case my data will most likely be pointers as keys and pointers as values. Or if it works out better, I could probably get by with integers as keys. Any papers or discussions on the subject would be great.

答:
You could take a quick look at "Cuckoo hashing" - if it works, you are guaranteed constant lookup time (in contrast to most hashing schemes, such as open addressing). Of course, it is not without its own problems, but it might be worth looking into, considering your insert/lookup preferences.

Article on wiki: http://en.wikipedia.org/wiki/Cuckoo_hashing

And though you might have considered it, Linear Probing also have its share of advantages - in contrast to OA you scan memory sequentially, which is of course a lot faster than the random access of OA (but of course, other factors influence this as well).

Finally, there exist schemes to create perfect hash tables - these are typically very slow to construct, but guarantee constant time lookups.

I won't link to any papers or articles, but search google for: cuckoo hashing, linear probing, perfect hashing

Title: Fast lookup hash map implementations


问:
Hating your own code - for good or bad, how do you deal with it?
Have you ever had this feeling that your code is bad, the whole project is a mess, and you just want to step off? On your daily job you can explain this feeling away with your coworkers, asshole boss, or something like this. But with side/pet projects there is really no excuse.

For example I'm currently maintaining my Firefox extension - fixing bugs and adding new features. Quite frequently when I go back to the code written months ago the feelings that arise inside me are quite controversial - "Did I write that? Really??" Knowing that proper implementation of new feature "the right way" requires throwing away whole module and still putting together a quick hack - sometimes I don't even hesitate.

As the project grows, features are added there remains less and less room for refactoring...

Do you have any recipes for dealing with this kind of emotional state? Do you just pull yourself together and give the whole project another thought, rewrite version 2? Or maybe just ignore all this - "working code is better than perfect code"?

答:
From what you're saying, it sounds like you have accumulated techincal debt.

I think everyone has thought "did I write that". I suggest the following for doing what you can to improvide it:

Refactor where at all possible

Make sure your naming is consistent

Format the code to make it more readable

Add a peppering of comments if it needs it

Take it in chunks as you come across what you're unhappy with.

Do you have any recipes for dealing with this kind of emotional state? Do you just pull yourself together and give the whole project another thought, rewrite version 2? Or maybe just ignore all this - "working code is better than perfect code"?

I think most people have these feelings. You need to push past it and remember it is "just code" and it works for you, not the other way round.

My advise from what you've said is to take a few days and refactor and rewrite what you're unhappy with before adding any features or fixing bugs.

ContentLicense: CC BY-SA 3.0


答:
As said already, you've accumulated technical debt. Refactoring may be a good tool, but it can also be abused. In the extreme, you could refactor all the 1s in your code into an interface constant named Constants.ONE. A contrived example, but one that serves to warn against refactoring as a silver bullet. What you're really after is technical debt containment. Keep a high quality architecture and you'll find that your mess, albeit always present in your code, remains confined to a certain module and is most often out of your sight. That realization always helps me enjoy my code.

I don't know at what pace your programming techniques evolve, but when I realize I wrote bad code it's not because I'm suddenly seeing a better way to solving a problem. Nowadays, I just don't learn a great deal in terms of programming techniques anymore - whether good or bad, my techniques are more or less established. It's more likely that I recognize my bad code as soon as I write it. You may be writing the code with the wrong mindset if you end up realizing the hacks later on. Code quality may not be a concern at the time you write it, perhaps because you write it under pressure.

I code at the highest level I can even for such things as Chrome extensions. I can rest assured that, due to architectural separation, I end up enjoying most of my code, because it stays focused and cohesive. I noticed a tendency to the contrary in fellow developers, especially Java or .NET developers, who sometimes think of Javascript as a lesser language and just whip together the quickest code they can write. I learned my lesson as early as high school, when my informatics teacher said when sitting at my computer to fix my crappy program: "all programs are worth salvaging". That mindset gave me a respect for all the programs I write, even throwaway scripts or SQL statements, which deserve comments and properly named variables. I warmly recommend giving this mindset a try, and you'll enjoy your programs a whole lot more.

Title: Hating your own code - for good or bad, how do you deal with it?

Body:
Have you ever had this feeling that your code is bad, the whole project is a mess, and you just want to step off? On your daily job you can explain this feeling away with your coworkers, asshole boss, or something like this. But with side/pet projects there is really no excuse.

For example I'm currently maintaining my Firefox extension - fixing bugs and adding new features. Quite frequently when I go back to the code written months ago the feelings that arise inside me are quite controversial - "Did I write that? Really??" Knowing that proper implementation of new feature "the right way" requires throwing away whole module and still putting together a quick hack - sometimes I don't even hesitate.

As the project grows, features are added there remains less and less room for refactoring...

Do you have any recipes for dealing with this kind of emotional state? Do you just pull yourself together and give the whole project another thought, rewrite version 2? Or maybe just ignore all this - "working code is better than perfect code"?


答: Don't hate. 2nd tier programmers hate. Craftsmen look at code without bringing ego into it. Code is not a reflection of who you are. It is a means to an end. Try to learn from your past mistakes and try not to repeat them but you can't do that if all you are thinking about is how shitty of a coder you are. So don't be a hater, don't be a 2nd tier programmer. Be a craftsman.</p>


问:
Benefits of combining programming languages
I know there are different ways to combine programming languages (Haskell's FFI, Boost with C++ and Python, etc...). I have an odd interest in combining programming languages; however, I have only found it "necessary" once (I didn't want to rewrite some older code). Also, I notice that this interest is shared (there are an abundance of questions about integrating languages on SO).

My question is, simply, are there any other benefits in combining programming languages? Is there value in mixing different programming paradigms (e.g. functional+OO, procedural+aspect-oriented)?

Any from-the-field examples would be much appreciated.

UPDATE

When I say "combine two languages" I am talking about using them in conjunction, in ways not necessarily originally intended. For example, suppose I use Boost to incorporate Python code in C++.

答:
A typical example shows up in the Computer games, particularly AAA titles where a C++ backend is the norm. The interface section will often be designed in a scripting language such as Python or Lua. This allows for easy modification by both the developers so they can test out new interface designs without messing with the highly complex physics and graphics engines underneath and at the same time allows for easy modification by players who may not have the coding chops to handle a full game engine but can competently do a few interface tweaks.

Another widespread use case is the web itself. Javascript, CSS and HTML combine to form a front end with whatever you want as a backend on the server. Windows 8 apps use a similar approach with the declarative XAML defining interfaces and providing class outlines while C# fills in the details and runs the thing.

Thus, the typical divide will be a fast, statically typed language running a solidly tested codebase handling heavily numerical work with a scripting language running on top of it to provide easily changeable frontends handling visual and presentation functions as well as input.

Other use cases exist as well. Data processing languages like R can be bolted on to other codebases to provide analytic and presentation functions more easily than the native codebase might be able to. As far as combinations of paradigms, a combination of Prolog for database work and some other language to handle the standard program functions is a known case. Another case would be having Fortran or Assembly routines for fast numerical computation within some scripting language like Python. Which is exactly what Numpy and Scipy do.


答:
Great question and I can feel your pain and emotions because I was into the same scenario few months back. Initially I was so upset and frustrated and feeling so bad for cleaning someone’s mess I asked myself several time “what the hell I am doing? I can’t take it any more…” but suddenly a very good suggestion was fired from my frustrated mind and as per that idea I created an XLS file with some common mistakes and their regular occurrences and then defined priorities to these line items so that I can go for all the cleansing in a managed way. During implementation my mind tried to pull me back by saying that this idea is also not going to work this is bullshit, but within 2 days the no of lines in the XLS reached to the healthy count of 40 and after observing those 40 line items in one go I found some great coding standards that every developer should follow in their day to day coding practices because knowing a concept is different but implementing that particular concept Is awesome like “LAZY INITIALIZATION” I know that concept or the whole development team knows that concept but no one follows or implement this. Those 40 line items motivated me a lot and ones you got motivated you are into the learning process and you will find that this time wasting cleansing activity actually brushed up your coding skills and you will always remember few of the common mistakes made by any programmer and even you will come up with some great ideas and suggestions for you future projects and their implementation so indirectly you are learning from someone’s mistakes. You are working for the means of organization benefit apart from your personal moral values.

Hope this will help you as well. Cheers

Thanks


问:
Developer name in the copyright notice of files contributed to open source project?
I am developing a small application which I want to make open source.

Currently only my work is on the application, and so in all the files I have put up a copyright notice in my name.

Now when I make the project open source and say a developer Sam does some enhancements to some existing files. Then should he be allowed to put up a copyright notice in his name as well?

And what if a new file is added by Sam which is entirely his work. So should he add his copyright or mine?

I feel that all files should have only my name as copyright irrespective of the work done by anybody. This is because say I have added some code which depends on Sam's copyrighted code and the application is running on it. Now in future if Sam is approached by some organization then he can sell the code under his copyright. If this happens then my application will stop working because I will have to remove Sam's code and all the depending code of mine.

This is just what I feel. What is the common practice in the Open Source Community?

Note I want to use GNU LGPL as my license. I am maintaining a list of contributors which can be viewed by clicking a button in the About Dialog.

答:
The two most popular ways of going about this are:

Accept only contributions under the same license as your main project (or a compatible one), and make all authors co-authors under a single unified license. This means your name and Sam's name both go in the copyright notice, or, when there are too many contributors, you reference a CONTRIBUTORS file.

Have the contributors sign their copyright over to you (or a nonprofit you set up for this, in case of larger projects); it is customary to combine this with a promise from your side that the code will be released under a free/libre license. Sam's name then doesn't have to be in the LICENSE, but it is still nice to attribute

In both cases, you need to make it abundantly clear under which terms the contribution happens, otherwise you do indeed risk Sam retracting his contribution and you having to remove his code from the project.


问:
Microsoft's coding standards for ASP.NET controls
I cannot find any naming standards/conventions in MSDN for naming ASP.NET controls.

One of the following standards tends to be used by programmers:

lblAddress

AddressLabel

Address

According to MSDN's Name of Type Members, should we be treating ASP.NET controls as fields, hence using Pascal Case (e.g. AddressLabel)?

答:
In programming language naming convention have great benefits to reduce the effort needed to read and understand source code. It provides better understanding in case of reuse code after a long interval of time. It is an initial step for beginner to learn any programming language. It is a very important element

A good reference regarding this:http://cybarlab.blogspot.com/2013/02/standard-naming-convention-for-aspnet.html

Hope it will help you

Best regard


问:
Course Map Generator
My university lists the rotation of courses each semester/year. Therefore, it is possible to predict when every class will be taught.

I am trying to create a JavaScript (language is irrelevant, really) program that will have the user select all the courses they would like to take, for how many semesters, and the max (or maybe exact) number of  classes they'd like to take during each one of those semesters.

So, for instance, my university offers:
12 courses in Fall (varies between even and odd years)
10 courses in Spring (varies between even and odd years)
6 courses in Summer (varies between even and odd years)
essentially, 6 different semester patterns

Basically, the user will choose their preferred 16 or so courses, enter 6 semesters, the semester they would like to start in, and the max number of courses per semester. From there, I would like to generate all the possible course maps the user could take in order to graduate in 6 semesters. I want them to be able to vary the number of courses in each semester--like 3 courses one semester, 2 courses in another, etc. I also want to check previous classes to make sure classes aren't duplicated, as well as ensure that the classes meet their respective pre-requisites.

My instincts say to go with recursion in order to do this, but I'm not exactly sure how I would go about it.

So far, I have only been able to come up with: generate all the sets per semester based on home many courses the user would like in that semester (if the user picks 3 courses for the first semester, then create all the sets of 3 out of the 12 courses). Do this for each semester. Then, loop through all these combinations to see which ones work. Seems very inefficient and slow to me.

As this is Programmers SE, I'm not really looking for any code, but maybe an algorithm or a more efficient approach to this problem. Any help would be greatly appreciated. I can post a link to my university's course rotation if that would help.

答:
You could do this by hand, in which case you will indeed need to backtrack during a recursive search. However, this sort of problem is very complex and you have a high risk that your implementation will not be robust against a lot of changes, which invariably will happen.

A more general approach to these problems is available in the form of constraint programming (CP). With CP you can reduce your problem to providing correctly formatted input and writing down the constraints, i.e. restrictions, that valid paths must adhere to.

So when you think about your problem, you can easily come up with several constraints:

All mandatory courses must be included in the solution.

No course time schedule (time, room,..) must overlap with any other from the solution.

The number of required semesters for taking all the courses of the solution must not exceed 6 semesters.

and so on, and so on

In a CP solution you would write down exactly these constraints as part of your code and provide the available courses as input, whereas the underlying constraint solver (several libraries in various languages are available for these) will perform the grunt work for you in very efficient ways.

In order to model things like "prefer to have only 2 courses in first semester" in such a way, that 3 or 4 courses would be possible too, you will need to look up so-called soft constraints.

Title: Course Map Generator


答:
Now when I make the project open source and say a developer Sam does some enhancements to some existing files. Then should he be allowed to put up a copyright notice in his name as well?

Well, copyright law (in most jurisdictions) states that Sam owns copyright on any non-trivial changes that he makes to the files.  He is reasonably entitled to add his Copyright notices.  You have two alternatives:

Accept his changes as is (with or without changes to the Copyright notice.)

Require him to formally assign you the copyright as a precondition of accepting his changes.  Of course, he may not agree with that, and walk away.  Or he may just decide to fork your project an make his changes in his fork.

In a sense, him putting his copyright notices ... or not ... is irrelevant.  If his copyright material is in the file, then he has a legal claim on part of the IP, irrespective of the copyright headers.

But the bottom line is that if you are going to run an open source project, it is not all about you getting the ownership, the credit, the glory.  If you want other people to help you, you have to think about what they want to get out of it too.

However ...

Now in future if Sam is approached by some organization then he can sell the code under his copyright.

If you choose a decent open source license, that cannot happen.  In a decent license, stuff properly published under the license cannot be unpublished.  It is out there ... forever.

(If you are worried about this, get him to sign something to attest that 1) he is legally entitled / authorized to contribute his work, and 2) he agrees (irrevocably) to it being published under your project's open source license.)

(A bit off topic, but important nevertheless.)

There is another (practical) reason for asking people to assign copyright.  If the copyright of a codebase is held variously by a number individuals, it can be difficult if you need to do something that requires the consent of all copyright holders.  The classic case is if you want to change the license, you need to find all copyright holders and get them to agree.  Even tracking them all down can be difficult.

But the flip-side is that if you want people to assign copyright to you, they have to trust that you are not going to abuse your position as the copyright holder; e.g. by relicensing under a closed source license.

Title: Developer name in the copyright notice of files contributed to open source project?

Body:
I am developing a small application which I want to make open source.

Currently only my work is on the application, and so in all the files I have put up a copyright notice in my name.

Now when I make the project open source and say a developer Sam does some enhancements to some existing files. Then should he be allowed to put up a copyright notice in his name as well?

And what if a new file is added by Sam which is entirely his work. So should he add his copyright or mine?

I feel that all files should have only my name as copyright irrespective of the work done by anybody. This is because say I have added some code which depends on Sam's copyrighted code and the application is running on it. Now in future if Sam is approached by some organization then he can sell the code under his copyright. If this happens then my application will stop working because I will have to remove Sam's code and all the depending code of mine.

This is just what I feel. What is the common practice in the Open Source Community?

Note I want to use GNU LGPL as my license. I am maintaining a list of contributors which can be viewed by clicking a button in the About Dialog.


问:
What does the term day-one-bug mean?
I came across this term recently in a mail chain. Google tells me there is a term zero-day bug and that Microsoft and Adobe are the frontrunners :)

Is there such a term as day one bug? What might that mean?

答:
A "day one" bug is simply a bug that has been around a long time (day one being the software's creation date), as compared to a "regression", or recently introduced bug.  When analyzing a problem which has just been reported for the first time, it is general practice to focus on recent changes to the software as the most likely source of the problem.  Some bugs however, lead a charmed life and lay dormant for years (or even decades) without being noticed.  In my experience as a developer, day one bugs generally are masked by other software that repairs the damage or prevents the bug from being exercised; seemingly unrelated changes can remove one of these "compensating factors" which allow the original bug to finally manifest and be noticed.  I found a bug in 2012 in code that I wrote in 1986 and which had processed billions if not trillions of transactions at hundreds of installations before its first crash.  I spent several days convincing myself (by constructing elaborate tests) that the bug was truly day one.

The term "zero day" is totally unrelated to the much older "day one".

Title: What does the term day-one-bug mean?


问:
Why do some big projects, like Git and Debian, only use a mailing list and not an issue tracker?
Bug tracker for any decent sized project seem like a bit of a no-brainer to me - it makes it really easy to organise hundreds or thousands issues, without issues colliding or getting mixed up.

So when I see some really big projects, like Git, using a mailing list as the main method of coordinating maintenance and development, I get a bit blown away. Examples:

Git - Community page:

...Bug reports should be sent to this mailing list.

Debian bug tracking system, per Wikipedia:

...Its unique feature is that it doesn't have any form of web-interface to edit bug reports - all modification is done through email.

Many modern bug trackers have very good integration with email (you can receive comments or notifications about bugs you're watching, or that get assigned to you), as well as to version control systems (commits can be marked as resolving an issue, etc.). Much of this would have to be done manually with a mailing list, and you get tons of emails about bugs you're not interested in.

So what are the main advantages of a mailing list over a web-based bug tracker? Why do some big projects only use a mailing list?

答:
The preference you observe looks like a natural consequence of recommendation clearly stated in GNU Coding Standards. It suggests to report bugs by email, as you can see in below quote (I marked bold the part that directly addresses your observations):

4.7.2 --help

The standard --help option should output brief documentation for how to invoke the program, on standard output, then exit successfully. Other options and arguments should be ignored once this is seen, and the program should not perform its normal function.

Near the end of the ‘--help’ option’s output, please place lines giving the email address for bug reports, the package’s home page (normally ‘http://www.gnu.org/software/pkg’, and the general page for help using GNU programs. The format should be like this:

```<code>    Report bugs to: mailing-address
    pkg home page: <http://www.gnu.org/software/pkg/>
    General help using GNU software: <http://www.gnu.org/gethelp/>
</code>```

It is ok to mention other appropriate mailing lists and web pages.

Above preference, in turn, reflects universal acceptance of email as a form of electronic communication. Any user reading --help message like suggested above is supposed to easily understand what to do if they see a bug - mailing is easy.

Issue tracker might be (and I think is) better for a developer working in the project, but for a wider audience it would be harder to present and explain how to use it, especially taking into account wide variety and differences between different issue tracking systems.

One project can use Bugzilla, another will stick with JIRA, third with... GNATS, etc etc, etc. There's just no way to present all this "zoo" in a way that would be as standard and uniform as

Report bugs to: mailing-address

Note above doesn't mean that projects shouldn't be using issue tracker internally. As explained in an excellent answer to related question,

Your bug tracker is for your convenience, not your customers'. If you can't be bothered to take their phone or email issue and enter it yourself, how do you think they feel?

You need to be able to enter issues and assign them manually to a client...

Body:
The preference you observe looks like a natural consequence of recommendation clearly stated in GNU Coding Standards. It suggests to report bugs by email, as you can see in below quote (I marked bold the part that directly addresses your observations):

4.7.2 --help

The standard --help option should output brief documentation for how to invoke the program, on standard output, then exit successfully. Other options and arguments should be ignored once this is seen, and the program should not perform its normal function.

Near the end of the ‘--help’ option’s output, please place lines giving the email address for bug reports, the package’s home page (normally ‘http://www.gnu.org/software/pkg’, and the general page for help using GNU programs. The format should be like this:

    Report bugs to: mailing-address
    pkg home page: <http://www.gnu.org/software/pkg/>
    General help using GNU software: <http://www.gnu.org/gethelp/>

It is ok to mention other appropriate mailing lists and web pages.

Above preference, in turn, reflects universal acceptance of email as a form of electronic communication. Any user reading --help message like suggested above is supposed to easily understand what to do if they see a bug - mailing is easy.

Issue tracker might be (and I think is) better for a developer working in the project, but for a wider audience it would be harder to present and explain how to use it, especially taking into account wide variety and differences between different issue tracking systems.

One project can use Bugzilla, another will stick with JIRA, third with... GNATS, etc etc, etc. There's just no way to present all this "zoo" in a way that would be as standard and uniform as

Report bugs to: mailing-address

Note above doesn't mean that projects shouldn't be using issue tracker internally. As explained in an excellent answer to related question,

Your bug tracker is for your convenience, not your customers'. If you can't be bothered to take their phone or email issue and enter it yourself, how do you think they feel?

You need to be able to enter issues and assign them manually to a client...


答:
Another example that was not mentioned is the use of a new programming paradigm with existing legacy code and / or libraries.

For example, Java has tons of existing libraries and frameworks that can be used directly by new languages like Scala and Clojure. In this way, one has the advantage of using a clean implementation of a different programming paradigm that is not supported by Java, while retaining backward compatibility with legacy code and existing libraries. (I chose Java, Scala and Clojure but there are probably other examples I do not know of).

Title: Benefits of combining programming languages

Body:
I know there are different ways to combine programming languages (Haskell's FFI, Boost with C++ and Python, etc...). I have an odd interest in combining programming languages; however, I have only found it "necessary" once (I didn't want to rewrite some older code). Also, I notice that this interest is shared (there are an abundance of questions about integrating languages on SO).

My question is, simply, are there any other benefits in combining programming languages? Is there value in mixing different programming paradigms (e.g. functional+OO, procedural+aspect-oriented)?

Any from-the-field examples would be much appreciated.

UPDATE

When I say "combine two languages" I am talking about using them in conjunction, in ways not necessarily originally intended. For example, suppose I use Boost to incorporate Python code in C++.


答:
With Git, in particular, there is a simple historic reason: Git was started by Linux hackers for Linux hackers, and it uses the same development model and tools as Linux itself does. Linux, however, is older than the WWW, so, when Linux was started there simply were no web-based issue trackers, because there was no web!

As a consequence, the Linux community has developed extremely efficient tools and workflows for dealing with bug reports and code reviews over email, and there was no reason for them to throw all of that work away and start from scratch when they started the Git project.

Title: Why do some big projects, like Git and Debian, only use a mailing list and not an issue tracker?

Body:
Bug tracker for any decent sized project seem like a bit of a no-brainer to me - it makes it really easy to organise hundreds or thousands issues, without issues colliding or getting mixed up.

So when I see some really big projects, like Git, using a mailing list as the main method of coordinating maintenance and development, I get a bit blown away. Examples:

Git - Community page:

...Bug reports should be sent to this mailing list.

Debian bug tracking system, per Wikipedia:

...Its unique feature is that it doesn't have any form of web-interface to edit bug reports - all modification is done through email.

Many modern bug trackers have very good integration with email (you can receive comments or notifications about bugs you're watching, or that get assigned to you), as well as to version control systems (commits can be marked as resolving an issue, etc.). Much of this would have to be done manually with a mailing list, and you get tons of emails about bugs you're not interested in.

So what are the main advantages of a mailing list over a web-based bug tracker? Why do some big projects only use a mailing list?


问:
Determining what is a useful unit test
I've been going through phpunit's docs and came accross the following quote:

You can always write more tests. However, you will quickly find that only a fraction of the tests you can imagine are actually useful. What you want is to write tests that fail even though you think they should work, or tests that succeed even though you think they should fail. Another way to think of it is in cost/benefit terms. You want to write tests that will pay you back with information.
       --Erich Gamma

It got me wondering. How do you determine what makes a unit test more useful than another, aside from what's stated in that quote about cost/benefit. How do you go about deciding which piece of your code you create unit tests for? I'm asking that because another of those quotes also said:

So if it's not about testing, what's it about?
  It's about figuring out what you are trying to do before you run off half-cocked to try to do it. You write a specification that nails down a small aspect of behaviour in a concise, unambiguous, and executable form. It's that simple. Does that mean you write tests? No. It means you write specifications of what your code will have to do. It means you specify the behaviour of your code ahead of time. But not far ahead of time. In fact, just before you write the code is best because that's when you have as much information at hand as you will up to that point. Like well done TDD, you work in tiny increments... specifying one small aspect of behaviour at a time, then implementing it.
  When you realize that it's all about specifying behaviour and not writing tests, your point of view shifts. Suddenly the idea of having a Test class for each of your production classes is ridiculously limiting. And the thought of testing each of your methods with its own test method (in a 1-1 relationship) will be laughable.
       --Dave Astels

The important section of that is

*And the thought of testing each of your methods with its own test method (in a 1-1 relationship) will be laughable. *

So if creating a test for each method is 'laughable', how/when do you chose what you write tests for?

答:
Unit tests should be part of a larger testing strategy. I follow these principles in choosing what types of tests to write and when:

Focus on writing end-to-end tests. You cover more code per test than with unit tests and so get more testing bang for the buck. Make these the bread-and-butter automated validation of your system as a whole.

Drop down to writing unit tests around nuggets of complicated logic. Unit tests are worth their weight in situations where end-to-end tests would be difficult to debug or unwieldy to write for adequate code coverage.

Wait until the API you are testing against is stable to write either type of test. You want to avoid having to refactor both your implementation and your tests.

Rob Ashton has a fine article on this topic, which I drew heavily from to articulate the principles above.

Title: Determining what is a useful unit test


答:
There is no such thing as a "general purpose" programming language. Every language is strong in one area and useless in the others. Therefore, in a complex project which covers many different problem domains it is most efficient to use multiple languages. As far as I know, there are no benefits whatsoever in using a single language for a project where you can use multiple languages.

Of course, the most efficient language for any given problem domain is a language tailored specifically for this narrow domain. This approach is known as Language Oriented Programming, and such languages are called Domain Specific Languages. But even if you, for some weird reason, do not want to implement you own languages, there are multiple ready to use languages out there, and picking one most suitable for a task still will be much more efficient than using a language which does not fit well into the problem domain constraints.

One of the most efficient and convenient way of mixing different languages together is using embedded DSLs hosted inside a single meta-language. This way you won't need any FFI, you can reuse features of your host language library from within your DSLs, you can reuse your host language optimising compiler.

Another common approach is to host different languages within a runtime of a single common VM, like Java+Clojure+Scala or C#+VB.NET+F#.


答: Tkinter is a graphical library for Python that is built upon Tcl/Tk. It's actually an embedded Tcl interpreter that is called from python. Normally this goes mostly unnoticed, but it's possible to put tcl code in a string and run it directly in the interpreter. This lets you do things that the native tcl/tk can do that Tkinter cannot because of an incomplete implementation. </p>


答:
Programming languages are fundamentally abstractions that assist in helping you tell a computer what to do. As they are abstractions, this means that they hide some of the details and so simplify the overall task, enabling you to comprehend how to do some particular piece of programming without having to understand the whole thing at once. But that hiding also means that they restrict what you can do: going outside the abstraction is hard, and so also is having to build a lot of new abstractions on top of the base level provided by the language.

The net effect of this is to mean that a particular programming language has a range of programming tasks that it is well suited to, but it is not going to be good for everything. A low-level programming language allows you to do low-level work, often that happens to be performance critical (such as numeric-heavy processing). That's OK, but doing high-level work in the same language is nothing like as easy as using a language that specializes in higher-level abstractions. What's more, there's no perfect set of abstractions to choose: some problems are better described in one group (e.g., functional programming), and others require a different approach (e.g., logic programming).

The best way out of this situation where a programming language that can do one task isn't good for others is to use multiple programming languages. Let each language focus on doing the tasks that it is good at, and then transfer control to code written in another language for other parts. It's specialization (and also componentization) and it is a good thing indeed. Of course, there are languages that happen to work particularly well together since they have strongly compatible ABIs (e.g., Java and Scala, C# and VB, C++ and Lua) but they're most certainly not the only levels that you can plug things together at. Indeed, when you're accessing a web service you're probably using the same ideas: the languages that clients are written in are probably not those that servers are written in because, even if there's no theoretical reason for a language to be unable to do both sides, some languages have better abstractions for one side or the other.


答:
I would say the benefit is to get the most expressive and best performing solution to the problem at hand. Also, embedding one language in another often lets you move to a higher level of abstraction for parts of your work.

I am doing IOS development, so naturally I am writing in Objective-C++, which gives the awesome power and complexity of C++ and the run-time binding and introspection of Objective-C. I would think this is perhaps the most popular "hybrid" language/paradigm currently. Often I will write .mm (objective c++) files with mostly C++ and STL and just a little Objective-C. For example, last week I wrote a state machine in C++ that called back into an Objective-C object to perform its actions. Writing the machine in C++ was easier, more expressive, and reusable.

In this particular project, I also wrote a scheme interpreter which is embedded in the program and is used to control a communication channel by writing scheme at runtime based on environmental conditions. Scheme is a good choice for this because it is so small, simple and "code is data." It also raises the level of abstraction, and a functional approach works well in this situation.

I don't find embedding little languages to abstract complex problems unusual at all. Be it a set of tokens in a string that control an interpreter to drive some complex decision tree, or a full-blown specialty language of my own design or a unique problem, or a more off-the-shelf solution like LUA.


答: If there actually is a benefit in mixing two languages, soon enough either one language picks up elements or concepts of the second one, or a new language emerges "between" both languages (one could argue that this happened with Scala, which pretty much sits in the "middle" between Java and Haskell).


问:
Choosing between words with different spellings for function names
A question has been bothering me for a while: when developing international projects, it is common sense to use English as the reference language since it is the language that the most people understand.

However, how can one choose to name a function when it could have different valid English spellings. For example, would one name a function get_center or get_centre?

Are there some rules of thumb to choose, do we choose both or just choose one arbitrarily and try to keep consistency afterwise?

NOTE: Most answers recommend using American English, which makes sense. However, I had no idea that one of the spellings was American English and the other one was Great-Britain English. Therefore, my example is not a good one. Of course I would have used center if I had known that difference. But my question is still valid even though my example is a poor one.

NOTE²: Concerning  center vs centre, I see that wxWidgets uses both.

答:
You choose what makes sense for your organization/project, document your choice, and use it consistently. There really isn't any universal guideline for this.

If the majority of your developers spell it "centre", then it may make sense to standardize on the "British English" spelling vs. the "American English" spelling of "center", since that's what most people will be accustomed to.

OTOH, if you're working with one or more APIs/frameworks/toolsets which use the "American English" spellings, you may be better off sticking with that for consistency with those.

But again, document your decision - not just what you decide, but why and make sure that everyone has read, understood & agreed to follow it.


答:
when developing international projects, it is common sense to use English as the reference language since it is the language that the most people understand

For the very same reason, it is common sense to use American English (en-US), not any other regional accents or dialects:

en-US is used in every international project I've seen. Switching from en-US to, for example en-NZ (New Zealand) would be painful and create inconsistencies between the codebase you write and the APIs you use.

Variants other than en-US are less known compared to en-US. That's why I completely disagree with both the comment of Joel Brown and the answer of alroc: if you follow their logic, then you'll find yourself using German if you're in Germany, or Spanish if you're in Spain.

Either you are writing a local project and are completely sure that it will never be used by any foreign developer. In this case, you are not forced to stick to English in the first place, and many developers will use their language instead.

Or your intent is to develop an international project, which means using American English, not English used in Australia or Ireland.

If you're using a language other than American English, it would be consistent to also use non-American localization (not at UI level, but in code and documentation). This creates additional unneeded complexity.

I imagine that for people who have English as their native language, it's pretty simple to understand any English dialect or regional accent. This is not the case for foreigners. Developers working in India, China, Russia are accustomed to American English, and for them (for us), using other variant is painful.

Note: this is still just my own experience as a French developer and what a few of Indians and Russians told me. It appears from the comments that some other foreigners are more accustomed to en-UK.

For example, I have no issues watching a movie in American English, but I can hardly understand some movies shot in Scotland or Wales. Written English is more uniform, but still is slightly more difficult to read and especially write for foreigner developers.

Using English only in a professional context makes things worse. When the only usage of English for a Russian developer is his job, the person will be accustomed to write color or center, and colour or centre will be perceived as a misspelling; just a few seconds after that, the person will understand that it's a correct spelling of a word in another regional accent.

Spell checkers, browsers and other tools are generally configured to be used in American English. Working on a project which uses other locale will require either a dedicated development environment or a constant reconfiguration of tools if the developer has to maintain multiple projects at the same time.

Title: Choosing between words with different spellings for function names

Body:
A question has been bothering me for a while: when developing international projects, it is common sense to use English as the reference language since it is the language that the most people understand.

However, how can one choose to name a function when it could have different valid English spellings. For example, would one name a function get_center or get_centre?

Are there some rules of thumb to choose, do we choose both or just choose one arbitrarily and try to keep consistency afterwise?

NOTE: Most answers recommend using American English, which makes sense. However, I had no idea that one of the spellings was American English and the other one was Great-Britain English. Therefore, my example is not a good one. Of course I would have used center if I had known that difference. But my question is still valid even though my example is a poor one.

NOTE²: Concerning  center vs centre, I see that wxWidgets uses both.


问:
Keep a programming language backwards compatible vs. fixing its flaws
First, some context (stuff that most of you know anyway):

Every popular programming language has a clear evolution, most of the time marked by its version: you have Java 5, 6, 7 etc., PHP 5.1, 5.2, 5.3 etc. Releasing a new version makes new APIs available, fixes bugs, adds new features, new frameworks etc. So all in all: it's good.

But what about the language's (or platform's) problems? If and when there's something wrong in a language, developers either avoid it (if they can) or they learn to live with it.

Now, the developers of those languages get a lot of feedback from the programmers that use them. So it kind of makes sense that, as time (and version numbers) goes by, the problems in those languages will slowly but surely go away. Well, not really. Why? Backwards compatibility, that's why. But why is this so? Read below for a more concrete situation.

The best way I can explain my question is to use PHP as an example:

PHP is loved, and hated by thousands of people. All languages have flaws, but apparently PHP is special. Check out this blog post. It has a very long list of so called flaws in PHP. Now, I'm not a PHP developer (not yet), but I read through all of it and I'm sure that a big chunk of that list are indeed real issues. (Not all of it, since it's potentially subjective).

Now, if I was one of the guys who actively develops PHP, I would surely want to fix those problems, one by one. However, if I do that, then code that relies on a particular behavior of the language will break if it runs on the new version. Summing it up in 2 words: backwards compatibility.

What I don't understand is: why should I keep PHP backwards compatible? If I release PHP version 8 with all those problems fixed, can't I just put a big warning on it saying: "Don't run old code on this version !"?

There is a thing called deprecation. We had it for years and it works. In the context of PHP: look at how these days people actively discourage the use of the mysql_* functions (and instead recommend mysqli_* and PDO). Deprecation works. We can use it. We should use it. If it works for functions, why shouldn't it work for entire languages?

Let's say I (the developer of PHP) do this:

Launch a new version of PHP (let's say 8) with all of those flaws fixed

New projects will start using that version, since it's much better, clearer, more secure etc.

However, in order not to abandon older versions of PHP, I keep releasing updates to it, fixing security issues, bugs etc. This makes sense for reasons that I'm not listing here. It's common practice: look for example at how Oracle kept updating version 5.1.x of MySQL, even though it mostly focused on version 5.5.x.

After about 3 or 4 years, I stop updating old versions of PHP and leave them to die. This is fine, since in those 3 or 4 years, most projects will have switched to PHP 8 anyway.

My question is: Do all these steps make sense? Would it be so hard to do? If it can be done, then why isn't it done?

Yes, the downside is that you break backwards compatibility. But isn't that a price worth paying ? As an upside, in 3 or 4 years you'll have a language that has 90 % of its problems fixed.... a language much more pleasant to work with. Its name will ensure its popularity.

EDIT: OK, so I didn't expressed myself correctly when I said that in 3 or 4 years people will move to the hypothetical PHP 8. What I meant was: in 3 or 4 years, people will use PHP 8 if they start a new project.

答:
A lot of the "flaws" people scream about in popular programming languages aren't, they're things the screamer's favourite toy of the day has that that language lacks, THEREFORE that language is fundamentally flawed because it lacks that.

The next hype comes around, the language is suddenly flawed because it doesn't adhere to that hype.

The lack of closures in Java is a classic example. That's not a flaw in the language at all, and changing the language (as is sadly on the agenda) to include them will IMO fundamentally cripple it or at the very least make it a lot harder to read and comprehend.

What all too many people lose sight of is that each language has its strengths and weaknesses and that trying to create something that combines the strenghts of everything while avoiding every weakness will only create an utterly unusable monster that's good at nothing, incredibly unwielding, impossible to use effectively.

Add, as others have pointed out, that backwards compatibility is vital to retain existing users, many of whom are NOT going to spend the thousands of hours and millions of dollars/Euros to retrofit their million line codebases to whatever you think is "better" than the version of the language they've been using for years, and you've a host of very good arguments to leave well enough alone and if you want to play with some new overhyped idea that's supposedly the next "java killer" you'd best play with that toy rather than scream that "Java iz ded" unless it "gets fixed" to be a clone of that toy.


答:
Two examples:

Wrote a system that imported CSV and XLS spreadsheets into a database using custom mapping documents. Wrote that system in Java and it worked fine. Then came the requirement to read those documents from an FTP server that would need to be polled at set intervals. Ruby's perfect for that, could write that code far more efficiently in Ruby than Java. So wrote a Ruby script to poll and retrieve the documents, which fed them to the original Java application which still could be called standalone as well for additional inserts or testing

Working on a system written in an old language that's probably going the way of the dodo soon (losing support from toolvendors, training providers, etc.). Porting the entire system to a new environment in one go would be too risky for the business, take too long to please marketing, and deny customer new capabilities they've been asking for. So we create for several releases a hybrid system, with part created in that old technology and part in the new, gradually transiting from one to the other until in a year or two maybe the old will all have been retired.

Every system using web services (or other EDI) to communicate is inherently hybrid at least in potentiality. It doesn't matter for your client whether the web service provider is written in Java, C#, Cobol, or whatever as long as the documents exchanged are in a format that both sides understand. Makes for great flexibility in case you have several teams working side by side that have different skill sets. Each can employ what technology it knows best, the end result will be better as a result.


问:
The problems with Avoiding Smurf Naming classes with namespaces
I pulled the term smurf naming from here (number 21). To save anyone not familiar the trouble, Smurf naming is the act of prefixing a bunch of related classes, variables, etc with a common prefix so you end up with "a SmurfAccountView passes a SmurfAccountDTO to the SmurfAccountController", etc.

The solution I've generally heard to this is to make a smurf namespace and drop the smurf prefixes. This has generally served me well, but I'm running into two problems.

I'm working with a library with a Configuration class. It could have been called WartmongerConfiguration but it's in the Wartmonger namespace, so it's just called Configuration. I likewise have a Configuration class which could be called SmurfConfiguration, but it is in the Smurf namespace so that would be redundant. There are places in my code where Smurf.Configuration appears alongside Wartmonger.Configuration and typing out fully qualified names is clunky and makes the code less readable. It would be nicer to deal with a SmurfConfiguration and (if it was my code and not a library) WartmongerConfiguration.

I have a class called Service in my Smurf namespace which could have been called SmurfService. Service is a facade on top of a complex Smurf library which runs Smurf jobs. SmurfService seems like a better name because Service without the Smurf prefix is so incredibly generic. I can accept that SmurfService was already a generic, useless name and taking away smurf merely made this more apparent. But it could have been named Runner, Launcher, etc and it would still "feel better" to me as SmurfLauncher because I don't know what a Launcher does, but I know what a SmurfLauncher does. You could argue that what a Smurf.Launcher does should be just as apparent as a Smurf.SmurfLauncher, but I could see `Smurf.Launcher being some kind of class related to setup rather than a class that launches smurfs.

If there is an open and shut way to deal with either of these that would be great. If not, what are some common practices to mitigate their annoyance?

答:
It is definitely a good rule of thumb that if you've got a common prefix on a bunch of classes, then they probably deserve to go in their own namespace. To deal with the problem then, when you need to use similarly named classes from two namespaces:

1) Alias the namespaces, though I'd make it short and to the point, any
    natural abbreviation, maybe even just 1 letter:

```<code>using Sm = Smurf;
using W = Wartmonger;
</code>```

Then always prefix wherever used and name instances appropriately:

```<code>Sm::Configuration smConf;
W::Configuration wConf;
</code>```

2) Alias the class, as suggested in other answer.

```<code>using SmConf = Smurf.Configuration;
</code>```

3) Any library you have control over, consider not using the term 'Configuration'. Use thesaurus: e.g. 'Settings', 'Model', 'Parameters'. Might be more meaningful to the context anyway: E.g. if Smurf was some sort of numerical analysis module you'd written perhaps 'Parameters' would be better for its configuration. Use the particular vocabulary associated with a module's context to your advantage to come up with unique names that hold uniqueness even when mixed into other namespaces.
I feel this might be kind of an answer to OP question 2.

4) Refactor code so that you don't have to mix the use of configuration from two different places. Details of that are up to you.

5) Combine the two configurations into one before you pass it into your class. Use a combined conf class to represent:

```<code>struct Conf {
    SmurfConfiguration smurf;
    WartmongerConfiguation wart;
}
</code>```

The short member variable names are now kind of achieving the same thing as aliasing the class/namespace.

Body:
It is definitely a good rule of thumb that if you've got a common prefix on a bunch of classes, then they probably deserve to go in their own namespace. To deal with the problem then, when you need to use similarly named classes from two namespaces:

1) Alias the namespaces, though I'd make it short and to the point, any
    natural abbreviation, maybe even just 1 letter:

using Sm = Smurf;
using W = Wartmonger;

Then always prefix wherever used and name instances appropriately:

Sm::Configuration smConf;
W::Configuration wConf;

2) Alias the class, as suggested in other answer.

using SmConf = Smurf.Configuration;

3) Any library you have control over, consider not using the term 'Configuration'. Use thesaurus: e.g. 'Settings', 'Model', 'Parameters'. Might be more meaningful to the context anyway: E.g. if Smurf was some sort of numerical analysis module you'd written perhaps 'Parameters' would be better for its configuration. Use the particular vocabulary associated with a module's context to your advantage to come up with unique names that hold uniqueness even when mixed into other namespaces.
I feel this might be kind of an answer to OP question 2.

4) Refactor code so that you don't have to mix the use of configuration from two different places. Details of that are up to you.

5) Combine the two configurations into one before you pass it into your class. Use a combined conf class to represent:

struct Conf {
    SmurfConfiguration smurf;
    WartmongerConfiguation wart;
}

The short member variable names are now kind of achieving the same thing as aliasing the class/namespace.


问:
Application layer vs domain layer?
I am reading Domain-Driven Design by Evans and I am at the part discussing the layered architecture. I just realized that application and domain layers are different and should be separate. In the project I am working on, they are kind of blended and I can't tell the difference until I read the book (and I can't say it's very clear to me now), really.

My questions, since both of them concerns the logic of the application and are supposed to be clean of technical and presentation aspects, what are the advantages of drawing a boundary these two?

答:
I recently read DDD myself. When I got to this section I was pleasantly surprised to find out I discovered the same 4-layer architecture that Evans did. As @lonelybug pointed out, the domain layer should be completely isolated from the rest of the system. However, something has to translate UI-specific values (query strings, POST data, session, etc.) into domain objects. This is where the application layer comes into play. It's job is to translate back and forth between the UI, the data layer and the domain, effectively hiding the domain from the rest of the system.

I see a lot of ASP.NET MVC applications now where almost all the logic is in the controllers. This is a failed attempt to implement the classic 3-layer architecture. Controllers are difficult to unit test because they have so many UI-specific concerns. In fact, writing a controller so that it isn't directly concerned with "Http Context" values is a serious challenge in and of itself. Ideally, the controller should be just perform translation, coordinate work and spit back the response.

It can even make sense to do basic validation in the application layer. It's okay for the domain to assume the values going into it make sense (is this a valid ID for this customer and does this string represent a date/time). However, validation involving business logic (can I reserve a plane ticket in the past?) should be reserved for the domain layer.

Martin Fowler actually comments on how flat most domain layers are these days. Even though most people don't even know what an application layer is, he finds that a lot of people make rather dumb domain objects and complex application layers that coordinate the work of the different domain objects. I'm guilty of this myself. The important thing isn't to build a layer because some book told you to. The idea is to identify responsibilities and separate our your code based on those responsibilities. In my case, the "application layer" kind of evolved naturally as I increased unit testing.

Title: Application layer vs domain layer?


问:
Can one can survive in the IT industry without knowledge of C and C++?
I am just a graduate from India and I have knowledge of Java, JSP and Servlets, Android application development and some iOS development.

I do not have a background in C or C++ and a little weak background in Data Structures and Algorithms. I want to know whether I can make a successful career in the IT industry without knowledge of C or C++ but having a strong grasp on Java and Python (which is what I am thinking of learning next).

As for the Data Structures and Algorithms part I am planning to study them again with implementation in Java as I am not fluent in C or C++. Can I go good in future if I know Data Structures through Java?

答: There are many Java jobs out there.  Being weak on Data Structures and Algorithms is a bigger issue than not being familiar with a specific language, though.  Don't worry about learning new languages until you understand the uses and implementations of data structures and algorithms.  Opportunities to learn new languages will come to you if you've got a solid foundation in the principles of Computer Science.</p>


问:
Should I use extern global variables or static global variables with "get" and "set" functions in C
I am working on one of my first projects in C (microcontroller code) which is split up into multiple C files. I noticed some inconsistency in my coding where I had some variables declared as extern global variables and would just access them directly (ISR and some other places), and others declared static global variables, and would then accesses them from different files using function calls.

What is the best way to do this? Should I always keep the scope as small as possible even if it means adding extra functions just to set or read the values? Or should I just make them global across all files and just access them directly.

答:
I would say that in this specific case you would probably accomplish the same effect by declaring the variables as extern. I'm basing this on the following assumptions:

You do not have any logic within your getters/setters, and do not intend to add any.

You have one declaration of foo, and functions getFoo() and setFoo(). If you have different variables named foo, with different getter/setter functions, than clearly you can't make them extern (but should probably rename them anyway).

That said, your code will be more modular (but no less coupled) if you adopt the practice of defining static variables within the compilation unit, and access them via getters/setters.


答:
I have been a "web" programmer for many years now and have not touched C or C++ in over 10 years.

That said, the algorithms experience would be very valuable.  Look for a book on the subject that is not specific to language and you should be OK.  I find that a lot of interviewers will ask questions about algorithms and specifically things like sorting, reversing arrays and the such that you wouldn't even think of doing "the hard way" in java, so you need to be able to do pseudo code implementations of those and know the big O notation for each kind of solution.

As for everyday usage, your milage will vary based on what you are doing.  You may write a lot of code and not really dive into anything that requires and in depth understanding algorithms, but occasionally you will.

Title: Can one can survive in the IT industry without knowledge of C and C++?

Body:
I am just a graduate from India and I have knowledge of Java, JSP and Servlets, Android application development and some iOS development.

I do not have a background in C or C++ and a little weak background in Data Structures and Algorithms. I want to know whether I can make a successful career in the IT industry without knowledge of C or C++ but having a strong grasp on Java and Python (which is what I am thinking of learning next).

As for the Data Structures and Algorithms part I am planning to study them again with implementation in Java as I am not fluent in C or C++. Can I go good in future if I know Data Structures through Java?


问:
How can I unit-test my REST web service?
I am new to unit testing, I've one REST web method that just calls DB and populates a DTO. Pseudo code is

```<code>public object GetCustomer(int id)
{
  CustomerDTO objCust = //get from DB
  return objCust;
}
</code>```

My doubt is how to write tests for these methods and type of tests (Integration/Unit) to be included. And for unit tests, does it need to hit the DB. If it were and I pass a customer id and do few assertions, the data might change eventually resulting in failures.

I think I am missing something here understanding these concepts.

答:
While unit testing you are not expected to test with a database, or at least, not with a database you haven't prepared for unit testing. Testing with a database, and as such, testing different layers of your application at the same time is generally seen as integration tests. With unit tests you are supposed to test only what your method does, what it returns depending on different parameters, and when (or not) it should fail.

It is very much expected that in your method you make calls to X methods from other classes. You are not testing these X methods so what you have to do is to mock these methods.

I suppose you're writing your code in Java, in that case you have great mocking frameworks such as Mockito which may be helpful to you. Whether or not you use a mocking framework is your choice, I'll just say they'll save you a lot of time and the one I mentioned at least is really not complicated.

If you just want to write your own mock to experiment, then suppose you have the following CustomerRepository class:

```<code>public class CustomerRepository {
 public CustomerDTO getCustomer(int id) {
   ...
 }
}
</code>```

You can write your own mocked and dirty CustomerRepository class the following way:

```<code>public class MockedCustomerRepository extends CustomerRepository {
 public boolean bThrowDatabaseException;
 public boolean bReturnNull;
 public boolean bReturnCustomerWrongId;
 public boolean bReturnCustomerWithId;
 public CustomerDTO getCustomer(int id) {
  if(bThrowDatabaseException) {
    throw new DatabaseException("xxx");
  } else if(bReturnNull) {
    return null;
  } else if(bReturnCustomerWrongId) {
    throw new CustomerNotExistException(id);
  } else if(bReturnCustomerWithId) {
    return new CustomerDTO(id);
  }
 }
}
</code>```

Then, in your test case you basically replace your "standard" instance of CustomerRepository with a mocked instance that will allow you to test your method for various outcomes of getCustomer:

```<code>public class CustomerRestTest {
  public void testGetCustomer_databaseFailure() {
    MockedCustomerRepository dto = new MockedCustomerRepository();
    dto.bThrowDataBaseException = true;
    yRestClass rest = new MyRestClass();
    rest.dto = dto;
    rest.getCustomer(0);
    // depending on what you do in your getCustomer method, you should check if you catched the exception, or let it pass, etc.. Make your assertions here

  public void testGetCustomer_customerNotExist() {
    // etc.
  }
}
</code>```

Generally, every test method should test one thing only, this helps keep your tests small and focused on one task.

I'm going to repeat it :-) Writing a whole mocked class takes some time as you see. Consider using a mocking framework, the less one writes code, the less errors one makes, right? Mocking a method that throws an exception, or returns a given value for a given parameter is a piece of cake and takes 2 or 3 lines (with mockito at least)

Hope that helps testing your REST method.

Body:
While unit testing you are not expected to test with a database, or at least, not with a database you haven't prepared for unit testing. Testing with a database, and as such, testing different layers of your application at the same time is generally seen as integration tests. With unit tests you are supposed to test only what your method does, what it returns depending on different parameters, and when (or not) it should fail.

It is very much expected that in your method you make calls to X methods from other classes. You are not testing these X methods so what you have to do is to mock these methods.

I suppose you're writing your code in Java, in that case you have great mocking frameworks such as Mockito which may be helpful to you. Whether or not you use a mocking framework is your choice, I'll just say they'll save you a lot of time and the one I mentioned at least is really not complicated.

If you just want to write your own mock to experiment, then suppose you have the following CustomerRepository class:

public class CustomerRepository {
 public CustomerDTO getCustomer(int id) {
   ...
 }
}

You can write your own mocked and dirty CustomerRepository class the following way:

public class MockedCustomerRepository extends CustomerRepository {
 public boolean bThrowDatabaseException;
 public boolean bReturnNull;
 public boolean bReturnCustomerWrongId;
 public boolean bReturnCustomerWithId;
 public CustomerDTO getCustomer(int id) {
  if(bThrowDatabaseException) {
    throw new DatabaseException("xxx");
  } else if(bReturnNull) {
    return null;
  } else if(bReturnCustomerWrongId) {
    throw new CustomerNotExistException(id);
  } else if(bReturnCustomerWithId) {
    return new CustomerDTO(id);
  }
 }
}

Then, in your test case you basically replace your "standard" instance of CustomerRepository with a mocked instance that will allow you to test your method for various outcomes of getCustomer:

public class CustomerRestTest {
  public void testGetCustomer_databaseFailure() {
    MockedCustomerRepository dto = new MockedCustomerRepository();
    dto.bThrowDataBaseException = true;
    yRestClass rest = new MyRestClass();
    rest.dto = dto;
    rest.getCustomer(0);
    // depending on what you do in your getCustomer method, you should check if you catched the exception, or let it pass, etc.. Make your assertions here

  public void testGetCustomer_customerNotExist() {
    // etc.
  }
}

Generally, every test method should test one thing only, this helps keep your tests small and focused on one task.

I'm going to repeat it :-) Writing a whole mocked class takes some time as you see. Consider using a mocking framework, the less one writes code, the less errors one makes, right? Mocking a method that throws an exception, or returns a given value for a given parameter is a piece of cake and takes 2 or 3 lines (with mockito at least)

Hope that helps testing your REST method.


问:
What are the advantages of myBatis over Hibernate?
I've done some research on my own and understand the basic concept. But some insights can only be gained through actual experience.

What are the advantages of myBatis that would make it worth learning a new framework?

In what case would you avoid using it?

答:
Consider what you're trying to achieve. Typically, the Command Query Response Segregation
model works well for complex domains.

The reason is that you're trying to do one of two things typically:

Create/Update/Delete some complex domain entities

Run analytic fetch queries (i.e. summation/aggregation queries)

Hibernate works well for case 1 allowing you to just make a POJO and persist/update it. It also does this quickly, unless your domain is quite large.

myBatis is great for fetch queries (case 2) where you just want an answer. Hibernate would attempt to load the entire object graph and you'd need to start tuning queries with LazyLoading tricks to keep it working on a large domain. This is important when running complex analytic queries that don't even return entity objects. Hibernate only offers SqlQuery and bean Transformers in this case with huge default types like BigDecimal, while myBatis could easily map to a simple POJO non-entity.

These two cases are the difference between Commands where you want to change the domain data and Responses where you just want to fetch some data.

So, consider these two cases and what your application does. If you have a simple domain and just fetch information, use myBatis. If you have a complex domain and persist entities, use Hibernate. If you do both, consider a hybrid approach. That's what we use on our project that has thousands of entities to keep it under control. ;)


答:
In corporate IT, in my experience generally about 1 in 5 IT personnel are programmers of some sort. Of those who have the "programmer"/"developer" label, most are LOB (Line of Business) programmers. They generally work with business objects, workflows, etc - relatively high-level technical abstractions - and can still be extremely effective, valuable to the business, and well-compensated.

So it's more important to understand what kinds of activities make you happy. Do you like spending your time being highly technical and solving difficult technical problems? Or do you prefer to spend your time understanding business processes and building applications that fulfill them? Both are valuable and rewarding.


问:
Should a Presenter or a View sort data in an MVP application?
A typical MVP application might have a View method such as:

void setDisplayItems(List<DisplayItem> items);
```

<p>Should the Presenter sort the list of items or is that a task for the view?</p>

<p>I feel this might be a task for the View, for two reasons:</p>

<ol>
<li><p>If it were a task for the Presenter, then methods such as:</p>

<pre class="lang-java prettyprint-override"><code>void addDisplayItem(DisplayItem item);
</code>```

won't work, as the Presenter can't insert the item at the correct place.

The View can offer different sorting options, based on user selections.

However, I also can't shake the feeling that this is too much "thinking" for the View to be doing. Can anyone comment on the correct choice for MVP?

I should note that I typically produce Swing-based Java applications (in case that allows for more specific answers).

答:
I would put logic like this in the Presenter. One of the important jobs of the Presenter is to  put the data into the correct form for your View. This will make it easier for you to swap out views in the future.

In general, you should try to avoid putting a lot, if any, logic in your View. The only thing in your view should be visual display code and basic code for displaying data as prepared by the presenter.


答:
The point of namespaces is so you can have classes of the same name from different libraries without them colliding. When you need to use the same named class from both you need to remove the ambiguity by prefixing one or both with its namespace scope.

That said, it's not really that bad to have a bunch of Smurf classes if Smurf tells you something specific about the class. The class names should be descriptive enough to give you some information about what the class does.

```<code>      Session
       ^   ^
      /     \
DBSession   HttpSession
</code>```

Similarly a DBSession might take a DBRequest object which returns a DBResponse object. The HttpSession might also operate on HttpRequest and HttpResponse objects.

These are Smurf classes with a purpose.

They might live in the MyCompany namespace but MyCompanyHttpSession and MyCompanyDBSession does not give you any more information than you had before. In this case drop the Smurf and make it a namespace.

```<code>MyCompany.HttpSession
</code>```

Title: The problems with Avoiding Smurf Naming classes with namespaces

Body:
I pulled the term smurf naming from here (number 21). To save anyone not familiar the trouble, Smurf naming is the act of prefixing a bunch of related classes, variables, etc with a common prefix so you end up with "a SmurfAccountView passes a SmurfAccountDTO to the SmurfAccountController", etc.

The solution I've generally heard to this is to make a smurf namespace and drop the smurf prefixes. This has generally served me well, but I'm running into two problems.

I'm working with a library with a Configuration class. It could have been called WartmongerConfiguration but it's in the Wartmonger namespace, so it's just called Configuration. I likewise have a Configuration class which could be called SmurfConfiguration, but it is in the Smurf namespace so that would be redundant. There are places in my code where Smurf.Configuration appears alongside Wartmonger.Configuration and typing out fully qualified names is clunky and makes the code less readable. It would be nicer to deal with a SmurfConfiguration and (if it was my code and not a library) WartmongerConfiguration.

I have a class called Service in my Smurf namespace which could have been called SmurfService. Service is a facade on top of a complex Smurf library which runs Smurf jobs. SmurfService seems like a better name because Service without the Smurf prefix is so incredibly generic. I can accept that SmurfService was already a generic, useless name and taking away smurf merely made this more apparent. But it could have been named Runner, Launcher, etc and it would still "feel better" to me as SmurfLauncher because I don't know what a Launcher does, but I know what a SmurfLauncher does. You could argue that what a Smurf.Launcher does should be just as apparent as a Smurf.SmurfLauncher, but I could see `Smurf.Launcher being some kind of class related to setup rather than a class that launches smurfs.

If there is an open and shut way to deal with either of these that would be great. If not, what are some common practices to mitigate their annoyance?

Body:
The point of namespaces is so you can have classes of the same name from different libraries without them colliding. When you need to use the same named class from both you need to remove the ambiguity by prefixing one or both with its namespace scope.

That said, it's not really that bad to have a bunch of Smurf classes if Smurf tells you something specific about the class. The class names should be descriptive enough to give you some information about what the class does.

      Session
       ^   ^
      /     \
DBSession   HttpSession

Similarly a DBSession might take a DBRequest object which returns a DBResponse object. The HttpSession might also operate on HttpRequest and HttpResponse objects.

These are Smurf classes with a purpose.

They might live in the MyCompany namespace but MyCompanyHttpSession and MyCompanyDBSession does not give you any more information than you had before. In this case drop the Smurf and make it a namespace.

MyCompany.HttpSession


答:
For Git:

There are several discussions on the mailing list where people propose to use some kind of bug tracker. These initiatives seem all to have fizzled, so the reason Git does not uses a bug tracker is probably simply that most contributors do not find it useful.

In a post to the mailing list, Junio C Hamano (Git's maintainer) summed up why he feels a bug tracker is not very useful. I don't want to include the whole post (it's quite long), but it boils down to:

If you are only looking for information on solved problems, searching the list archives works just as well as searching a bug tracker.

If you report a genuine bug, and people want to take care of it, the list also works well.

If no one is interested in working on a problem, it will fall through the cracks, even in a bug tracker.

A bug tracker would be one more system that needs to be maintained, checked for new bugs regularly, have fixed bugs closed etc., in short, extra work for little benefit.


问:
Asp MVC section and partial views
I have a question regarding ASP sections and partial views.

What ser the benefit of using one over another?

Because if I have a menu, i guest that it could be both as a section, but also as a partial view.

So what is the difference?

答:
A partial view is used when you have some view component (optionally with it's own model) that is used in more than one place, or is better separated in to a separate file (for readability, for example).

A section is placed in a master page, and allows individual views to populate those areas - they can mandatory or optional. There aren't really pro's and con's in a comparison between the two, since they serve different purposes.

For your menu example, you may have some mark-up that builds a menu (from a collection) which you would want to to use in many places, then a partial view would be the best option.

If you have a single menu on a page, whose contents change based on the page, then you might use a section to require that the view populates the menu (you may use a partial to populate that menu section too).

Title: Asp MVC section and partial views


问:
Is this technique a design pattern? If so, what's it called?
I'll use C# as an example, but it should apply globally. Say I have a string value that should be one of a few constants, but I also want the client to set which string value to use so:

```<code>private int foo;
private string bar;

public int Foo {
    get { return foo; }
    set
    {
        foo = value;
        bar = getStringValueFromDatabase(value);
    }
}

public string Bar { get { return bar; } }
</code>```

I use this technique quite a lot and want to know if it's considered as any formal concept.

答: Well, it is similar in a way to Lazy Loading, but it's not exactly that.  At first glance, it actually seems a tad dangerous, in that setting a property has side effects.  I believe that's generally frowned upon, but this is hardly an egregious violation.</p>

ContentLicense: CC BY-SA 2.5


问:
What does SVN do better than Git?
No question that the majority of debates over programmer tools distill to either personal choice (by the user) or design emphasis, that is, optimizing design according to particular uses cases (by the tool builder). Text editors are probably the most prominent example--a coder who works on Windows at work and codes in Haskell on the Mac at home, values cross-platform and compiler integration and so chooses Emacs over TextMate, etc.

It's less common that a newly introduced technology is genuinely, demonstrably superior to the extant options.

Is this in fact the case with version-control systems (VCS), in particular, centralized VCS (CVS and SVN) versus distributed VCS (Git and Mercurial)?

I used SVN for about five years, and SVN is currently used where I work. A little less than three years ago, I switched to Git (and GitHub) for all of my personal projects.

I can think of a number of advantages of Git over Subversion (and which for the most part abstract to advantages of distributed over centralized VCS), but I cannot think of one contra example--some task (that's relevant and arises in a programmers usual workflow) that Subversion does better than Git.

The only conclusion I have drawn from this is that I don't have any data--not that Git is better, etc.

My guess is that such counter-examples exist, hence this question.

答:
Subversion and Git both encourage particular (and very different) approaches to development and collaboration. Some organizations will get more out of Git, and others will get more out of Subversion, depending on their organization and culture.

Git and Mercurial are both excellent for distributed and loosely organized teams of highly competent professional programmers. Both of these popular DVCS tools encourage small repositories, with reuse between developers taking place via published libraries with (relatively) stable interfaces.

Subversion, on the other hand, encourages a more centralized and tightly coupled management structure, with more communication between developers and a greater degree of organizational control over day-to-day development activities. Within these more compactly organized teams, reuse between developers tends to take place via unpublished libraries with (relatively) unstable interfaces. TortoiseSVN also permits Subversion to support multidisciplinary teams with members who are not professional programmers (e.g. systems engineers, algorithms engineers or other subject-area specialists).

If your team is distributed, with members either working from home or from many different international sites, or if they prefer to work alone and in silence, with little face-to-face communication, then a DVCS like Git or Mercurial will be a good cultural fit.

If, on the other hand, your team is located on a single site, with an active "team" approach to development, and lots of face-to-face communication, with a "buzz" in the air, then SVN may be a better cultural fit, particularly if you have lots of cross-disciplinary teams.

Of course, it is possible to configure Git and Hg (powerful and flexible as they are) to do pretty much whatever you want, but it is definitely more work, and they are definitely harder to use, particularly for those members of the team who would not naturally be inclined to use any form of version control whatsoever.

Finally, I also find that sharing functionality using "hot" library development under Svn (with CI & a test-driven approach) permits a pace of coordinated development that is difficult to achieve with a more distributed and loosely-coupled team.

Title: What does SVN do better than Git?


问:
Is the average number of bugs per loc the same for different programming languages?
I have been told that the average number of bugs/defects per line of code is "constant" for different programming languages. 10 KLOC of Ruby would have the same number of bugs as 10 KLOC of c++. The argument is usually used to promote the use of expressive languages (think python/ruby over c++/assembly) since the number of lines to describe the same functionality would be smaller.

Does anybody know where this claim comes from? Does higher-level languages lead to fewer bugs?

答: This observation is very old, and comes from a very venerable source, namely Fred Brooks in his book "The Mythical Man Month". He was a top manager at IBM, and managed many programming projects including the milions-of-lines operating system OS/360. In fact he reported that the number of bugs in a program is not proportional to the length of code, but quadratic! According to his research, the number of bugs was proportional to the length of the program to the power 1.5. In other words, a program that is ten times longer has 30 times more bugs. And he reported that this held over all programming languages, and levels of programming languages.


答:
The most important thing is to lay down an API and stick with it.  C offers a few different ways to hide the implementation that look like functions to your callers, and that's preferable to direct access because it gives you more avenues for changing the implementation without breaking existing code.

For example, you can start with variables and access disguised as functions by the preprocessor:

```<code>/* bar.h - Extern-Based Version */
extern int bar_foo;
#define bar_foo_get()  (bar_foo)
#define bar_foo_set(x) bar_foo = (x)
</code>```

Later, if you need bona fide functions with logic inside them, the interface remains the same:

```<code>/* bar.h - Function-Based Version. */
extern int  bar_foo_get();
extern void bar_foo_set(int x);
</code>```

You also have the option of writing your get and set functions as inline.  This gives you the best of both worlds by cutting down on overhead and providing better checking of calls at compile time.  There can be some portability implications that can be overcome by knowing what they are and coding carefully around them.

Which method you choose really depends on whether or not your application can tolerate the extra overhead of a function call.

Title: Should I use extern global variables or static global variables with "get" and "set" functions in C

Body:
I am working on one of my first projects in C (microcontroller code) which is split up into multiple C files. I noticed some inconsistency in my coding where I had some variables declared as extern global variables and would just access them directly (ISR and some other places), and others declared static global variables, and would then accesses them from different files using function calls.

What is the best way to do this? Should I always keep the scope as small as possible even if it means adding extra functions just to set or read the values? Or should I just make them global across all files and just access them directly.

Body:
The most important thing is to lay down an API and stick with it.  C offers a few different ways to hide the implementation that look like functions to your callers, and that's preferable to direct access because it gives you more avenues for changing the implementation without breaking existing code.

For example, you can start with variables and access disguised as functions by the preprocessor:

/* bar.h - Extern-Based Version */
extern int bar_foo;
#define bar_foo_get()  (bar_foo)
#define bar_foo_set(x) bar_foo = (x)

Later, if you need bona fide functions with logic inside them, the interface remains the same:

/* bar.h - Function-Based Version. */
extern int  bar_foo_get();
extern void bar_foo_set(int x);

You also have the option of writing your get and set functions as inline.  This gives you the best of both worlds by cutting down on overhead and providing better checking of calls at compile time.  There can be some portability implications that can be overcome by knowing what they are and coding carefully around them.

Which method you choose really depends on whether or not your application can tolerate the extra overhead of a function call.


答:
Instead of talking about lines of code - which are indeed a useless metric - I'd like to address this part of your question:

Does higher-level languages lead to fewer bugs?

This is different than bugs/LOC, because higher-level languages do more with less code. Implementing some feature requirement might take 500 lines of LISP vs 15000 lines of x86 assembly.

So, even if bugs/LOC is constant between all languages, the higher-level language will still yield fewer bugs.

Title: Is the average number of bugs per loc the same for different programming languages?

Body:
I have been told that the average number of bugs/defects per line of code is "constant" for different programming languages. 10 KLOC of Ruby would have the same number of bugs as 10 KLOC of c++. The argument is usually used to promote the use of expressive languages (think python/ruby over c++/assembly) since the number of lines to describe the same functionality would be smaller.

Does anybody know where this claim comes from? Does higher-level languages lead to fewer bugs?


答:
A partial view works well with Model Binding. You can "type-bind" a partial view so that it will "bind" to the model provided.

```<code>@Html.Partial("_NavigationMenu", Model.Navigation)
</code>```

A Section is basically like a "placeholder" or "literal" which will just output whatever code is placed within the region in it's appropriate location defined in the "parent".

```<code>@section JavaScript{
    //some code to be included on the "parent" view
}
</code>```

Generally, I use sections for various ad-hoc script requirements, or CSS, and partial views for DOM elements like formatting (you could use extensions too) / menus / navigation, etc... same idea as the old ".ascx" controls.

Also:

Partial views do not respect section declarations (by design) and therefor cannot be used.

Title: Asp MVC section and partial views

Body:
I have a question regarding ASP sections and partial views.

What ser the benefit of using one over another?

Because if I have a menu, i guest that it could be both as a section, but also as a partial view.

So what is the difference?

Body:
A partial view works well with Model Binding. You can "type-bind" a partial view so that it will "bind" to the model provided.

@Html.Partial("_NavigationMenu", Model.Navigation)

A Section is basically like a "placeholder" or "literal" which will just output whatever code is placed within the region in it's appropriate location defined in the "parent".

@section JavaScript{
    //some code to be included on the "parent" view
}

Generally, I use sections for various ad-hoc script requirements, or CSS, and partial views for DOM elements like formatting (you could use extensions too) / menus / navigation, etc... same idea as the old ".ascx" controls.

Also:

Partial views do not respect section declarations (by design) and therefor cannot be used.


答:
I tend to follow a different approach to unit testing that seems to work well. Instead of thinking of a unit test as "Testing some behavior" I think of it more as "a specification which my code must follow". In this way, you can basically declare that an object should behave in a certain way, and given that you assume that elsewhere in your program, you can be fairly certain it's relatively bug free.

If you're writing a public API, this is extremely valuable. However, you'll always need a good dose of end-to-end integration tests as well because approaching 100% unit test coverage is usually not worth it and will miss things that most would consider "untestable" by unit testing methods(mocking, etc)

Title: Determining what is a useful unit test

Body:
I've been going through phpunit's docs and came accross the following quote:

You can always write more tests. However, you will quickly find that only a fraction of the tests you can imagine are actually useful. What you want is to write tests that fail even though you think they should work, or tests that succeed even though you think they should fail. Another way to think of it is in cost/benefit terms. You want to write tests that will pay you back with information.
       --Erich Gamma

It got me wondering. How do you determine what makes a unit test more useful than another, aside from what's stated in that quote about cost/benefit. How do you go about deciding which piece of your code you create unit tests for? I'm asking that because another of those quotes also said:

So if it's not about testing, what's it about?
  It's about figuring out what you are trying to do before you run off half-cocked to try to do it. You write a specification that nails down a small aspect of behaviour in a concise, unambiguous, and executable form. It's that simple. Does that mean you write tests? No. It means you write specifications of what your code will have to do. It means you specify the behaviour of your code ahead of time. But not far ahead of time. In fact, just before you write the code is best because that's when you have as much information at hand as you will up to that point. Like well done TDD, you work in tiny increments... specifying one small aspect of behaviour at a time, then implementing it.
  When you realize that it's all about specifying behaviour and not writing tests, your point of view shifts. Suddenly the idea of having a Test class for each of your production classes is ridiculously limiting. And the thought of testing each of your methods with its own test method (in a 1-1 relationship) will be laughable.
       --Dave Astels

The important section of that is

*And the thought of testing each of your methods with its own test method (in a 1-1 relationship) will be laughable. *

So if creating a test for each method is 'laughable', how/when do you chose what you write tests for?


问:
Justifying deficiencies in design
I would like some input on how to handle clients and third party vendors that ask me about the deficiencies in my design.

For example. It turns out I need a data field in a webservices response. This response has been signed off on weeks ago and I get questions like "Why haven't you identified this field X weeks ago?". Of course the answer is that all software development is iterative and this requirement wasn't on my radar at that point in time. I'm not prescient.

I would like a business-y way of deflecting these questions. Any advice?

Update:
To clarify, this shortcoming is completely on me. How do I then own up to this mistake cleanly, without sounding too apologetic?

答:
Add the new field in (do the work), and tell them that you're "looking forward to improving the development process" so that these shortcomings are prevented in the future.

Basically, by adding the field in, you've acknowledged that additional development was needed to satisfy the requirements.

This is not YOUR fault necessarily (it could be if the spec was overlooked, but it happens), and if it was signed off, then everyone missed it.

and then acknowledge the the communication and acceptance process "has room for improvement" so that this situation doesn't arise again. This gives them reassurance that this is not acceptable and they can expect improvements in the future.

The last thing they want is an apology, they want you to acknowledge the mistake, and to hear that it was in fact, a mistake and that efforts will be made to correct and prevent more mistakes in the future.

Title: Justifying deficiencies in design


答:
I almost always just accept the blame for everything:

I'm sorry, I missed it.  Perhaps we can get into the details why in a
  future retrospective.  In the meantime, field X has now been
  identified and needs to be implemented now in order to come close to
  meeting our deadlines.

It takes the issue of blame off the table, and lets people focus on being constructive.

If you think they'll fire you over it, well, you've got other issues in your relationship with your customers.

Title: Justifying deficiencies in design

Body:
I would like some input on how to handle clients and third party vendors that ask me about the deficiencies in my design.

For example. It turns out I need a data field in a webservices response. This response has been signed off on weeks ago and I get questions like "Why haven't you identified this field X weeks ago?". Of course the answer is that all software development is iterative and this requirement wasn't on my radar at that point in time. I'm not prescient.

I would like a business-y way of deflecting these questions. Any advice?

Update:
To clarify, this shortcoming is completely on me. How do I then own up to this mistake cleanly, without sounding too apologetic?