答:
I have refracted the code, in the hope that it makes it clearer.

```<code>def factorial(n):
  if n < 0:
    raise ValueError
  if n == 0:
    return 1
  else:
    return factorial(n-1) * n
</code>```

It says:

I only work for positive numbers

0! = 1

n! = (n-1)! × n

This is the definition: we just write the mathematical definition of factorial in python.

Also look at Kilian Foth's answer as it considers stack-overflow problems.

Title: Need help understanding a recursion example in Python

Body:
Python is my first programming language, and I'm learning it from "How to Think Like a Computer Scientist". In Chapter 5 the author gives the following example on recursion:

```<code>def factorial(n):
  if n == 0:
    return 1
  else:
    recurse = factorial(n-1)
    result = n * recurse
    return result
</code>```

I understand that if n = 3, then the function will execute the second branch. But what I don't understand is what happens when the function enters the second branch. Can someone explain it to me?

Body:
I have refracted the code, in the hope that it makes it clearer.

def factorial(n):
  if n < 0:
    raise ValueError
  if n == 0:
    return 1
  else:
    return factorial(n-1) * n

It says:

I only work for positive numbers

0! = 1

n! = (n-1)! × n

This is the definition: we just write the mathematical definition of factorial in python.

Also look at Kilian Foth's answer as it considers stack-overflow problems.


问:
How should I remember what I was doing and why on a project three months back?
I was working on a project three months back, and then suddenly another urgent project appeared and I was asked to shift my attention.

Starting tomorrow, I'll be heading back to the old project. I realize that I do not remember what exactly I was doing. I don't know where to begin.

How can I document a project such that anytime I look back it shouldn't take me more than a few minutes to get going from wherever I left. Are there best practices?

答:
For simple projects, I do this:

A simple README file in the root directory (which, therefore, will also end up in version control) where I note whatever pops up while developing: things to do, bugs, improvements/ideas. That is the first file I will read should I have to put the project on the back burner.

TODO/FIXME/XXX comments

I often also use ToDoList

ContentLicense: CC BY-SA 3.0


问:
Showing the structure of the program (menu) as a tree - does it a have name?
In my thesis, I want to show the structure of the program, like this:

```<code>> Menu  ---  Settings ---- Audio ---- ...
>                     ---- Video
>
>       ---  Perform  ---- Calculation
>                     ---- Video demo
</code>```

You know, like a map for a website, I would like to present a tree for the menu. But does this have a fancy name in SW engineering?

答: I have not seen any specific term. I have seen all of the following used: menu diagram, menu tree diagram, menu tree.


问:
Writing a new programming language - when and how to bootstrap datastructures?
I'm in the process of writing my own programming language which, thus far, has been going great in terms of what I set out to accomplish. However, now, I'd like to bootstrap some pre-existing data structures and/or objects.  My problem is that I'm not really sure on how to begin.

When the compiler begins do I splice in these add-ins so their part of the scope of the application?

If I make these in some core library, my concern is how I distribute the library in addition to the compiler--or are they part of the compiler?

I get that there are probably a number of plausible ways to approach this, but I'm having trouble with the setting my direction.  If it helps, the language is on top of the .NET core (i.e it compiles to CLR code).

Any help or suggestions are very much appreciated!

答:
In the core runtime library, which you will distribute with your compiler.

Your question is a bit abstract, which I think has misled others in how they've tried to answer. I shall assume your language has a domain of interest, and there are some core objects (base classes, perhaps) which are critical for the language. If your language was for writing games then perhaps you might have some special base classes for players, non-player characters, objects and terrain. This would allow you to have special keywords and language constructs for creating games.

While it is tempting to somehow 'emit' those classes from inside the compiler, in practice it makes more sense to write them as a separate library with known features and have the compiler assume that they will exist. On top of the 'core' library you then build one or more 'extension' or 'add-on' libraries as the language system grows. The compiler knows nothing about these.

In fact it turns out that you should put as little as possible inside the compiler and the core because it is far easier to extend the language system by add-ons than by extending the compiler and core itself.

If this is off the mark, please edit your question to provide some more concrete details.


问:
Why do executables depend on the OS but not on the CPU?
If I write a C program and compile it to an .exe file, the .exe file contains raw machine instructions to the CPU. (I think).

If so, how is it possible for me to run the compiled file on any computer that runs a modern version of Windows? Each family of CPUs has a different instruction set. So how come any computer that runs the appropriate OS can understand the instructions in my .exe file, regardless of it's physical CPU?

Also, often in websites in the "download" page of some application, you have a download for Windows, for Linux, and for Mac (often two downloads for each OS, for 86 and 64 bit computers). Why aren't there many more downloads, for each family of CPUs?

答:
An exe contains more information than just raw machine code. The OS reads this when loading it and can figure out how it should run.

When you compile you generally set a target CPU, if you don't the compiler will pick your current CPU and will restrict itself to only choosing instructions that are common to your CPU and older versions of it. If you want to use a fancy new instruction that's specific to certain revision of your target CPU, you can either tell the compiler or manually code it with either intrinsics or inline assembly code. However your program will crash if it's run on a CPU that doesn't support that instruction.


答:
Executables do depend on both the OS and the CPU:

Instruction Set: The binary instructions in the executable are decoded by the CPU according to some instruction set. Most consumer CPUs support the x86 (“32bit”) and/or AMD64 (“64bit”) instruction sets. A program can be compiled for either of these instruction sets, but not both. There are extensions to these instruction sets; support for these can be queried at runtime. Such extensions offer SIMD support, for example. Optimizing compilers might try to take advantage of these extensions if they are present, but usually also offer a code path that works without any extensions.

Binary Format: The executable has to conform to a certain binary format, which allows the operating system to correctly load, initialize, and start the program. Windows mainly uses the Portable Executable format, while Linux uses ELF.

System APIs: The program may be using libraries, which have to be present on the executing system. If a program uses functions from Windows APIs, it can't be run on Linux. In the Unix world, the central operating system APIs have been standardized to POSIX: a program using only the POSIX functions will be able to run on any conformant Unix system, such as Mac OS X and Solaris.

So if two systems offers the same system APIs and libraries, run on the same instruction set, and use the same binary format, then a program compiled for one system will also run on the other.

However, there are ways to achieve more compatibility:

Systems running on the AMD64 instruction set will commonly also run x86 executables. The binary format indicates which mode to run. Handling both 32bit and 64bit programs requires additional effort by the operating system.

Some binary formats allow a file to contain multiple versions of a program, compiled for different instruction sets. Such “fat binaries” were encouraged by Apple while they transitioning from the PowerPC architecture to x86.

Some programs are not compiled to machine code, but to some intermediate representation. This is then translated on-the-fly to actual instructions, or might be interpreted. This makes a program independent from the specific architecture. Such a strategy was used on the UCSD p-System.

One operating system can support multiple binary formats. Windows is quite backwards compatible and still supports formats from the DOS era. On Linux, Wine allows the Windows formats to be loaded.

The APIs of one operating system can be reimplemented for another host OS. On Windows, Cygwin and the POSIX subsystem can be used to get a (mostly) POSIX-compliant environment. On Linux, Wine reimplements many of the Windows APIs.

Cross-platform libraries allow a program to be independent of the OS APIs. Many programming languages have standard libraries that try to achieve this, e.g. Java and C.

An emulator simulates a different system by parsing the foreign binary format, interpreting the instructions, and offering a reimplementation of all required APIs. Emulators are commonly used to run old Nitendo games on a modern PC.

Title: Why do executables depend on the OS but not on the CPU?

Body:
If I write a C program and compile it to an .exe file, the .exe file contains raw machine instructions to the CPU. (I think).

If so, how is it possible for me to run the compiled file on any computer that runs a modern version of Windows? Each family of CPUs has a different instruction set. So how come any computer that runs the appropriate OS can understand the instructions in my .exe file, regardless of it's physical CPU?

Also, often in websites in the "download" page of some application, you have a download for Windows, for Linux, and for Mac (often two downloads for each OS, for 86 and 64 bit computers). Why aren't there many more downloads, for each family of CPUs?


问:
Is too much whitespace a bad thing?
I'm often told by my friends and colleagues that I use way to much whitespace. I guess I do use a little too much whitespace. I often add a line break almost after every line and large blocks of whitespace, often 3 or 4 lines because it helps me see what I've written and understand what I've written when I look back on it at a later time. I also think it just looks cleaner.

Although I can see two issues with this, 1) It can increase the file size of the source files, even just a line break every two or three lines can add up in a long file. I know that a good compiler will optimize all the white space out (I'm not actually sure, I think LLVM/Clang does this) but the source file is still large.

And 2) it may cause some people to think I'm embellishing my code to make it look longer and "bigger" to make others think I'm doing more work than I actually am (consider 3000 lines vs. 6000 lines, 3000 being newlines). Which I am not doing that by the way. Is using too much whitespace bad from a technical standpoint and/or a professional standpoint?

答:
It's depend of what you mean by too many space. For me it's important and primordial to use space for improve the readability of your code. Use one line free to seperate few block in function, free space between function and class it's good, and allign symbol with few language can be cool also:

```<code>sub my_function {
     my $arg = @_;

     my $a       = 42;
     my $b       = 50;
     my $sum     = $a + $b;

     my $map = {
         key         => 'value',
         second => 'second value'
     }

     if ( $sum > $ arg ) {
         return $sum
     }

     return;
}
</code>```

A little example what I love, hovewer if you use too my line space is not good. For example five free line between the last return and the conditional structure, for me it's a bad idea.

Title: Is too much whitespace a bad thing?

Body:
It's depend of what you mean by too many space. For me it's important and primordial to use space for improve the readability of your code. Use one line free to seperate few block in function, free space between function and class it's good, and allign symbol with few language can be cool also:

sub my_function {
     my $arg = @_;

     my $a       = 42;
     my $b       = 50;
     my $sum     = $a + $b;

     my $map = {
         key         => 'value',
         second => 'second value'
     }

     if ( $sum > $ arg ) {
         return $sum
     }

     return;
}

A little example what I love, hovewer if you use too my line space is not good. For example five free line between the last return and the conditional structure, for me it's a bad idea.


问:
Why would programmers ignore ISO standards?
One of the things I run into often is problems caused by programs which don't conform to ISO standardss.

One example would be not using the ISO country tables but making up their own shorthands, which goes okay for the United States (US), or the Netherlands (NL) but goes spectacularly wrong for the United Kingdom (GB, not UK) or Spain (ES, not SP) and a lot of other countries.

As another example, internal date notations. Why would anyone store a date as 01/02/2014 ever? It is completely unclear whether that is 1st February or January 2nd, whereas if you use the ISO standard you just store 2014-02-01* and it's unambiguously February 1st.

My question: When and why should a programmer make up their own constructs when there is an ISO standard available?

* Store 2014-02-01, and format the date accordingly when showing it to an end user.

答:
A point not raised so far is the cultural appropriateness of international standards.

Consider the international standard for measurements. Let's present those to users in the United States. I'm not sure all your US users will be happy about kilometres, kilograms, and litres.

Consider that international standards are written by governments. If the government of Spain chooses not to recognise the Basque language then how does it get a ISO specification? This is particularly an issue with the dialects and creoles of marginalised groups.

Even country codes can be problematic: does the Crimea now get its own country code? Formulas are eventually found (eg, "Former Yugoslav Republic of Macedonia") but your application may need some stand-in until the diplomacy or war comes to an end.

Consider that international standards are written with particular applications in mind. These may not entirely fit your application. For example, if you are storing language with a view to sending letters then you may wish to code the blind distinctly, even if they are proficient in speaking, say, US English. Statistics organisations are well aware of the need for specifying the exact meaning of a variable (aka the variable's "meta data") as they encounter every possible edge case during a population census. Some of that rigour is well worthwhile for database fields.

The final point is that in making these sort of choices your program may be making a political statement. This reality can mess with the nicest of code (eg, you may need multiple language names for the same language).


答:
If I'm building an Oracle database, and I want to store dates, I'm going to use the Oracle DATE datatype.  I won't know, or care, whether or not Oracle conforms to the ISO standard.  This is really a case of my conformance to a different standard (the Oracle one) and not so much departure from the ISO standard.  See @David's response.

In some cases, by the time I realized there was an ISO standard for something I had designed, the cost of going back and redesigning would have been prohibitive, or at least was seen that way.

In the short term, more working code is produced by using available standards or by inventing new ones than by careful research into extant standards.  The downside occurs when large scale integration requires interoperability.  This almost always occurs in the context of a later project.

Title: Why would programmers ignore ISO standards?

Body:
One of the things I run into often is problems caused by programs which don't conform to ISO standardss.

One example would be not using the ISO country tables but making up their own shorthands, which goes okay for the United States (US), or the Netherlands (NL) but goes spectacularly wrong for the United Kingdom (GB, not UK) or Spain (ES, not SP) and a lot of other countries.

As another example, internal date notations. Why would anyone store a date as 01/02/2014 ever? It is completely unclear whether that is 1st February or January 2nd, whereas if you use the ISO standard you just store 2014-02-01* and it's unambiguously February 1st.

My question: When and why should a programmer make up their own constructs when there is an ISO standard available?

* Store 2014-02-01, and format the date accordingly when showing it to an end user.


答:
You can have too much whitespace - usually its annoying to see a blank line between block and the ending curly brace, eg:

```<code>if (x)
{
    // do something

    // do more

}
</code>```

That annoys me a lot. But then, I like multiple blank lines between functions - 1 line is enough for logical blocks within a function, so 2 makes each function stand out that little more.

Within functions, you do not want to space it out so much that it looks like the logical blocks within it are functions themselves. You're trying to break up a big block of text so its easy to read (like paragraphs in a book) without introducing extraneous white that starts to disrupt reader's ability to group these blocks together.

So: a quick standard for you:
1. indent correctly.
2. single blank line between blocks, where appropriate
3. multiple blank lines between functions.
4. nowhere else.

Stick to that and you'll have happy colleagues and tidy code.

Title: Is too much whitespace a bad thing?

Body:
I'm often told by my friends and colleagues that I use way to much whitespace. I guess I do use a little too much whitespace. I often add a line break almost after every line and large blocks of whitespace, often 3 or 4 lines because it helps me see what I've written and understand what I've written when I look back on it at a later time. I also think it just looks cleaner.

Although I can see two issues with this, 1) It can increase the file size of the source files, even just a line break every two or three lines can add up in a long file. I know that a good compiler will optimize all the white space out (I'm not actually sure, I think LLVM/Clang does this) but the source file is still large.

And 2) it may cause some people to think I'm embellishing my code to make it look longer and "bigger" to make others think I'm doing more work than I actually am (consider 3000 lines vs. 6000 lines, 3000 being newlines). Which I am not doing that by the way. Is using too much whitespace bad from a technical standpoint and/or a professional standpoint?

Body:
You can have too much whitespace - usually its annoying to see a blank line between block and the ending curly brace, eg:

if (x)
{
    // do something

    // do more

}

That annoys me a lot. But then, I like multiple blank lines between functions - 1 line is enough for logical blocks within a function, so 2 makes each function stand out that little more.

Within functions, you do not want to space it out so much that it looks like the logical blocks within it are functions themselves. You're trying to break up a big block of text so its easy to read (like paragraphs in a book) without introducing extraneous white that starts to disrupt reader's ability to group these blocks together.

So: a quick standard for you:
1. indent correctly.
2. single blank line between blocks, where appropriate
3. multiple blank lines between functions.
4. nowhere else.

Stick to that and you'll have happy colleagues and tidy code.


问:
How to handle a vendor who asks for the solution of an issue they could not solve
Being a small department of developers, it's not uncommon for us to outsource projects.  We have a set of companies that we really like to work with, very reliable and good local people who appreciate the work.

This has happened a couple times, most recently today: We receive a project, set it up in our environment, and notice an issue.  Due to them not being able to provide a solution in time, we're forced to find a solve internally.  Then the vendor, who we pay very well, will sometimes ask how we solved the problem.

Again, this is a rarity, and we have a great relationship with these guys, but I do have some inkling that I should not be handing out the answers to a resource which we're paying.

How should I handle this?  Do I set aside my ego and just say "Thanks for doing a great job, here's your $30k and we finished the project for you by doing this one thing your company was unable to do but now can charge us more to do next time"?

Is it appropriate to tell them I can't give them "company" code/etc?  Would this tarnish our relationship?

答:
It is completely appropriate to refuse to release company code (as intellectual assets as the business lawyers would call it) to anyone. Just refuse, and blame the legal team. Your IP is what makes your software company, give it all away and don't be surprised when you find a competitor springing up doing remarkably similar work to you...

Payment... goodwill plays a fair part here, you must be reasonable. There again, you must not be taken advantage of. The first time this happens, fair enough, you can forgive it. If it continues to happen - either downgrade their payment (ie don't offer to pay them as much the on next contract), or charge them back for fixing their work (they can complain, but then you can tell them they have to fulfil the terms of the contract in full or get no payment at all, and might be sued as well for breach)(I wouldn't recommend this course as it always ends badly).

Chances are, a frank discussion with the boss of the other company is required. I would reduce the contract amount next time to make up for the cost to you of fixing their work.

If they still cannot do the job, stop giving them work. Find someone else who can.


问:
Deferred execution of Dispose for IDisposable objects
I'm working on an application that does lots of encryption and decryption in-application and this is probably the number-one bottleneck, so I've been spending some time making performance tweaks to it.  A lot of this has involved simply caching things in memory (I realize there is something of a security tradeoff in doing that), but I noticed during profiling that Dispose() was a fair amount of the time doing decryption (I believe for .NET cryptography stuff it zeroes over everything so this makes sense).  So I came up with this idea:

Have a "dispose pool."  Instead of using blocks, create objects, use them, return the result, and add them to the dispose pool in the finally block.  Internally, the dispose pool uses a queue and a timer and every time the timer fires it dequeues the objects and disposes them.

I tried implementing this and it seems to work and improve performance, but then again, profiling it locally is not a really realistic use case.  Is this sound?  Am I likely to run into runaway performance issues I'm not currently thinking about?

I suppose I should add that this is an ASP.NET MVC application so everything revolves around requests.

答:
maybe you want a collector that regularly runs and when it does, it cleans up these .. how can we call them.. I know - 'garbage' objects. We can call this thing a garbage collector.

Dispose was added to provide deterministic finalisation so you can have objects clean up immediately rather than waiting for later, making a non-deterministic Dispose is just redundant. There is no need to reinvent the wheel.

So, you want finalisation that occurs at a later time, then just use a finaliser. The GC will run that when load is lower. Chances are you don't want that as you do want your dead objects to be memory-wiped immediately, to prevent the security risk of something reading the contents later, probably important in a security application.

Performance will be the same overall - you are simply shifting the place where the cleanup occurs from 'right now' to 'a bit later'. Usually this means the user won't notice the time spent cleaning up but in a heavily used system there's no way to avoid it.


问:
Why do binary files load quicker than alphanumeric text files?
I've noticed that when I load/store large data files in a binary format, the program runs much faster than if I load data from an ASCII encoded file.

Why is this the case? The data in my case is plain, with limited parsing involved other than read() or fscanf().

答:
Its difficult to say without knowing what you're parsing but...

text files are generally bigger. You want to store a number, that can be 4 bytes for an integer, but 10 bytes (*2 for Windows unicode) for some depending on the value.

Both parsing and formatting can be hugely slow. eg. you want to write the integer "123" out to binary - just dump 4 bytes and you're done. Read it back in, read 4 bytes, problem solved.

In text, this involves understanding how to turn the binary 123 into "123" which is quite time-consuming, write it, and then read it back in - you have to parse the text between whitespace, switch on each character (eg so 3 gets read and added to the value, then 2 gets read, multiplied by 10 and added, then 1 gets read, multiplied by 100 and added). I hope you can see how that can be very much more slower than simply reading in 4 bytes.


答:
Feedback is crucial to maintaining this relationship

I'd advocate for a more collaborative approach to help you work better together with these vendors. If you value the closeness of this relationship, and want to keep it, open lines of communication that help them serve you better are best.

Consider the fact that almost nothing works perfectly once it is shipped. Real life production code will encounter real life problems that you may need to work with the original coders to fix. They may be true bugs, or just as likely feedback from real-life users on the operation of the system. (if you're not paying for post-production support and maintenance, perhaps you should continue to engage this team)

There's a good chance you'll want them in the loop after delivery. Even if you don't, you want to give frank feedback for work given to help with future projects. Nothing is more frustrating to a software vendor than the lack of honest feedback (I know I am one!). Its like operating in the dark for them. It will also help you test the relationship: if they are receptive to feedback, you've made the relationship stronger and your vendors better. If not, then you know these are not people you want to work with.

Frankly I wouldn't think of these folks as vendors but rather partners. You want to build their ability to serve you (by giving feedback and educating them about your business/tech requirements as much as possible). You can almost think of it as onboarding an employee -- it takes time and honest feedback to educate somebody on how to work in your environment. If they take feedback and adjust, then its a good fit. If not, then don't continue the relationship.

As for proprietary info, IANAL etc, but its likely your vendors have signed NDAs up the wazzoo, and already have seen this particular proprietary information (the code they developed for you). Even if this vendor is not allowed to see the rest of the system, I can't imagine you couldn't phrase feedback in a way that might be useful to them in serving you better in the future.

Title: How to handle a vendor who asks for the solution of an issue they could not solve

Body:
Being a small department of developers, it's not uncommon for us to outsource projects.  We have a set of companies that we really like to work with, very reliable and good local people who appreciate the work.

This has happened a couple times, most recently today: We receive a project, set it up in our environment, and notice an issue.  Due to them not being able to provide a solution in time, we're forced to find a solve internally.  Then the vendor, who we pay very well, will sometimes ask how we solved the problem.

Again, this is a rarity, and we have a great relationship with these guys, but I do have some inkling that I should not be handing out the answers to a resource which we're paying.

How should I handle this?  Do I set aside my ego and just say "Thanks for doing a great job, here's your $30k and we finished the project for you by doing this one thing your company was unable to do but now can charge us more to do next time"?

Is it appropriate to tell them I can't give them "company" code/etc?  Would this tarnish our relationship?


答:
It definitely depends on the various factors others have mentioned.

There are some circumstances where I want more whitespace, e.g. I may prefer

```<code>class Thing

  def method1
    stuff
  end

  def method2
    stuff
  end

end
</code>```

to

```<code>class Thing
  def method1
    stuff
  end
  def method2
    stuff
  end
end
</code>```

because if those methods get long, having the whtespace lines between them is helpful.

So as a general guideline for code, for % of whitespace lines, I would look for a figure of between 10% and 30%.  Less than that and you have long algorithms, more than than that and you may be scrolling up and down and losing context and visual 'see together' grouping.

However, that said...

for some uses, having it 'all on one screen' is really helpful.

A good example if my .bashrc file which had got to 3 or 4 'screens worth' and was leading to more:

duplication for same settings

conflicting uses of same settings

forgetting what settings do

So in this case, I went to a lot of effort to 'compact' it down.  In this case not just whitespace but making if then constructs fit on 1 line, e.g.

```<code>test -f ~/.bash_aliases && . $_
</code>```

and was able to get it down to 27 lines which I can see all at once, even in a small terminal window, i.e.

Finally, the two issues you mention - file size and padding length are not factors that any programmers I know and respect would pay attention to - remember 100GB is a hundred thousand million bytes.  Extra line spaces would just be considered to be your preference for line space.  If the code actually worked this would usually be a relatively minor issue, though with a team, one that should be agreed on.

Title: Is too much whitespace a bad thing?

Body:
It definitely depends on the various factors others have mentioned.

There are some circumstances where I want more whitespace, e.g. I may prefer

class Thing

  def method1
    stuff
  end

  def method2
    stuff
  end

end

to

class Thing
  def method1
    stuff
  end
  def method2
    stuff
  end
end

because if those methods get long, having the whtespace lines between them is helpful.

So as a general guideline for code, for % of whitespace lines, I would look for a figure of between 10% and 30%.  Less than that and you have long algorithms, more than than that and you may be scrolling up and down and losing context and visual 'see together' grouping.

However, that said...

for some uses, having it 'all on one screen' is really helpful.

A good example if my .bashrc file which had got to 3 or 4 'screens worth' and was leading to more:

duplication for same settings

conflicting uses of same settings

forgetting what settings do

So in this case, I went to a lot of effort to 'compact' it down.  In this case not just whitespace but making if then constructs fit on 1 line, e.g.

test -f ~/.bash_aliases && . $_

and was able to get it down to 27 lines which I can see all at once, even in a small terminal window, i.e.

Finally, the two issues you mention - file size and padding length are not factors that any programmers I know and respect would pay attention to - remember 100GB is a hundred thousand million bytes.  Extra line spaces would just be considered to be your preference for line space.  If the code actually worked this would usually be a relatively minor issue, though with a team, one that should be agreed on.


答:
Is too much whitespace a bad thing?

Clearly:Yes. If you say, it is too much, then it is a sign, for something smelly going on.

I often add a line break almost after every line and large blocks of whitespace, often 3 or 4 lines because it helps me see what I've written and understand what I've written when I look back on it at a later time. I also think it just looks cleaner.

Your problem is not whitespace, your problem is clean code or better: a lack of clean code.

One lesson clean code teaches us is: breaking down large code blocks into smaller ones. I bet, every block you wrap in whitespache is a block, which could be chopped up into small handy pieces.

Try it with paranoia: Every function greater than 10 lines has to be broken up into smaller chunks. And in case you are writing OO: every class longer than 200 lines is too large.

Of course 10/200 lines is an arbitrary number, but if you follow this rule for a while, you will notice the effects: a) you won't have whitespace blocks anymore b) your code gets more compact, readable and better to understand, and in the end: maintainable.

Although I can see two issues with this, 1) It can increase the file size of the source files, even just a line break every two or three lines can add up in a long file. I know that a good compiler will optimize all the white space out (I'm not actually sure, I think LLVM/Clang does this) but the source file is still large.

Why worring about filesize? We do not live in the 80ies and store everything on tape. We are in the age of Big Data. That is the wrong concern. And if you break up your blocks into readable chunks, the number of files and the size will increase. But don't worry.

And 2) it may cause some people to think I'm embellishing my code to make it look longer and "bigger" to make others think I'm doing more work than I actually am (consider 3000 lines vs. 6000 lines, 3000 being newlines). Which I am not doing that by the way. Is using too much whitespace bad from a technical standpoint and/or a professional standpoint?

That is also a wrong concern. If you are measured by the LoC or the bytesize of your output, quit your job. Code should be measured in quality not quantity.

Title: Is too much whitespace a bad thing?


问:
Which Java based web ui framework to use?

Wicket

Click

GWT

Vaadin

As I understand them, these frameworks all enable gui components to be created using java (with all its benefits) without having to do lots of html/javascript.

As well as considering the technical factors, I am also interested to hear if any are gaining popularity fast. Is a particular framework is becoming the leader of the pack, this will also effect the decision.

答:
1.)  Have a look at Matt Raible's comparison chart and then as he advises - take a hefty grain of salt to go with it.  In particular have a look at the different types of requirements (functional and non-functional) that he measures.  Which of those are more important to you?

2.)  Pick 2-3 that seem to fit your requirements best and prototype some pages/UI/Ux/workflow with those.  Probably spend 2-3 days on each as a minimum (1 week if you can get away with it)

Then decide :)

ContentLicense: CC BY-SA 2.5


问:
Should each method have a separate JUnit test class?
I am writing JUnit unit tests for my classes.

Is it better to have a separate class for each method, or have just one test class for every actual class?

答:
To your specific question, the JUnit convention, is to have a 1:1 correspondence between your application classes (Foo1.java, Foo2.java) and JUnit test classes (Foo1Test.java, Foo2Test.java).

That said, I agree wholeheartedly with Kilian's highlighting of the importance of the spirit/goals of unit testing over any organizational schemes that might be used. Pick some conventions and stick with them most of the time, while guardedly allowing exceptions to your conventions, when they're warranted.

ContentLicense: CC BY-SA 4.0


答:
Is it better to have a separate class for each method, or have just one test class for every actual class?

If you have the need to write separate test classes for methods of one class, then you have the wrong design. Methods should be small, easy to read, easy to test and easy to change. The tests could be a bit longer than the original code due to making up testdata, mocking etc., but should not be significantly longer. If they are, your class under test is too complex and does for sure more than one thing (single responsibility principle): Work on your design.

Title: Should each method have a separate JUnit test class?

Body:
I am writing JUnit unit tests for my classes.

Is it better to have a separate class for each method, or have just one test class for every actual class?


问:
Implementing distributed Semaphore for AWS workload
We have a messaging gateway in AWS (Amazon Cloud) that comprises of a number of nodes (Linux servers) responsible for receiving, routing, despatching and escalating messages (emails, SMS' and voice calls). They all talk to a backend MySQL database on a dedicated machine.

Every few minutes we run a maintenance script - escalating stale messages, etc.

The problem is that we shouldn't run the maintenance on multiple nodes at the same time - hence I want to implement some sort of Distributed Semaphore that would be raised by the first node and if any other node attempts to run the script before the first one finishes it should simply exit. At the moment we run the script only on one node and have the cron job disabled on the others, but we prefer to have all the nodes with the same configuration.

On a single host I would probably use a lock file but how do I do that across multiple hosts? They don't have a shared filesystem and pretty much the only thing they share is the MySQL database. Also - if the process or node dies halfway through the processing the semaphore should eventually release or time out.

I prefer to use the database as the Semaphore holder but am also quite happy to use any other AWS service.

FWIW The script is written in Python. Not that I think it matters...

Thanks for any ideas!

答:
If you want that only one machine at a time do something you can have a token and only the machine that "have" this token can launch the process. When a machine finish the process pass the token to other machine (randomly, round robin, to the machine who have less load...).

you can pass this token via AWS or store in the database. One problem to this approach its that the machine who holds the token crash and never pass the token to others. Perhaps you need something to recover this errors, distributed system are very complex things.

And precisely for this complexity, are you sure yo need something like that?, you can have one machine with the rol "maintenance_scripts_runner" and only this machine executes the script.


问:
How does your team approach technical code QA?
For the first time, our team is taking a rigorous approach to technical code QA.  We identify work to QA by picking out top level classes and QA'ing it and everything it calls or uses below it (and what they call/use etc.).  I reckon our QA code coverage to be reasonably close to 100% and its an eye opener for me in terms of improvements both in code and design as well as catching bugs early.  I'll definetly be promoting this in the future, but wondered how other teams approach techincal code QA.  Do you have a rigorous approach?  Do you aim to QA everything?  Does one or two people tend to do it or is it spread evenly about the team?  What do you look for when QA'ing?  Any thoughts appreciated!</p>

答:
There's a couple of things we try to do:

1.)  Code reviews can be too late.  How about some pair/peer design, peer/pair programming to begin with?!

2.)  Use static code tool analysis tools and checkstyle tools to get rid of the distracting fluff before you review what's really important.  Much like reviewing an article in English, if there's a ton of spelling and grammar issues, then it's hard to review the real content.

3.)  Come up with some agreed broad idioms that you want your code to follow, e.g:

Code to interfaces

SRP (Single Responsibility Principle)

No re-inventing the wheel

Dependency Injection of Factory lookups

That way you can build up a list of neutrally worded design code standards that you try to adhere to.

4.)  Be darn sure to make it an encouraging and neutrally worded environment, you're playing with people's fragile egos here :)

"I like the concept and I think we can improve it by X" is better than "That's just plain wrong.".

Good luck!


问:
Can GC.SuppressFinalize cause performance problems?
I'm being asked to implement IDisposable on objects that are 100% managed resources, which contain no streams, and no large resources.

I understand the importance of properly disposing of large resources and unmanaged resources, but what about the other side of the equation?

For an object that doesn't benefit from implementing IDisposable (small fully managed objects), what negative impact can GC.SuppressFinalize have, if any?

答:
The only goal of GC.SuppressFinalize is:

to prevent the finalizer from releasing unmanaged resources that have already been freed by the IDisposable.Dispose implementation.

Source: MSDN

Once you disposed the object, you should indeed call GC.SuppressFinalize(this);, like shown in an answer to the question "When should I use GC.SuppressFinalize()?". Code analysis' CA1816 rule is also useful as well.

Now, implementing IDisposable on objects which don't have unmanaged resources looks quite weird and questionable. Since the only reason the person gave you was: "its just the way we've always done it, you do it too", instead of providing profiling/benchmarking data which shows that adding IDisposable will improve something in a specific case, there are no actual reasons to do it.

Would it cause performance problems? Difficult to say: it would depend on particular case.

Would it cause any other problems? Of course. Not counting the fact that IDisposable is painful to implement, if this practice is used too much, the code becomes unreadable and impossible to maintain:

```<code>public int ComputePrice(Rebate rebate)
{
    using (var currentCurrency = this.User.FindCurrency())
    {
        using (var priceWithoutRebate = this.GetPurePrice())
        {
            using (var canApplyRebate = rebate.CanApplyTo(this))
            {
                if (!canApplyRebate)
                {
                    return priceWithoutRebate;
                }

                using (var priceWithRebate = priceWithoutRebate.Apply(rebate))
                {
                    return priceWithRebate;
                }
            }
        }
    }
}
</code>```

Body:
The only goal of GC.SuppressFinalize is:

to prevent the finalizer from releasing unmanaged resources that have already been freed by the IDisposable.Dispose implementation.

Source: MSDN

Once you disposed the object, you should indeed call GC.SuppressFinalize(this);, like shown in an answer to the question "When should I use GC.SuppressFinalize()?". Code analysis' CA1816 rule is also useful as well.

Now, implementing IDisposable on objects which don't have unmanaged resources looks quite weird and questionable. Since the only reason the person gave you was: "its just the way we've always done it, you do it too", instead of providing profiling/benchmarking data which shows that adding IDisposable will improve something in a specific case, there are no actual reasons to do it.

Would it cause performance problems? Difficult to say: it would depend on particular case.

Would it cause any other problems? Of course. Not counting the fact that IDisposable is painful to implement, if this practice is used too much, the code becomes unreadable and impossible to maintain:

public int ComputePrice(Rebate rebate)
{
    using (var currentCurrency = this.User.FindCurrency())
    {
        using (var priceWithoutRebate = this.GetPurePrice())
        {
            using (var canApplyRebate = rebate.CanApplyTo(this))
            {
                if (!canApplyRebate)
                {
                    return priceWithoutRebate;
                }

                using (var priceWithRebate = priceWithoutRebate.Apply(rebate))
                {
                    return priceWithRebate;
                }
            }
        }
    }
}


问:
What should I do and know before I start writing C?
I have a college degree in CS, and learned about Java and OCaml. Java was used as introduction, and in most CS classed, except the theoretical ones. OCaml was part of learning a different programming paradigm. Since OCaml wasn't a successful entry in my CV, I became a better Java programmer. Also, most jobs are for Java programmers. Later on I learned Golang.

I know about the simplifications provided by Java, i.e. garbage collection. I also know, that C doesn't do garbage collection and you have to know when to allocate and when to free the memory. But during my education I was never taught to think in this kind of way. We never learned algorithms in the aspect of memory. I feel like I missed something.

So my question is, how deep do I have to dig, before I can start writing passable C code, without having myself put obstacles in my way, because of my own crufty code and deep misunderstanding of relevant issues?

答:
Passable code in any language demonstrates know-how in how the language can be used to write readable code in the large and small. Which of course takes practice! Specifically I'd expect you to know how to:

Break down code into modular chunks

Write code that's idiomatic for that language

The standard library for this language

Know what libraries exist for common tasks

Best practices for writing libraries

Build systems if applicable

How to do automated testing of your code

Specifically for C, I'd expect knowledge of:

Pointers

How an array is a pointer is an array (sort of)

How a C string is a special kind of array that needs special care

Manual Memory allocation (and most importantly deallocation) -- and idioms for management thereof

How the stack works vs how the heap works (value vs reference based semantics)

Comfort building/using your own data structures

Probably comfort with the platform you're writing on (posix, or whatever syscalls you care about)

But you want be able to do any of this unless you write really bad code for a really long time and make lots of mistakes! See also Norvig: Teach Yourself Programming in Ten Years.


答:
There is a very long answer above, I will give a short one.

I started in Java too and then started c for a good base for the rest of my programming career.

It doesn't take too long to start writing good code. Luckily I had a professor to help me.

Most important

Pointers pointers pointers

**allocating and freeing up memory **

After you get a good grasp of those concepts you should be able to take off running.

Title: What should I do and know before I start writing C?

Body:
I have a college degree in CS, and learned about Java and OCaml. Java was used as introduction, and in most CS classed, except the theoretical ones. OCaml was part of learning a different programming paradigm. Since OCaml wasn't a successful entry in my CV, I became a better Java programmer. Also, most jobs are for Java programmers. Later on I learned Golang.

I know about the simplifications provided by Java, i.e. garbage collection. I also know, that C doesn't do garbage collection and you have to know when to allocate and when to free the memory. But during my education I was never taught to think in this kind of way. We never learned algorithms in the aspect of memory. I feel like I missed something.

So my question is, how deep do I have to dig, before I can start writing passable C code, without having myself put obstacles in my way, because of my own crufty code and deep misunderstanding of relevant issues?


问:
Server should accumulate several requests and to retrurn response for all
For example I have a server [c#] and 4 clients. When the first client sends a request to the server I want to push a notification to the other 3 clients that they should send a request to the server with some required data. After I receive requests from all clients I want to send the same response to all of them.

What is the best way/pattern to implement something like this?

答:
Since WCF supports two-way communications, this is technically possible. When client C1 sends a request through the channel, the server sends the requests to C2, C3 and C4 and waits until those clients respond. Once all four responded, the server sends the final response.

But are you sure you want to do that?

It doesn't seem you gain anything compared to more ordinary communication patterns.

If you think that you gain bandwidth, you're not (you'll even waste a lot doing all the additional requests and responses).

If you think that the server footprint will be reduced by avoiding to generate the same response to multiple clients again and again, this is a false assumption as well: it will increase (again, because of those additional requests and responses). Caching, on the other hand, will be more appropriate.

The drawback is that if any of the four clients is down, the other ones will never receive the response.


答: This sort of scheme would require two-way communication between the server and it's clients. One straightforward approach would be to use the WebSocket protocol, but applications running on the .NET platform might benefit from SignalR.</p>

Title: Server should accumulate several requests and to retrurn response for all

Body:
For example I have a server [c#] and 4 clients. When the first client sends a request to the server I want to push a notification to the other 3 clients that they should send a request to the server with some required data. After I receive requests from all clients I want to send the same response to all of them.

What is the best way/pattern to implement something like this?


答:
If you haven't done so already, read "The C Programming Language" and work through the examples. I learned C by way of this book (coming from FORTRAN). Since you are already aware of the issues and pitfalls of C-style memory management, you're already off to a good start.

A programming principal you should always follow is to never leave a "dangling" pointer (a pointer which refers to de-allocated memory) - always initialize pointers to null, and when memory is freed, always set the associated pointer to null. A check for null can then be used as a test for whether memory has been allocated.

To make it easier to avoid dangling pointers, another principal is symmetry. In object-oriented programming (C++, for example) it is expressed as: he who allocates memory is responsible for freeing it. This is typically implemented in classes such that each method which "new"s an object has a counterpart method in the same class responsible for "delete"ing that which was "new"d.

In C, the principle is obeyed by implementing function pairs where allocated memory is used; for each function which performs allocation(s), there should be another function which performs "cleanup" - freeing the allocated memory.


答:
When it comes to whitespace, file size and compile performance should be of no concern, and whitespace should have no effect on compiler output.

It's all about readability, but readability of a given sample will be different for different readers.

As has been stated in other answers, too much vertical whitespace has the effect of lifting bits of code out of context, which can impair understanding when that context is necessary to proper understanding. I will generally never separate anything by more than one blank line - enough to set off a bit of code without sacrificing context. I worked with a developer who insisted upon four blank lines between functions. He found it helpful for readability, I felt was excessive, contributed nothing to readability and that it hampered navigation.

If you are working in a team, you should have a style guide and work to that (whether home-brewed or something more widely distributed); presumably it will accommodate the majority of the readers who will have to work with that code.

Title: Is too much whitespace a bad thing?


问:
In plain English, what is recursion?
The idea of recursion is not very common in real world. So, it seems a bit confusing to the novice programmers. Though, I guess, they become used to the concept gradually. So, what can be a nice explanation for them to grasp the idea easily?</p>

答:
Recursive programming is the process of progressively reducing a problem in to easier to solve versions of itself.

Every recursive function tends to:

take a list to process, or some other structure, or problem domain

deal with the current point/step

call itself on the remainder(s)/subdomain(s)

combine or use the results of the subdomain work

When step 2 is before 3, and when step 4 is trivial (a concatenation, sum, or nothing) this enables tail recursion.  Step 2 often must come after step 3, as the results from the subdomain(s) of the problem may be needed in order to complete the current step.

Take the traversal of a straight forward binary tree.  The traversal can be made in pre-order, in-order, or post-order, depending on what is required.

```<code>   B
A     C
</code>```

Pre-order: B A C

```<code>traverse(tree):
    visit the node
    traverse(left)
    traverse(right)
</code>```

In-order: A B C

```<code>traverse(tree):
    traverse(left)
    visit the node
    traverse(right)
</code>```

Post-order: A C B

```<code>traverse(tree):
    traverse(left)
    traverse(right)
    visit the node
</code>```

Very many recursive problems are specific cases of a map operation, or a fold - understanding just these two operations can lead to significant understanding of good use-cases for recursion.

Title: In plain English, what is recursion?

Body:
Recursive programming is the process of progressively reducing a problem in to easier to solve versions of itself.

Every recursive function tends to:

take a list to process, or some other structure, or problem domain

deal with the current point/step

call itself on the remainder(s)/subdomain(s)

combine or use the results of the subdomain work

When step 2 is before 3, and when step 4 is trivial (a concatenation, sum, or nothing) this enables tail recursion.  Step 2 often must come after step 3, as the results from the subdomain(s) of the problem may be needed in order to complete the current step.

Take the traversal of a straight forward binary tree.  The traversal can be made in pre-order, in-order, or post-order, depending on what is required.

   B
A     C

Pre-order: B A C

traverse(tree):
    visit the node
    traverse(left)
    traverse(right)

In-order: A B C

traverse(tree):
    traverse(left)
    visit the node
    traverse(right)

Post-order: A C B

traverse(tree):
    traverse(left)
    traverse(right)
    visit the node

Very many recursive problems are specific cases of a map operation, or a fold - understanding just these two operations can lead to significant understanding of good use-cases for recursion.


答:
I think learn C is a good idea, because many language is based on C, understand how memory works can be only good, and sometimes make C for solve problem can be useful. </p>

<p>The good first way you can make, it's read the C programming language, some give very solid knowledge. After you can find a cool free software write in C and contribute. </p>

Body:
I think learn C is a good idea, because many language is based on C, understand how memory works can be only good, and sometimes make C for solve problem can be useful.

The good first way you can make, it's read the C programming language, some give very solid knowledge. After you can find a cool free software write in C and contribute.


问:
Implementing keyword "const"
A constant pointer is a pointer which points to a fixed memory location throughout.The question is how do you ensure that this behavior is ensured without using the keyword constant while declaring the pointer in a C program.</p>

答:
In C, const isn't "implemented".  It's a message to the compiler about whether to generate errors.  gcc compiles this:

```<code>const char *cp = "Hello";
</code>```

to

```<code>.section    __TEXT,__cstring,cstring_literals
</code>```

L_.str:                                 ## @.str
    .asciz   "Hello"

```<code>.section    __DATA,__data
.globl  _cp                     ## @cp
.align  3
</code>```

and this:

```<code>char *cp = "Hello";
</code>```

to the exact same this:

```<code>.section    __TEXT,__cstring,cstring_literals
</code>```

L_.str:                                 ## @.str
    .asciz   "Hello"

```<code>.section    __DATA,__data
.globl  _cp                     ## @cp
.align  3
</code>```

Title: Implementing keyword "const"

Body:
In C, const isn't "implemented".  It's a message to the compiler about whether to generate errors.  gcc compiles this:

const char *cp = "Hello";

to

.section    __TEXT,__cstring,cstring_literals

L_.str:                                 ## @.str
    .asciz   "Hello"

.section    __DATA,__data
.globl  _cp                     ## @cp
.align  3

and this:

char *cp = "Hello";

to the exact same this:

.section    __TEXT,__cstring,cstring_literals

L_.str:                                 ## @.str
    .asciz   "Hello"

.section    __DATA,__data
.globl  _cp                     ## @cp
.align  3


问:
Why to declare a String (as final) and then use it?
In a typical spring mvc validator class, while inserting an errorCode value in the Errors object, what difference does it make between using a String (props.somefield.req) like so

```<code>errors.rejectValue("elementId", "props.somefield.req");
</code>```

verses a declared static final String ?

```<code>private static final String SOMFIELD_REQ = "props.somefield.req"; ...
errors.rejectValue("elementId", SOMFIELD_REQ);
</code>```

Does it improve the performance even in a slightest way? I have read a few questions on stack overflow (String and final, Does it make sense to define a final String in Java?) but no one got around to answering this questions update question.

答:
final fields have many benefits!

Declaring fields as final has valuable documentation benefits for developers who want to use or extend your class - not only does it help explain how the class works, but it enlists the compiler's help in enforcing your design decisions. Unlike with final methods, declaring a final field helps the optimizer make better optimization decisions, because if the compiler knows the field's value will not change, it can safely cache the value in a register. final fields also provide an extra level of safety by having the compiler enforce that a field is read-only.

Don't try to use final as a performance management tool. There are much better, less constraining ways to enhance your program's performance. Use final where it reflects the fundamental semantics of your program: to indicate that classes are intended to be immutable or that fields are intended to be read-only.

Before declare final fields, you should ask yourself: does this field really need to be mutable?


问:
Scrum vs. Agile vs. CMMI
I am pushing my project over to Visual Studio Online in order to have some source control. I am developing this project by myself. I have never used Scrum, Agile, nor CMMI before, and the detailed description I read at http://msdn.microsoft.com/library/vstudio/ms400752.aspx is assuming a lot of knowledge. (It makes no sense to someone who doesn't already know what they are talking about.)

The best way for me to really learn Scrim or Agile or CMMI is by using them. But where to start? The above link does not help me there.

As a solo developer who is just looking for source control, should I start off with Scrum, Agile, or CMMI?

To take the opinion-basedness out of this question, I will make my official question: What is the difference between Scrum, Agile, and CMMI in Layman's terms? (But really, I just am trying to figure out where to start!)

答:
All of them are software development processes.

Scrum is very collaborative you discuss with your team constantly so everyone can be aware of what's happening. Helps to deal with problems efficiently as a team.

Agile can be many things. But when I have experienced it it has been very fast development with iterations. So you get the product working then incrementally make it better. Quickly so you can get feedback before taking the next step.

I haven't heard CMMI too much

Title: Scrum vs. Agile vs. CMMI


问:
How to handle duplicate files in version control
Right now we use a very simple system for version control.  We have a completely flat master repository for our entire product line.  As our codebase grows and we add more products to the product line, this starts to present some serious drawbacks.  We'd like to move away from this, especially with out flat style, but there are seemingly fundamental problems with a structured approach, so it'd be great to hear how other people handle these common situations:

Your code's got multiple duplicate files in separate locations.  For example, you have:

```<code>./somedir/source1.c
./someotherdir/source1.c
</code>```

All instances of source1.c are the same, so when someone changes source1.c, they shouldn't have to make the same change to every source1.c in each location where it exists.  This is kind of where a flat system works, but it means the structure (with somedir and someotherdir have to be created to create the correct file structure.

On the other hand, if you have something like this:

```<code>./somedir/config
./someotherdir/config
</code>```

where both instances of config are unique, and they only share a filename.  This presents a big problem in a flat system, you end up doing something like keeping them in a flat repository with unique names, and then renaming them as you recreate the product structure.  It seems like this is where a structured file system would make things easier, because there would be no inherent relationship between ./somedir/config and ./someotherdir/config.

Maybe I am approaching this with a fundamentally bad idea of standard idioms, but as I'm sure you are all aware, when you are making big changes to an existing codebase, it has to be more of a transition than a throw-everything-away-and-start-over situation.

答:
My experience is with CVS and laterly Subversion, so someone else will need to cover the more modern distributed systems like Git and Mecurial.

Your first question (source.c) is probably better fixed by putting common code into libraries, then linking the libraries into multiple products. That way there is only a single source file to change. SVN does provide a facility that will make a file appear in multiple places in the source tree, but if you plan to bring Continuous integration and automated compile/release into the picture, the cross-couplings become difficult to understand and manage. I much prefer the library approach.

The question about config is not be a problem. To my knowledge all source code control systems use the fully-qualified path to identify the file, so your two files are definitely stored in different places.


答:
There are approaches within svn (and another approach).  Other tools such as git will handle a symbolic link (and more info).  It is fairly common for various version control systems to have some way of handling symbolic links (perforce, hg as two more).

At this point it becomes a question of how you want to structure your code.

All that said, I'm going to put forth at the start that doing symbolic links or the like is often the wrong answer.  While you still have a single copy of the file that is the source of all, it is too easy to mangle the link (someone copies an older version of the file on top of it) and make someone's day in the future unhappy.

You have an object file of some sort.  Rather than copying the source (<s>or heaven forbid #include "../foo/bar.c</s> forget that I wrote that.  Just forget it for your own good.  You didn't see it.) link against the object file.

You've got .../common/source1.c and that produces .../common/source1.o and when you link, its something like cc foo.o bar.o qux.o ${PROJECT_ROOT}/common/source1.o and you're good.  Don't copy source1.c into the directory with foo, bar, and qux because you don't need it - there are better and more elegant ways of handling this.

If you are in a Java world, make the utils or commons (or whatever you name it) a separate project and let it be a dependency of those that need it.  Similar for Go, or Python, or other languages that have a dependency management build tool.

So - keep unique files unique.  Copying files into multiple locations violates DRY and will eventually come back to bite you hard.  Symbolic links are better, but you have to be disciplined to use them and not clobber them with actual files.  Link in the common libraries when you need to - but they are their own project (if they're a proper project).

Title: How to handle duplicate files in version control

Body:
Right now we use a very simple system for version control.  We have a completely flat master repository for our entire product line.  As our codebase grows and we add more products to the product line, this starts to present some serious drawbacks.  We'd like to move away from this, especially with out flat style, but there are seemingly fundamental problems with a structured approach, so it'd be great to hear how other people handle these common situations:

Your code's got multiple duplicate files in separate locations.  For example, you have:

```<code>./somedir/source1.c
./someotherdir/source1.c
</code>```

All instances of source1.c are the same, so when someone changes source1.c, they shouldn't have to make the same change to every source1.c in each location where it exists.  This is kind of where a flat system works, but it means the structure (with somedir and someotherdir have to be created to create the correct file structure.

On the other hand, if you have something like this:

```<code>./somedir/config
./someotherdir/config
</code>```

where both instances of config are unique, and they only share a filename.  This presents a big problem in a flat system, you end up doing something like keeping them in a flat repository with unique names, and then renaming them as you recreate the product structure.  It seems like this is where a structured file system would make things easier, because there would be no inherent relationship between ./somedir/config and ./someotherdir/config.

Maybe I am approaching this with a fundamentally bad idea of standard idioms, but as I'm sure you are all aware, when you are making big changes to an existing codebase, it has to be more of a transition than a throw-everything-away-and-start-over situation.


答:
(Just FYI - I am cofounder of a company (Digité) that builds and sells enterprise software to a variety of technology organizations, so I have some background on these topics :-) )

Agile and Scrum are related, in that they are software development methods. Agile is an umbrella term for specific methods such as Scrum, Extreme Programming (XP) and others.

CMMI, on the other hand, is a quality management framework useful for large organizations that need to measure themselves in terms of their overall capability and maturity to demonstrate repeatable quality of software work they do.  Organizations can use a mix of software development methods - Agile methods (such as Scrum/ Kanban/ XP/ BDD/ TDD/ etc), 'traditional' methods (Waterfall, Iterative) or a mix (Hybrid Agile), depending on their business needs. They can still use CMMI as an overall governance framework to measure and develop their software capabilities.

Definitely, as a solo developer, you don't need to worry about CMMI!

Agile methods in general give you the ability to build your software with less risk, greater chances of success and early warnings that what you are developing may not be the right product (as I am sure you know, it is not only important to build your product right - but also to build the right product). Even if you are a solo developer, you must have other people you (need to) interact with, especially your customer(s). Agile methods such as Scrum or Kanban give you the ability to deliver to them working software more often (in sprints of every 2-3 weeks),  get their feedback more often, and take corrective steps more often than otherwise. Kanban helps you do it even more continuously.  I'd recommend the following books, if you have not read any others so far -

Scrum - The Power of Scrum - by Jeff Sutherland

Kanban - Successful Evolutionary Change for your Technology Organization - by David Anderson. (If you need a basic introduction to Kanban, you can look here - What is Kanban?)

To answer your final question, I would recommend starting with Kanban.  My assumption is that you already have some process you follow to build and deliver software to your customers. Kanban will help you map your existing process, help you "visualize" it - and help in delivering more often/ more continuously. And make improvements in your process to help you become more agile overall. If you do want something more formal and structured, you should adopt Scrum. It may require greater effort up-front - but don't worry too much about it's formal structures, instead focus on its fundamental intent of delivering working software  more often to your customer.

Hope this helps.

Cheers!

Title: Scrum vs. Agile vs. CMMI

Body:
I am pushing my project over to Visual Studio Online in order to have some source control. I am developing this project by myself. I have never used Scrum, Agile, nor CMMI before, and the detailed description I read at http://msdn.microsoft.com/library/vstudio/ms400752.aspx is assuming a lot of knowledge. (It makes no sense to someone who doesn't already know what they are talking about.)

The best way for me to really learn Scrim or Agile or CMMI is by using them. But where to start? The above link does not help me there.

As a solo developer who is just looking for source control, should I start off with Scrum, Agile, or CMMI?

To take the opinion-basedness out of this question, I will make my official question: What is the difference between Scrum, Agile, and CMMI in Layman's terms? (But really, I just am trying to figure out where to start!)


问:
Which management book would you recommend to read for a fresh Team Leader?
Which management book would you recommend to read for a fresh Team Leader?</p>

答:
Rapid Development by Steve McConnell.

The reason I go for this over PeopleWare is that there are a few more things in here you might actually be able to implement as a team leader.  When you're a team leader (with the lack of clout that normally comes with) much of PeopleWare is largely aspirational as you're not going to be able to significantly influence working environment, salaries and recruitment and so on.

I guess it depends on whether you're looking for something on development process or on management and leadership though.  While I've not read it I like the look of The First 90 Days which someone has recommended.  Alternatively I quite like The One Minute Manager though plenty have issues with it (largely that it's told as a story and that it's content is obvious - which I agree with but we frequently miss the obvious so reminding ourselves from time to time is no bad thing and whatever you think of it it is at least very short).


问:
Queue of jobs in a different states and with different services around
I need to design a 'queue' of jobs (in a a very much UI oriented application) that can be run by a user and I need some other thoughts to pick optimal approach from ground up.

My jobs can be in a different states (imported, sent from elswhere, created by user, even to be just simulated with their imported recorded progress - following a whola different workflow), etc.

Therefore they can also pass thru the different states of their lifecycle, like being created, running, paused, validated or edited by a user (in case of invalid job parameters), imported or even in the process of being deleted (at least for logging or auditing).

Because of this, all jobs have to have their state at each point of time and they need to be managed somehow by a common logic.

There are also domain and application rules, that only one can be running/stopped/params edited in a time state, etc...

My main question is, whether to implement some kind of monolithic singleton controller for all states where it can answer state guards of each one of them (can/cant transition to other state) for all states and can call actions (other services) upon them, or whether to implement state machines inside of the jobs themselves and somehow call the services and related conditional logic from themselves (delete me/ edit me and so on).

I also need to tie this tightly to the UI, so that I have a list of tasks with the states visible for the user but I also have the separation of the concerns (job itself as a domain object of parameters - not states, UI).

This is just a brief description of my main problem, so I might update the requirements as suggestion or more questions that I forgot to address arrive.

答:
I'd have a BaseJob class which will contain basic/shared properties and functionality. It can be an abstract class or just a plain base class, depending on the situation. If all jobs and states have similar behavior the base class can act as a controller and be abstract.

I'd also have State in each Job or may be the BaseJob can expect some sort of BaseState or GenericState. The State can contain the logic for next state or might even call some service for that, but you isolate that logic in that object.

For UI you'll need some sort of viewmodel anyway I'd think, it'll keep your business layer isolated, and contain the more UI/MVVM related concerns.


问:
What is the best practice for designing a system supporting many languages, 1 central dictionary for all languages or seperated dictionary?
I want to build a system which uses dictionary of many different language.

There are 2 options: Build 1 central dictionary Table & each language is identified by langType (ex 1 for German & 0 for English):

```
CentralDict
word - meaning - langType
car  - ....    - 0
auto - ....    - 1
```

or 2 separated Tables

```
EngDict
word - meaning
car  - ....

GerDict
word - meaning
auto - ....
```

If the option is 2, then when do the coding

```<code>String DictTable="";
String locale=getLocale();
if ("gm".locale){
   DictTable="GerDict";
}
else if("en".locale){
   DictTable="EngDict";
}
</code>```

Then when we query from

```<code>String sql="select * from "+DictTable;
//access data from table here
</code>```

If option 1 is selected,

```<code>    int langType=0;
    String locale=getLocale();
    if ("gm".locale){
       langType=1;
    }
    else if("en".locale){
       langType=0;
    }
    String sql="select * from CentralDict where langType="+langType;
    //access data from table here
</code>```

I am guessing the 2 option is more elegant, but not sure I am right?

With option 2 we can create a 1 to 1 relationship between 2 languages easily.

Note: It is not the internationalization issue as my system can handle internationalization very well. While internalization deals with text of the Gui like the text of the button or the message info, it does not deal with the data that was pulled out from DB.

My Dictionary System helps user to see the explanation terms such as "car", "phone".... for teaching purpose.

Currently, it works fine in English language, but I want to support German & many be French or any other languages in the future. I don't know whether I should create a complete separated table for each language or I just need 1 centralized dictionary for all languages & has a langType field for identifying the language that need to be used based on the user requirement. Ex: WHen user enters mydomain.com/locale=de then the system will show the exact Gui ( as in English) but all the text of the Gui will be in German. Also when user searches for data , it should pull out the German data from DB. not English data.

答:
If you know what language you want before the lookup, it's going to be faster to search one small language-specific table than a huge universal table with lots of languages.

Option 2 gets my vote!


答:
What is the actual issue you want to solve? What is your application doing? On which operating system?

If it is a matter of internationalization, e.g. adapting your software to give messages in various human languages, most operating systems provide a framework for that. On Linux and Posix systems, you can use the locale(7) infrastructure.

If you goal is natural language processing (e.g. adapting your software to somehow "understand" various human languages inputs) there are many techniques (and libraries) for that (and NLP is a complex and difficult field, so start reading many books and/or follow some university courses). AFAIK the techniques might depend on the actual human language, because of the diversity of written human languages : some are syllabic, some are alphabetic, some use pictographs, some have cases and genders, and some languages don't even have the notion of verb as in Indo-European languages (English, French, Russian being the one I know ...).

Title: What is the best practice for designing a system supporting many languages, 1 central dictionary for all languages or seperated dictionary?

Body:
I want to build a system which uses dictionary of many different language.

There are 2 options: Build 1 central dictionary Table & each language is identified by langType (ex 1 for German & 0 for English):

```
CentralDict
word - meaning - langType
car  - ....    - 0
auto - ....    - 1
```

or 2 separated Tables

```
EngDict
word - meaning
car  - ....

GerDict
word - meaning
auto - ....
```

If the option is 2, then when do the coding

```<code>String DictTable="";
String locale=getLocale();
if ("gm".locale){
   DictTable="GerDict";
}
else if("en".locale){
   DictTable="EngDict";
}
</code>```

Then when we query from

```<code>String sql="select * from "+DictTable;
//access data from table here
</code>```

If option 1 is selected,

```<code>    int langType=0;
    String locale=getLocale();
    if ("gm".locale){
       langType=1;
    }
    else if("en".locale){
       langType=0;
    }
    String sql="select * from CentralDict where langType="+langType;
    //access data from table here
</code>```

I am guessing the 2 option is more elegant, but not sure I am right?

With option 2 we can create a 1 to 1 relationship between 2 languages easily.

Note: It is not the internationalization issue as my system can handle internationalization very well. While internalization deals with text of the Gui like the text of the button or the message info, it does not deal with the data that was pulled out from DB.

My Dictionary System helps user to see the explanation terms such as "car", "phone".... for teaching purpose.

Currently, it works fine in English language, but I want to support German & many be French or any other languages in the future. I don't know whether I should create a complete separated table for each language or I just need 1 centralized dictionary for all languages & has a langType field for identifying the language that need to be used based on the user requirement. Ex: WHen user enters mydomain.com/locale=de then the system will show the exact Gui ( as in English) but all the text of the Gui will be in German. Also when user searches for data , it should pull out the German data from DB. not English data.


问:
Should temporary code be put under version control and how?
Here are some examples of temporary/local code. It is needed in order to work with the codebase, but would be harmful to be part of it:

Project files. Paths may need to be edited in order to reflect the layout on the current PC.

Makefiles. For example optimization may need to be turned off during debugging, but not for the CI server.

Dirty ugly hacks. For example return 7 in the middle of a function, in order to test something, depending on the function, and suspected to break at value of 7. Or 7 is the code of the not yet implemented button, that I am implementing and need to test throughout the life of my branch.

I have tried keeping those in a git commit that I always rebase to the top before pushing to the repo and then push HEAD~. This is quite inconvenient and doesn't work with svn. Stashing scares me even more - "did I remember to pop after pushing??".

Keeping the code out of version control introduces unpleasant noise everytime a commit is being assembled plus it might accidentally get introduced into a commit some friday evening.

What would be a sane solution for such throw-away code?

答:
It is never harmful to put code in source control.

Every single one of the items you mention should be in source control.


问:
Java and rest OOP languages - when to use super or this keywords
I have been programming java for like a year or more, and i have always used the this and super keywords.

And yesterday my mate read one source of mine, and told me not to over use it unless you are overriding the method.

```<code>class A extends JPanel {
     public A {
         super.setSize(400, 400);// instead of not using super keyword
     }
}
</code>```

But what he meant on how to use it, is this:

```<code>class A extends JPanel {
    public A {
        super.setSize(4,4);
    }

    public void setSize(int a, int b) {}
}
</code>```

So the language will know that your constructor calls the parent method and not local.

Should i only use the the keywords in this situation only or use the keywords everywhere for better readibly?

I know that this keyword is returning the whole local instance including the parent and all of its parents and interfaces.

And the super keyword returns the instance of the parent class and all of its instances (parents and interfaces).

But my question is, should you always use these keywords?

答:
You need to be aware of all the special cases where it is compulsory to use super or this. You described one of those corner cases - overridden functions. You will learn more special cases as you go on.

Other than those specific cases, using this and super is a matter of preference. They produce the same machine code, and so they are exactly the same as far as the machine is concerned. However, they differ in terms of their readability to a person.

It is important to pick one style and use it consistently. By this, I mean not just you, but your entire team. Everyone decides on one way of doing things and sticks to it. This makes it easy to understand the team's code. This is called a "coding standard".

Check if there are any published coding guidelines or coding standards set by the company or the team. If yes, just follow them. Otherwise, see what the rest of the team normally uses. You may want to discuss this with your team to officially decide on a standard.


问:
Creating menu structure using DB - is that fine?
I have an application that basically consists of a lot of screen so user needs to navigate a lot (like go from A>B>C>D) etc.

I have been thinking how to implement this (mainly hold the structure of the menu) as it needs to be on-screen menu (custom, no menu strips etc.) and did not find any solution.

Now I realized I could use a database for that, which would allow me also to change strings later with no impact.

My idea would be to have a table for each level (1-5) with options available. Once the user selects an option, the program will select any items in the table (CurrentLevel+1) based on its ID. Seems really a good solution to me but I am not a programmer (rather than an analyst).

Or even I could use specific table names and hold the table name in a specific column, for example:

User selects Settings

Program checks that with Settings, there is a table associated "SETTINGS" and query this table for all items available

Does this make sense?

答:
Your menu is essentially a tree, so could be stored in a single database table:

```<code>ID (number, not null)
PARENT_ID (number, can be null)
DESCRIPTION (text)
</code>```

where PARENT_ID is null for top-level menu items.

You might need one or more additional columns to hold the behaviour you want to associate with the menu items (e.g. an action ID, command name or URL).

Body:
Your menu is essentially a tree, so could be stored in a single database table:

ID (number, not null)
PARENT_ID (number, can be null)
DESCRIPTION (text)

where PARENT_ID is null for top-level menu items.

You might need one or more additional columns to hold the behaviour you want to associate with the menu items (e.g. an action ID, command name or URL).


问:
Rest API Architecture from Rest in Practice book
We maintain an API that as part of its purpose makes a call to an external API. This external API takes a few seconds to fulfil the request we make to it. With our current architecture the request is made synchronously, meaning that the http response we return to the user request is blocked until our service get the response from the external API.

I am considering changing our architecture to be able to deal with the request asynchronously... By this I mean accept the user request into our API and put a message on a queue so that we return an http response a lot quicker. The response would contain the address of where the full/complete result can be found. A background task would then pick messages up from the queue and make the call to the external API, then store the result at the address provided in our response. The address could then be polled by the user/client until the desired state of the respource is reached (i.e. when the background task has finished calling the external api and has stored the result).

This architecture I have mainly lifted from the REST in Practice book. The crux however is that our external API only takes 2-3 seconds to return the response. The example in the book describes an ordering process that might take minutes or hours. Is this suggested solution worth the increase in complexity for such a short response time from our external dependency? i.e. will the application still scale with the existing synchronous architecture?

答:
The situation you're describing (using queues and polling) will definitely work, but as long as your external API takes only a few seconds to return a response, I think there's an easier way:

As you described, it's a good idea to have your webpage response not include the data from the external API, because this allows the page response to be sent more quickly. I would make the call to the External API as follows:

The response page contains a piece of javascript that makes an asynchronous AJAX call to a REST endpoint on your website.

Your REST endpoint calls the external API, and just blocks until it receives the response. Once it receives the response, it returns the results to the caller (i.e. the browser that executed the AJAX call).

When the response page javascript receives the data from the AJAX call, it displayes the results by manipulating the HTML DOM of the response page.

This way, the only thing that needs to be async is the AJAX call from the browser; this effectively starts a new 'background thread', and the calls that are run in this thread (from browser, to your REST endpoint, to external API, and then back again) can all be executed synchronously.

Obviously, this only works as long as the external API returns its responses fast enough (under a minute or so), otherwise the synchronous calls will time out. As long as you're confident that this is the case, I think this solution is less complicated while still meeting your requirements.


答: The best example that I would point you to is C Programming Language by K & R. In that book (and I am quoting from memory), the entry in index page for recursion (alone) lists the actual page where they talk about recursion and the index page as well. </p>

Title: In plain English, what is recursion?

Body: The idea of recursion is not very common in real world. So, it seems a bit confusing to the novice programmers. Though, I guess, they become used to the concept gradually. So, what can be a nice explanation for them to grasp the idea easily?</p>


答:
Holding configuration data like this externally to the application code is quite common.  Since you have to persist this information somewhere a RDBMS is as good as anywhere, especially if the application is using the DB for "real" data already.

Having five tables for your putative five levels of menus is not a good idea.  It is inflexible and you can reasonably expect this to change within the life of the system.

There are a number of ways to store linked sets of data in a relational structure.  I found this post after a brief search.  It discusses several possibilities.  It will at least give you the vocabulary to research more thoroughly.  The one which best suits your circumstances will depend on the number of rows you wish to store, the rate at which they change and the programming skill of your team.

Title: Creating menu structure using DB - is that fine?

Body:
I have an application that basically consists of a lot of screen so user needs to navigate a lot (like go from A>B>C>D) etc.

I have been thinking how to implement this (mainly hold the structure of the menu) as it needs to be on-screen menu (custom, no menu strips etc.) and did not find any solution.

Now I realized I could use a database for that, which would allow me also to change strings later with no impact.

My idea would be to have a table for each level (1-5) with options available. Once the user selects an option, the program will select any items in the table (CurrentLevel+1) based on its ID. Seems really a good solution to me but I am not a programmer (rather than an analyst).

Or even I could use specific table names and hold the table name in a specific column, for example:

User selects Settings

Program checks that with Settings, there is a table associated "SETTINGS" and query this table for all items available

Does this make sense?


问:
the perils of using eval() for dynamic object creation -- is this a valid argument in a consenting-adults culture?
I've read on stackoverflow explicit warnings against using eval() to create objects.  The reason that seems to be given is that malicious code could be injected and blindly created objects could compromise a system.  Isn't this malicious-intent argument invalidated by the consenting-adult argument, though?

Some sample code:

```<code>class Test(object):
    def __init__(self, vala, valb, valc):
        self._vala = vala
        self._valb = valb
        self._valc = valc

    def __repr__(self):
        return "<Test(vala={0}, valb={1}, valc={2})>".format(self._vala, self._valb, self._valc)

testlist = [dict(cls="Test", vala="this is vala", valb="this is valb", valc="this is valc"), dict(cls="Test", vala="this is vala II", valb="this is valb II", valc="this is valc II")]

mytestobjects = []

for test in testlist:
    newobj = eval(test['cls'])(**{key: value for key, value in test.items() if key != "cls"})
    mytestobjects.append(newobj)

print(mytestobjects)
</code>```

答:
You should have some idea about who will use your software and how.

If you are sure that your code will always be used by "good people" - e.g. if your code is some internal in-house development which will never interact with outside people (or sources), then the consenting adults argument is valid.
But then you should document -at the very least in some comments- your design choice (i.e. state that bad input would trigger the dreaded undefined behavior, and that input is supposed to be good and valid).

If on the contrary you might believe that your code will eventually work with some data gotten from the internet (or from a server connected on the Internet), you should be aware that because of many various (social and cultural and human) factors, bad people willing to spend time and effort to break in exist.

BTW look at how some current internet technologies exist, eg. email. In the beginning of SMTP, Internet was mostly an academic (and also military) thing - with a strong culture of "good network behavior".
Today we are getting billions of SPAM because it is no longer the case

See bobby-tables! Beware of code injection...


问:
Problem : Certificate for multi Clients of WCF

If My WCF service have big number of clients through the
Internet,then whether should all of them share the same Client
Certificate(X509)?

And if their certificates should be unique , what should I do on the
WCF to identify all the certificates?

Last question: Must I import the server-side certificate  into
TrustedPeople location on every Client ? (Which seems to be
troublesome and any way convenient?  )

答:
I am assuming a WCF service hosted on IIS using HTTPS with client certificate.

This depends on your requirements. If you want to use the client cert to identify any valid client for your service then no. If you want to authorise each client individually then yes. Is your client for B2B scenario then you may have to use individual certificate for each client.

If hosting on IIS as long as the client cert is installed in Trusted People it should just work. For self hosting a custom certificate validator class can be implemented to do thus

This is not required if the cet is issued by a trusted certification authority e.g. Verisign. Otherwise I think you can use a Base64 encoded value of the cert in endpoint identity element as shown here http://msdn.microsoft.com/en-us/library/ms733130(v=vs.110).aspx


问:
Generally speaking, is it better to make all the functional parts or get UI working first - or a mix of the two?
Generally speaking, is it better to make all the functional parts or get UI working first - or a mix of the two?

Assuming you're working on something large, is it generally accepted practice to get all the functional data harvesting blobs working before any UI, get all the UI working one piece at a time as you go, or something in the middle?

We all know to break work down in to manageable pieces, but the question is ultimately whether UI is included in manageable pieces I suppose.

For the case of the example, consider a GUI application with one root window, but over a dozen tabs in various docks to separate different data components.  Each individual tab has a relatively complex set of moving parts behind it from a functional units perspective.

The example application in this particular question is here with the accompanying blog and the original commercial product.

答:
I would recommend making a mixture of both functionality and UI (and getting feedback or testing experience ASAP).

BTW, isn't it the way that most large GUI software is developed? Look for example into the Firefox browser: from one version to the next both functionality and user interface have evolved.


答:
It depends: You need a tight feedback loop around your most important piece of functionality

If the core of what you do, the risky and scary part, is some internal engine, then get the core part working in say the console or through unit testing. For example, a protocol parser doesn't need a UI to know whether its operating correctly.

If your cool thing involves any interactivity -- interactivity you need to be constantly troubleshooting, throwing away, and rediscovering -- then a UI-first approach is crucial. For example, I want to build an app to let people interact with a data visualization. The most important thing I need to figure out is if the visualization is meaningful, so I'll likely throw away a half-dozen approaches before settling on one. I'll do this all before writing a single unit test.

There's a fuzzy gray area in between where you get to decide the best combination on how to best interact and validate your code (automated tests? UI for experimentation?). I've personally done both extremes and everything in between, and deciding the right place to be on that spectrum is one of the hardest things I have to decide and is 100% dependent on the type of thing I'm building.

Body:
Generally speaking, is it better to make all the functional parts or get UI working first - or a mix of the two?

Assuming you're working on something large, is it generally accepted practice to get all the functional data harvesting blobs working before any UI, get all the UI working one piece at a time as you go, or something in the middle?

We all know to break work down in to manageable pieces, but the question is ultimately whether UI is included in manageable pieces I suppose.

For the case of the example, consider a GUI application with one root window, but over a dozen tabs in various docks to separate different data components.  Each individual tab has a relatively complex set of moving parts behind it from a functional units perspective.

The example application in this particular question is here with the accompanying blog and the original commercial product.