答:
What you seem to be caught in is the specific hell of someone trying to have their cake and eat it too.

RAII and exceptions are designed to go hand in hand. RAII is the means by which you do not have to write a lot of catch(...) statements to do cleanup. It will happen automatically, as a matter of course. And exceptions are the only way to work with RAII objects, because constructors can only succeed or throw (or put the object in an error state, but who wants that?).

A catch statement can do one of two things: handle an error or exceptional circumstance, or do cleanup work. Sometimes it does both, but every catch statement exists to do at least one of these.

catch(...) is incapable of doing proper exception handling. You don't know what the exception is; you can't get information about the exception. You have absolutely no information other than the fact that an exception was thrown by something within a certain code block. The only legitimate thing you can do in such a block is to do cleanup. And that means re-throwing the exception at the end of the cleanup.

What RAII gives you with regard to exception handling is free cleanup. If everything is RAII encapsulated properly, then everything will be properly cleaned up. You no longer need to have catch statements do cleanup. In which case, there is no reason to write a catch(...) statement.

So I would agree that catch(...) is mostly evil... provisionally.

That provision being proper use of RAII. Because without it, you need to be able to do certain cleanup. There's no getting around it; you have to be able to do cleanup work. You need to be able to ensure that throwing an exception will leave the code in a reasonable state. And catch(...) is a vital tool in doing so.

You cannot have one without the other. You cannot say that both RAII and catch(...) are bad. You need at least one of these; otherwise, you're not exception safe.

Of course, there's one valid-though-rare use of catch(...) that not even RAII can banish: getting an exception_ptr to forward to someone else. Typically through a promise/future or similar interface.

My coworkers says that you should always know what exceptions are to be thrown and that you can always use constructs like:

Your coworker is an idiot (or just terribly ignorant). This should be immediately obvious due to how much copy-and-paste code he's suggesting that you write. The cleanup for each of those catch statements will be exactly the same. That's a maintenance nightmare, not to mention readability.

In short: this is the problem that RAII was created to solve (not that it doesn't solve other problems).

What confuses me about this notion is that it's generally backwards to how most people argue that RAII is bad. Generally, the argument goes "RAII is bad because you have to use exceptions to signal constructor failure. But you can't throw exceptions, because it's not safe and you'll have to have lots of catch statements to clean everything up." Which is a broken argument because RAII solves the problem that the lack of RAII creates.

More than likely, he's against RAII because it hides details. Destructor calls aren't immediately visible on automatic variables. So you get code that gets called implicitly. Some programmers really hate that. Apparently, to the point where they think having 3 catch statements, all of which do the same thing with copy-and-paste code is a better idea.

OwnerDisplayName: Nicol Bolas


问:
Is `catch(...) { throw; }` a bad practice?
While I agree that catching ... without rethrowing is indeed wrong, I however believe that using constructs like this:

```<code>try
{
  // Stuff
}
catch (...)
{
  // Some cleanup
  throw;
}
</code>```

Is acceptable in cases where RAII is not applicable. (Please, don't ask... not everybody in my company likes object-oriented programming and RAII is often seen as "useless school stuff"...)

My coworkers says that you should always know what exceptions are to be thrown and that you can always use constructs like:

```<code>try
{
  // Stuff
}
catch (exception_type1&)
{
  // Some cleanup
  throw;
}
catch (exception_type2&)
{
  // Some cleanup
  throw;
}
catch (exception_type3&)
{
  // Some cleanup
  throw;
}
</code>```

Is there a well admited good practice regarding these situations?

答:
I generally agree with the mood of the posts here, I really dislike the pattern of catching specific exceptions--I think that the syntax of this is still in it's infancy and not able to cope with the redundant code yet.

But since everyone is saying that, I'll pipe in with the fact that even though I use them sparingly I've often looked at one of my "catch(Exception e)" statements and said "Damn, I wish I'd called out the specific exceptions that time" because when you come in later it's often nice to know what the intention was and what the client is likely to throw at a glance.

I'm not justifying the attitude of "Always use x", just saying that occasionally it actually is nice to see them listed out and I'm sure that's why some people think it's the "Right" way to go.

OwnerDisplayName: ereOn

ContentLicense: CC BY-SA 3.0

OwnerDisplayName: Bill K


问:
What hurts maintainability?
For someone who doesn't have much real world experience yet, the notion of maintainable code is a bit vague, even though it follows from typical good practice rules. Intuitively I can tell that code can be well written, but not maintainable if for example it hard-wires information that is subject to constant change, but I still have a hard time looking at code and deciding if it's maintainable or not.

So the question is: what hurts maintainability? What should I look for?

答:
besides the mentioned patterns one of the most important things is

readable code, every single line of code you put in a codebase will be read 100+ times and as people are tracking down bugs you do not want them spend 30 minutes to try and figure out what it does each time.

So don't try to be clever with "optimized" code unless it really is a bottleneck and then comment it and put the original readable (and working) code in comments (or alternative compilation path for testing) as a reference for what it should do.

this includes descriptive function, parameter and variable names and comments explaining WHY a certain algorithm is chosen over another

Title: What hurts maintainability?


问:
Does simplicity always improve Readability?
Recently, I was developing a set of coding standards for our company.  (We're a new team branching out into a new language for the company.)

On my first draft, I set the purpose of our coding standards as improving Readability, Maintainability, Reliability, and Performance.  (I ignored writability, portability, cost, compatibility with previous standards, etc.)

One of my goals while writing this document was to push through the idea of simplicity of code. The idea was that there should be only one function call or operation per line.  My hope was that this would increase readability.  It's an idea that I carried over from our previous language.

However, I've questioned the assumption behind this push:

Does simplicity always improve readability?

Is there a case where writing simpler code decreases readability?

It should be obvious, but by "simpler", I don't mean "easier to write", but less stuff going on per line.

答:
Always? - NO

Ironically, attaining the right level of simplicity can be a complex undertaking. I think the key is in moderation.  Simplicity can also be in the eye of the beholder, so if you find yourself over-thinking it - just leave it alone or come back to it later.

Personally, when I try to go back and simplify something that I've written I focus on areas where I changed my mind or tried a couple of things to get what I wanted.  Those areas can usually be smoothed out.  Then just make a couple of passes through the code to make it more readable without spreading things out so much that you're jumping all over the place to figure out what's happening on a debug.


答:
Does simplicity always improve readability?

No. I have seen plenty of cases where doing multiple simpler things on one line is less complex than having multiple lines.

There is a tradeoff between less code and simpler code.

In general, I would recommend going for simpler code unless you're sure doing it in fewer lines is better. I would much rather have "too verbose" code over "too complex" code.

Title: Does simplicity always improve Readability?

Body:
Recently, I was developing a set of coding standards for our company.  (We're a new team branching out into a new language for the company.)

On my first draft, I set the purpose of our coding standards as improving Readability, Maintainability, Reliability, and Performance.  (I ignored writability, portability, cost, compatibility with previous standards, etc.)

One of my goals while writing this document was to push through the idea of simplicity of code. The idea was that there should be only one function call or operation per line.  My hope was that this would increase readability.  It's an idea that I carried over from our previous language.

However, I've questioned the assumption behind this push:

Does simplicity always improve readability?

Is there a case where writing simpler code decreases readability?

It should be obvious, but by "simpler", I don't mean "easier to write", but less stuff going on per line.

ContentLicense: CC BY-SA 4.0


答:
If your coding standard is about "Readability, Maintainability, Reliability, and Performance" then just state that.

Don't try and prescribe how to achieve these things as there will always be situations where there is a counter example.

What you do need to prescribe is things that will cause code to break if not adhered too. Stylistic traits will not break code and should be suggestions (as long as a majority of the team agree that it is Readability the rest should be developer preference (with code review so that peer pressure reminds people that other people need to read the code)).


答:
"Make things as simple as possible, but no simpler" - An often paraphrase of Albert Einstein

Simplicity improves everything. For differing values of simplicity, of course. Is it less lines of code? Maybe. Is it a smaller executable? Possibly. Is it something your team needs to agree upon? Absolutely.


答:
Less "stuff per line", simplicity, and readability are not the same thing.  One can take an incredibly complicated obscure undocumented algorithm and code it with 1 statement per line instead of 2, and it won't become that much more readable.

Less "stuff per line" also might require supplying developers with great big tall monitors to see code blocks now spread out more vertically.  Or cause eye strain from reading tinier fonts.

Readability is it's very own metric, which often requires a compromise among several other more easily measurable metrics.  Pre-constrain all those other metrics, and the compromise no longer becomes possible, resulting in less readable code.


问:
What Part of Your Project Should be in Source Code Control?
A fellow developer has started work on a new Drupal project, and the sysadmin has suggested that they should only put the sites/default subdirectory in source control, because it "will make updates easily scriptable."  Setting aside that somewhat dubious claim, it raises another question -- what files should be under source control?  And is there a situation where some large chunk of files should be excluded?

My opinion is that the entire tree for the project should be under control, and this would be true for a Drupal project, rails, or anything else. This seems like a no-brainer -- you clearly need versioning for your framework as much as you do for any custom code you write.

That said, I would love to get other opinions on this.  Are there any arguments for not having everything under control?

答:
I highly recommend unto you the following book which addresses your concerns:

Continuous Delivery: Reliable Software Releases through Build, Test, and Deployment Automation.  Specifically, Chapter 2 addresses items to be placed into source control, which as quite a few folks have said, is practically everything except mostly generated content as a result of a build.

I do not agree with one piece of the accepted answer provided by @FrustratedWithFormsDesigner less because he advocates not placing into version control the tools necessary to build the project.  Somewhere in source control (adjacent to the code being built) should be the build scripts to build the project and build scripts that run from a command line only.  If by tools he means, IDEs and editors, they should not be required to build the project whatsoever.  These are good for active/rapid development for developers and setup of this type of environment could be scripted as well or downloaded out of another section of SCM or from some type of binary management server and setup up such IDEs should be as automated as possible.

I also disagree with what @Yannis Rizos states about placing configurations for environments in source control.  Reason being is that you should be able to reconstruct any environment at will using nothing but scripts and it is not manageable without having configuration settings in source control. There is also no history of how configurations for various environments have evolved without placing this information into source control.  Now, production environment settings may be confidential or companies may not want to place these in version control, so a second option is to still place them in version control so that they have a history, and give this repository limited access.


答:
"Simple" is an overused word. "Readable" can profitably be defined as "simple to understand", in which case increasing (this measure of) simplicity by definition increases readability, but I don't think this is what you mean. I've written about this elsewhere, but generally something can be called "simpler" either by being more abstract (in which case fewer concepts can express more phenomena) or by being more concrete (in which case a concept does not require as much background knowledge to understand in the first place). I'm arguing that, depending on perspective, a more abstract concept can reasonably be called simpler than a more concrete concept, or vice versa. This, even though "abstract" and "concrete" are antonyms.

I'll use as an example some Haskell code I wrote a while ago. I asked a question on stackoverflow about using the List monad to calculate a counter in which each digit could have a different base. My eventual solution (not knowing much Haskell) looked like:

```<code>count :: [Integer] -> [[Integer]]
count [] = [[]]
count (x:xs) =
  -- get all possible sequences for the remaining digits
  let
    remDigits :: [[Integer]]
    remDigits = count xs
  in
  -- pull out a possible sequence for the remaining digits
  do nextDigits <- remDigits
     -- pull out all possible values for the current digit
     y <- [0..x]
     -- record that "current digit" : "remaining digits" is
     -- a valid output.
     return (y:nextDigits)
</code>```

One of the answers reduced this to:

```<code>count = mapM (enumFromTo 0)
</code>```

Which of these is "simpler" to understand (i.e. more readable) depends entirely on how comfortable the reader has become with (abstract) monadic operations (and, for that matter, point-free code). A reader who's very comfortable with these abstract concepts will prefer to read the (short) more abstract version, while one who is not comfortable with those operations will prefer to read the (long) more concrete version. There is no one answer about which version is more readable that will hold for everybody.

Body:
"Simple" is an overused word. "Readable" can profitably be defined as "simple to understand", in which case increasing (this measure of) simplicity by definition increases readability, but I don't think this is what you mean. I've written about this elsewhere, but generally something can be called "simpler" either by being more abstract (in which case fewer concepts can express more phenomena) or by being more concrete (in which case a concept does not require as much background knowledge to understand in the first place). I'm arguing that, depending on perspective, a more abstract concept can reasonably be called simpler than a more concrete concept, or vice versa. This, even though "abstract" and "concrete" are antonyms.

I'll use as an example some Haskell code I wrote a while ago. I asked a question on stackoverflow about using the List monad to calculate a counter in which each digit could have a different base. My eventual solution (not knowing much Haskell) looked like:

count :: [Integer] -> [[Integer]]
count [] = [[]]
count (x:xs) =
  -- get all possible sequences for the remaining digits
  let
    remDigits :: [[Integer]]
    remDigits = count xs
  in
  -- pull out a possible sequence for the remaining digits
  do nextDigits <- remDigits
     -- pull out all possible values for the current digit
     y <- [0..x]
     -- record that "current digit" : "remaining digits" is
     -- a valid output.
     return (y:nextDigits)

One of the answers reduced this to:

count = mapM (enumFromTo 0)

Which of these is "simpler" to understand (i.e. more readable) depends entirely on how comfortable the reader has become with (abstract) monadic operations (and, for that matter, point-free code). A reader who's very comfortable with these abstract concepts will prefer to read the (short) more abstract version, while one who is not comfortable with those operations will prefer to read the (long) more concrete version. There is no one answer about which version is more readable that will hold for everybody.


问:
How to tackle massive Linux/makefile projects effectively?
I have been developing Windows applications in C++ for like 10 years now. And recently I've started digging into some Linux projects, and I can't stand how unproductive I am...

I'm a fast learner, and I've been using Linux as a primary platform for some time now. And I do feel very comfortable with shell, OS principles and GUI. But when it comes to development, it feels like I'm back to school.

As soon as I open some larger project, I'm stuck. Most of them are makefile based, so basically when I try to navigate them with QT or CodeBlocks, at best, I can use intellisense on a per-file basis. And most of the time variables leak from scope.

Then there is a go-to-definition stuff, which seems nonexistent, try to join some larger project from sourceforge, and you're stuck for days, because navigating to definitions is so hard... grep -r "this_def" . --include "*.cpp" --include "*.h" seems so slow and clumsy.

And then, the debugging, gdb does work, but no matter what I do, it seems like it's light years behind WinDbg or VisualStudio debugger.

And these things are making me desperate, I want to write code, but it just goes so slow... I'm starting to think that Linux developers learn function definitions by heart and analyze code by eyes, but I can't believe it's so.

Has anyone gone through this? Is there something that I'm missing that could make me more productive?

答:
Your problem has been solved many times in the Linux world, however, unlike the Windows/Microsoft tools, it will not be handed to on a silver plate with a side dish of extras. You might need to do some work to get it.

I use a commercial editor (Visual Slick Edit, which is considered expensive by those that do not value their time as much as I do) for this exact problem. Eclipse with the CDT plugin are an open source way to go that has justifiable vast following. (No good for me as I often need ADA support)

What I do not do it try to reverse engineer the makefiles into some kind of project. I use the IDE's build in systems and manually add/remove files as needed. I am sure I could script it up, but the time is probably not worth it. For this I found eclipse a bit less usable than Slickedit (That could easily (and probably has) have changed since i last looked)

Linux has a vast array of tools, guys that know vi well out-perform me in all aspects of editing, it has references lookups etc, just a steep learning curve. I am certain Emacs can do it all as well, although have never used it.


问:
What is meant by "Now you have two problems"?
There is a popular quote by Jamie Zawinski:

Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.

How is this quote supposed to be understood?

答:
The meaning has two parts:

First, you didn't solve the original problem.

This probably refers to the fact that regular expressions often offer incomplete solutions to common problems.

Second, you now added additional difficulty associated with the solution you've picked.

In the case of regular expressions, the additional difficulty probably refers to complexity, maintainability, or the additional difficulty associated with making regular expressions fit a problem it wasn't supposed to solve.


答:
Interestingly enough I periodically have the same problem in the opposite direction. I'm primarily a UNIX coder, but I periodically have to port stuff to Windows. I can't tell you the number of times I've wanted to pull my hair out because I can't find the appropriate check box for a compiler option buried in one of 35 preference setting pages for a project. I'd rather just open up the  proj file and add the XML myself.

Moving in either direction, the secret is to have patience, and learn the tool set for the platform you are trying to work in. Of course you are going to be frustrated, it's new, and it's unfamiliar, and you are reduced to newbie status all over again. There is no way to avoid this.

In your particular case there are some additional tools you should be aware of. The first is DDD, a GUI front end for gdb. It's not as slick as Visual Studio, but it will hold your hand. However, I'd really recommend biting the bullet, and set about learning the ins and outs of gdb. In truth, if you are a regular user, there isn't a lot of difference between memorizing which commands to type vs memorizing which dialog box you have to bring up to change a setting.

You also need to know about tools like CScope and CTags. As much you may resist, I would suggest learning VIM or EMACS. They integrate well with tag tools I just mentioned. When in Rome, do as the Romans do. You can find extensions for VIM and EMACS that will do code completion for you. My own experience with tools that offer code completion is is that yes, it does saving some typing, but in general typing is easy. Thinking is what's hard. Your opinion may differ, particularly if you have carpal tunnel syndrome.

As for make. Make is admittedly horrible, but you probably just going to have to suck it up and learn it.

Title: How to tackle massive Linux/makefile projects effectively?

Body:
I have been developing Windows applications in C++ for like 10 years now. And recently I've started digging into some Linux projects, and I can't stand how unproductive I am...

I'm a fast learner, and I've been using Linux as a primary platform for some time now. And I do feel very comfortable with shell, OS principles and GUI. But when it comes to development, it feels like I'm back to school.

As soon as I open some larger project, I'm stuck. Most of them are makefile based, so basically when I try to navigate them with QT or CodeBlocks, at best, I can use intellisense on a per-file basis. And most of the time variables leak from scope.

Then there is a go-to-definition stuff, which seems nonexistent, try to join some larger project from sourceforge, and you're stuck for days, because navigating to definitions is so hard... grep -r "this_def" . --include "*.cpp" --include "*.h" seems so slow and clumsy.

And then, the debugging, gdb does work, but no matter what I do, it seems like it's light years behind WinDbg or VisualStudio debugger.

And these things are making me desperate, I want to write code, but it just goes so slow... I'm starting to think that Linux developers learn function definitions by heart and analyze code by eyes, but I can't believe it's so.

Has anyone gone through this? Is there something that I'm missing that could make me more productive?


答:
I have been developing Windows applications in C++ for like 10 years now. And recently I've started digging into some Linux projects, and I
  can't stand how unproductive I am...

Is there something that I'm missing that could make me more productive?

Develop on Windows, deploy on Linux.

This includes running unit tests both on your own (Windows) machine, and on the build server (Linux).

As a side effect, you'll learn how to write portable code.

Another positive effect is that using different compilers will generate more warnings and thus catch more bugs.

UPDATE: To all the Linux fanboys downvoting this answer: I don't say that everyone should develop on Windows! But using the platform you know very well is more productive than spending a lot of time on learning a new platform.


答:
Always? - YES

Attaining the right level of simplicity is a complex and difficult undertaking. But always worthwhile since it always improves readability.   I think the key is deep understanding. Simplicity is an absolute, measured by "new concepts" per "chunk" of code.  A few new concepts means simpler.

Focus on areas where there are a dense cluster of concepts and find ways to "chunk" or "summarize" or "abstract".  Make a couple of passes through the code to make it simpler and more readable.

A good abstraction is worth it's weight in gold.  A good abstraction makes this simpler -- and consequently more readable.


答:
Clarity + Standards + Code Re-use + Good Comments + Good Design  could improve readability.

Simplicity is not always in the hand of the developer because the nature of algorithms and the complexity of application structure these days.

Take the simple web pages that perform simple tasks. Given a sort routine, it is not possible to simplify the logic, but you can make it clearer with comments, using meaningful variable names, having it written in a structured manner, etc.


问:
Window Position on Startup
Here's a question for me that really makes me wonder every time I start designing and developing a thick-client desktop application.

I'm a .NET developer, and with my forms (WinForms mostly, but the platform should be unimportant) I also choose the startup position to be Center.  The reason I do this is because I can't stand randomness, and as a user myself I don't like when windows jump all over my monitor.

So my question for you, is what is the best way to go about this?  Center an application startup window or have it randomly placed?  And why?

答:
Did you think about allowing user to configure it? Maybe its the best approach, so each user could have a more satisfiying experience.

Give them options about where they would like windows to appear (upper/bottom right/left corner or center).

Title: Window Position on Startup


问:
Definition of mixing programming idioms?
Say I have class that is partially implemented as a static class and partially implemented as a singleton.

Besides "kludge" and "code-smell" (imo this is both) is there a more appropriate term for this type of mixing programming idioms?

答: The time honored tradition is to name this type of error after the programmer that made it, and then refer to similar errors with that name until you find someone worse.  :-)</p>


问:
Where is the M in MVC?
I'm trying to refactor my application into MVC, but I'm stuck on the M part.

In a database-backed app, the model is implemented in the app code, right?

But then, what is in the database -- is that not also the model?

(I'm not using the database as a simple object store -- the data in the DB is an enterprise asset).

答: I think the M contain some logic and store data into DB. The controller invoke which module would be execute and this module will execute logics and store data in DB(May be has persisent layer) and then this module return value to V.</p>

Title: Where is the M in MVC?


答:
What I like to do is save the last size and position of the application window (at app shutdown) as a user setting.  Then when the application is restarted I restore the last used size and position.

If you do this, be careful of using the spurious settings you'll get if the app is minimized at the time it is shut down (e.g. by a forced shutdown).

If I don't have a user setting to go by, I like to centre the window horizontally and then vertically I like it about 1/3 of the way down from the top.  This has a nicer feel to it than dead centre vertically.  Purely an asthetic choice on my part.

Title: Window Position on Startup

Body:
Here's a question for me that really makes me wonder every time I start designing and developing a thick-client desktop application.

I'm a .NET developer, and with my forms (WinForms mostly, but the platform should be unimportant) I also choose the startup position to be Center.  The reason I do this is because I can't stand randomness, and as a user myself I don't like when windows jump all over my monitor.

So my question for you, is what is the best way to go about this?  Center an application startup window or have it randomly placed?  And why?


答: You can initially put it in the center, but I prefer it to stay where I left it. That's the easiest way to remember where things are. I don't consider this random. I don't see how center is less random than upper-left. They can both be seen as arbitrary.</p>

Title: Window Position on Startup


问:
How to choose a language, when taking in account the community it includes?
I was reading the following article: Great Hackers

The following part grabbed my attention:

"When you choose a language, you're also choosing a community. The programmers you'll be able to hire to work on a Java project won't be as smart as the ones you could get to work on a project written in Python. And the quality of your hackers probably matters more than the language you choose. Though, frankly, the fact that good hackers prefer Python to Java should tell you something about the relative merits of those languages."

I would like to apply his advice on a commercial web application I am building (I am a strong believer in culture and community), yet this article was written in 2004, and python has increased in popularity in the recent years.

How can I decided a language when taking in consideration its community, rather than the popularity? Any recommendations?

Is there any language community that show dedication and passion for developing, rather than learning a language to get a Job and a paycheck?

答: Hire the best programmer you can find and after they understand what your web application needs to do, let them pick the language. If you need to find more programmers that understand the language of choice, this person should be able to find them.</p>


答:
If I go for simplicity, I can write code like this:

```<code>10000000000000000000000000000000000000000000
</code>```

But if I go for readability, I will prefer this:

```<code>1e43
</code>```

On the other hand, 1000 is much more readable and simple than 1e3 unless you work with numbers in scientific notation all the time.

This is a degenerate example of much more general pattern you can find almost anywhere -- building something out of very simple blocks can quickly become unreadable/inefficient/bad in a lot of different ways. Generalizing and reusing, on the other hand, is harder at first ("wtf is e?! did they mean to write 1343?" someone might say), but can help a lot in the long run.

Body:
If I go for simplicity, I can write code like this:

10000000000000000000000000000000000000000000

But if I go for readability, I will prefer this:

1e43

On the other hand, 1000 is much more readable and simple than 1e3 unless you work with numbers in scientific notation all the time.

This is a degenerate example of much more general pattern you can find almost anywhere -- building something out of very simple blocks can quickly become unreadable/inefficient/bad in a lot of different ways. Generalizing and reusing, on the other hand, is harder at first ("wtf is e?! did they mean to write 1343?" someone might say), but can help a lot in the long run.


答:
While "community" is important, I think you should look at the language used in your problem "domain". Utilities bill using COBOL, geologists analyze seismic results using fortran, Quants game the market using C++, bankers hold on to your money using a combination of COBOL and Java etc. etc.

For web applications its overwhelmingly php or Java. A small (but growing) percentage of web applications use Python; maps.yahoo.com being the poster child, but there are very few exmaples of top ranking/famous name sites developed completely in Python!

So this makes it a tough decision. I myself have recently taken the plunge and decided that I will use "web2py" for any development (assuming I have a choice!). This is after several years of doing serious stuff in J2EE and lesser tasks in PHP. I just plain hate the overkill inherent in all the Java APIs along with the sheer tedium of the coding involved, I actually like developing in "php" but there is always a "flared trousers and Hawaiian" shirts feel about it -- its fast, it works but its not elegant.

With Python one of the difficulties is choosing your framework Zope, cherrypy, pylons etc all have very different design philosophies and a Zope hacker cannot help you with your Pylons problems. So pick the framework that suits and you will find a small community of excellent hackers to help you out, which is probably better than a Superbowl of full of amateur php coders.

Title: How to choose a language, when taking in account the community it includes?

Body:
I was reading the following article: Great Hackers

The following part grabbed my attention:

"When you choose a language, you're also choosing a community. The programmers you'll be able to hire to work on a Java project won't be as smart as the ones you could get to work on a project written in Python. And the quality of your hackers probably matters more than the language you choose. Though, frankly, the fact that good hackers prefer Python to Java should tell you something about the relative merits of those languages."

I would like to apply his advice on a commercial web application I am building (I am a strong believer in culture and community), yet this article was written in 2004, and python has increased in popularity in the recent years.

How can I decided a language when taking in consideration its community, rather than the popularity? Any recommendations?

Is there any language community that show dedication and passion for developing, rather than learning a language to get a Job and a paycheck?


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

Here's what I wanted to accomplish:

For full applications:

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

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

can be included into commercial projects without modifications

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

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

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

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

Update:

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

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

答:
Whether you can actually apply for MPL or only GPL depends on one critical difference:

The "rights hereunder" include the right granted to recipients to link
  MPL "Covered Code" with private non-MPL code to form a "Larger Work"
  (MPL 3.7 Larger Works). GPL does not give recipients any such right.
  Therefore, the recipient cannot change the licensing terms to apply
  the GPL instead of MPL.

See this.

What this means for you is that if you are using any component which itself is GPL'ed, you (probably) cannot release code (which is using this) under MPL; MPL will wrongly attempt to allow redistribute GPL'ed code under MPL which is improper. This is fine, if your dependencies are in the order of MIT or Apache license.

In general, if you are not doing any better by choosing MPL over GPL alone unless you are already using MPL stuff. GPL will also ensures that contributions will be made published back as well.

There is only critical change MPL provides is the protection against the unknowingly induced patent infringements. As the license puts it:

It is not OK for someone to create a Modification for which he or she
  has a patent, make the Modification available free of charge as
  required under the License, and then come back and try to charge
  everyone for the patent rights.

MPL and GPL are not quite compatible.

You can see here: MIT vs. BSD vs. Dual License for discussion on implication of dual licenses.

ContentLicense: CC BY-SA 2.5


答:
Paul Graham usually says some pretty insightful things, but the specific advice in this quote regarding the quality of programmers you hire is rubbish - you can usually find great programmers in any sufficiently large community. Remember, if you are hiring intelligently you will hire from among the best not the average from your target group so the level of average ability is irrelevant.

Even if there are a lot of bad Java programmers, I doubt you'll find any difference between the best Java programmers or the best Python programmers. In fact, I suspect you'll find more truly great programmers in the Java community just because of sheer community size. For example, the Google Code Jam statistics show the top finalists choosing C++ and Java as the two most common languages over the past few years.

Anyway, if you are after a language with a great community I'd recommend checking out Clojure.

It's a Lisp. Lisps are a good place for great hackers (I agree with Paul Graham on this one!)

The mindset is "pragmatic" and "get things done" - you won't see any NIH attitudes, the tendency is to embrace different approaches.

The community is constantly innovating - seems to be a new library or tool announcement every couple of days. Nearly all of this is open source on GitHub.

It's production ready - since it's a JVM langauge, the underlying platform is extremely robust and you get all the production-quality Java libraries and tooling for free. This is a massive win over other languages that don't have access to this kind of ecosystem, and as a result there are plenty of startups choosing Clojure.

Very active IRC channel, Google Groups, development site etc.

Perhaps most importantly, the people in the community are passionate about what they do and always willing to help newcomers - the linked story is a touching example.


答: This is one webpage that resumes pretty well what you're looking for (it just presents a classification without any backup explained, but I think is still a good resource)... just search for the question that contains the word "community" in there http://therighttool.hammerprinciple.com/browse  </p>


答:
While there is truth in what Paul Graham said. However, it is more important to realize is that Hackers is not what you always want!

Before i see people fuming on such a statement, let me tell you what my interpretation of the word. For a simple example you can see The International Obfuscated C Code Contest. You will see a great many folks who are greatly talented to solve serious puzzles. However, there are times when you write software brevity is not always the first thing you are looking for.

Same is true if you find a lot of quality C programmers from embedded systems; however, when you put them on a larger scale enterprise applications you will start that many habits that helps them to be lean on those platform, begins hurting projects of different type.

I am not making any judgment about individuals, it is true that quality of individuals matters a lot; however, when you are choosing the language or platform is a larger business decision and many more factors count.


问:
Why is Zend Framework so complicated?
I am web developer and have experience of developing several web applications in PHP. I have an idea of developing a product for myself and decided to use a MVC based framework because I really like the idea of MVC and how one can easily manage and modify the application without any difficulty.

I chose Zend Framework and it seems more difficult than learning a new programming language. There are so many things going at one time even to run a small application.

Similarly the idea of routing is very complex as it is new for a core programmer. I know that the guys here read thousand of such questions like one I am asking but I am not looking to learn Zend Framework overnight. I am willing to give as much time as it needs but until now it's making no sense to me. There are thousand of classes in the Zend library, but how would a noob know where to use a specfic class and how to use it? I am still finding it very difficult to understand the bootstrap of Zend Framework and its mapping. I read the manual, follow it and things start working but I really don't exactly how they are actually happening.

I also still have no clue how models, views and controllers work together and how to plan an application in Zend Framework. When it comes to core php I exactly have the idea in my mind what to do and than easily translate them in code but in Zend Framework I don't know how to translate my idea.

答:
Zend Framework is hard. It wasn't built as an entry level framework, knowledge of the concepts involved is assumed1. That said, the first requirement for Zend Framework 2.0 is to make it a little bit easier:

Ease the learning curve

In late 2009, we did a survey of framework users to determine what they use,
  what environments they use, and what their needs are. The top issue, bar none,
  was the difficulty of learning the framework. Some of these issues include:

Difficulty in the "first hour" with the framework.

Uncertainty about the "next steps" following the quick start.

Inconsistent APIs in the source code itself. One component may use "plugins," another "helpers," and yet another "filters."

Uncertainty about where extension points exist, and how to program for them.

Confusion over whether they can use Zend Framework only as an MVC stack or as individual components.

So it's not just you, it's hard for everyone - read the whole wiki page, there are quite a few things that are identified as unnecessarily complex. But even if the above requirement is fulfilled, still it won't become an entry level framework, meaning that it's not a framework you should be learning on, but one that you should be using when you've actually understood the concepts involved.

Since you are still learning, it would be a lot more valuable to build your own MVC architecture. Rasmus Lerdorf's notorious2 "The no-framework PHP MVC framework" blog post gives a very simple and clean example of MVC through procedural PHP, without any framework or other third party library involved.

But if you really want to learn with a framework, you should consider a micro framework instead of a full blown one. Slim has a very small, clean and thoroughly tested code base and it should be ideal for learning. I haven't played around with any other micro framework, you should do your own research and decide which one is better for you.

And for a quick and dirty introduction to routing, see my answer to this question. It's not a very hard concept to grasp, but Zend Framework does make it look like a lot more than it actually is.

1 The best description I've read for ZF is that's it's a framework building framework, not an application framework. It's raw power and extreme list of features aren't suitable for small to medium websites. Unfortunately can't really find where I read that.

2 Read disclaimer at the top of the blog post.

Update, inspired by @Karpie's comment:

A framework is not supposed to be hard, the whole point of a framework is to make things easier. It's possible that even with a firm grasp of the concepts involved, ZF is not a good fit for you.

There are a lot of subjective factors involved when choosing a framework, and unless every other framework lacks functionality you absolutely need - and can't write on your own, you should avoid ZF and use a framework that feels more natural to you.

If you know the concepts, the framework shouldn't be getting in the way.

Title: Why is Zend Framework so complicated?


答:
Does simplicity always improve readability? Yes.  Is one statement per line always simpler? No.  Quite a few languages have a ternary operator, which, once grasped, is simpler and easier to understand than the equivalent if/else assignments.

In languages that allow multiple variables to be set on one line, doing so is frequently simpler and easir to understand than whatever the equivalent is.

Another example: regular expressions do a lot, typically in just one line, and the equivalent without a regex is frequently much harder to read.  /\d{3}[ -]\d{3}-\d{4}/ is the equivalent of a function call with several comments at the least, and is easier to understand than the corresponding function body.


问:
Is Dijkstra's algorithm an appropriate solution to this signal routing problem?
I'm in the process of developing a signal management and routing module for an integrated audiovisual system and am designing it with the intent of being as flexible as possible across different signal distribution networks. The intent of the module is to handle routing across a number of stacked matrix switchers1 and handle necessary format conversion.

The best solution I've explored at this point is to map out the network to a graph with discrete vertices for each signal type supported by the switchers and which are then joined via nodes representing the video processors that handle format conversion.

Colours represent signal formats.
Round nodes are either switchers, sources or sinks.
Square nodes are video processors which perform format conversion.

From there I can use an implementation of Dijkstra's algorithm to identify the path that has to be formed in order to get input X to output Y. This should allow the data about the input / output configuration of all the switchers and processors to be passed in and the module adapt accordingly.

Is this an appropriate solution or is there an alternative approach that may be worth investigating?

1 aka 'crossbar switch', a video router with M input x N outputs that supports one-to-many connections. Each phsyical device may handle multiple signal formats and may or may not be capable of performing any format conversion.

edit: As mentioned by Péter Török, the graph will not necessarily be a tree, the diagram is a simple example to illustrate the idea. When implemented in the 'real world' multiple paths may exist which offer varying levels of definition (DVI > VGA > component > composite) which I was planning to represent with edge weighting.

edit 2: Here's an slightly more comprehensive example with directivity indicated and showing a network consisting of two signal types. The initial example has been modified slightly so that each input and output on a device is defined as a discrete node as this will provide the data required to control matrix routing / input selection.

答:
This is a tree, Dijkstra is O(n^2) overkill. Trivial O(n) breadth-first search is enough.

EDIT: Start the BFS in any node with degree at least two.

EDIT2: Since the graph is not guaranteed to be a tree, use Dijkstra, if you want to optimize a little, you can first "strip" the graph all the vertices of degree one (for them, the path is trivial), including those that happen to acquire degree one due to stripping their ex-neighbours, and do the Dijkstra on the rest (which is exactly the "non-tree" part).

Plus, I would say you want paths from every node to every other, don't you? Dijsktra's algorithm does only paths from one to all others. Maybe do Floyd-Warshall algorithm on the stripped rest. Of course, if the topology is very dynamic, it is best to do the (stripping and) Dijkstra, ad hoc.


答:
If you wrote all your code (that is, if you own your code) you can also dual license it: publish your code in e.g. GPLv3 and offer to sell it (with another license) to those wanting to use it less restrictively.

(this is in particular relevant for a library, because a GPL-ed library can only be used on GPL software).

Be careful about external contributions or patches that you incorporate into your code (since you don't own them).

Title: Choosing a licence for open source projects

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

Here's what I wanted to accomplish:

For full applications:

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

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

can be included into commercial projects without modifications

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

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

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

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

Update:

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

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


答:
Readability and simplicity are subjective terms which, depending on the person and the context, usually but not always go together.

A more objective term is conciseness - something you could in principle count by counting characters, though there are some flaws in that. Conciseness seems to imply simplicity and readability, but there are (at least in my opinion) exceptions.

A longer (and arguably more complex) piece of code can be more readable if it better expresses intent. Whether your definition of simplicity cares about intent is another subjective thing - you could define complexity in terms of the syntactic structure and information-theory entropy, for instance, with no reference to intentions at all.

So, a well-chosen longer variable name may...

Improve readability by better expressing intent

Reduce conciseness - it is longer, after all

Have no effect on syntactic simplicity at all - the syntactic structure of the code is unchanged

Similarly, I might write if (some_boolean == true). In comparison with the equivalent alternative if (some_boolean), this...

Reduces conciseness

Reduces syntactic simplicity, but

May improve readability by better expressing intent.

Of course this one will trigger a mass protest - to plenty of people, this always damages readability too. To me, it depends a lot on the source of the boolean - e.g. the variable name (or method name or whatever) may not clearly express that the value is "truth value". Sure, the if tells you something, but it still smells. But plenty of people will call me an idiot for believing this.

Which is further evidence of the overall subjectivity, of course.


问:
Session Variables and Proper Implementation
Is there any other reason for using session variables besides keeping the values longer than the current request? For instance, is it advisable to use session data when storing information in a file on the file system to prevent one user from writing data to the file of another user? I understand what a session variable is, but I'm not for sure how to properly implement it.</p>

答:
Yes, the most common use of sessions is to keep values longer than the current request. For instance, on log in, you might look up a user's name, or other profile details and store them in the session if you are going to be using them all the time - that way you don't have to continually query the database for these values. </p>

<p>I'm not sure what you are getting at. You want to implement your own sessions? Or, you want to implement the use of sessions in a given framework?  </p>

Body:
Yes, the most common use of sessions is to keep values longer than the current request. For instance, on log in, you might look up a user's name, or other profile details and store them in the session if you are going to be using them all the time - that way you don't have to continually query the database for these values.

I'm not sure what you are getting at. You want to implement your own sessions? Or, you want to implement the use of sessions in a given framework?


答:
All web frameworks within the Java/.NET world will let you access the session, and as such to the content related to the connected user. Generally, sessions are implemented as Maps (Java) or Dictionaries (.NET). HTTP is a "stateless" protocol, therefore sessions have been invented on the server side to keep some form of state between two requests. Check out Sun's documentation on designing EE applications, and when to use a given scope (page, request, session, application), more specifically the 4.4.7 paragraph.

From the developer point of view, one of the best practices is to build your own object that will keep all of data related to the user (example: UserData object with id, username, etc.) and map it as a session variable, instead of directly mapping each user's property directly to the session. You can implement a mechanism that saves the session in the database, in a file but you don't have to worry about one user writing into the session of another user, this is not going to happen (unless it has been hacked, and you have a bigger problem at hand).

The session scope keeps data longer than the request scope as you say. However, the request scope is populated with data entered by the user (it is generally possible to "hack" that and add values on the server side, but that's generally a bad design), whereas the session scope can only be populated from the server side. As @KyleHodgson wrote, more than often you use it to keep in there data that you don't want to retrieve from the database each time the same user sends a request. That is why you'll generally find there the user name, the user profile/preferences, the rights of the user, etc. And you update these session data only if the information is updated, for example when the user changes some preferences.

Title: Session Variables and Proper Implementation

Body: Is there any other reason for using session variables besides keeping the values longer than the current request? For instance, is it advisable to use session data when storing information in a file on the file system to prevent one user from writing data to the file of another user? I understand what a session variable is, but I'm not for sure how to properly implement it.</p>


问:
Is programming a SubCulture?
I was going through this article:

http://en.wikipedia.org/wiki/Subculture

Which got mee thinking is programming a subculture?

After the a while I started thinking it really hard, and if you go really in depth this is a very complex and interesting question to ask.

YOu can even ask yourself if (heavy) internet (social) users are an subculture and programmers a culture within.

I think it might be an interesting discussion, hope you like it!

NOTE:

I linked the wiki article because it might be a good baseline, maybe you can base you answer  on Ken Gelder´s proposal to distinguish subcultures. But it should be based on a little bit more that intuition.

Thanks in advance!

Trufa

答:
No, programmers are not, in themselves a subculture.  There isn't a sense of belonging shared among programmers as a group, or really any of the elements of a shared identity.  However -- and this is a big "however" -- a not-insignificant number of programmers are members of hacker culture.

Hackers have a shared identity, shared rituals/holiday, shared humor, a distinct shared language, they differentiate themselves from other cultures, have their own folklore, and modes of dress, foods, habits, etc.

Hacker culture is not the same as programmer culture.  Many programmers don't grok hacker culture at all, and being a hacker isn't really defined by the activity of programming itself.  It's more about the mind set.

You may be wondering why I call hackerdom a "culture" rather than a "subculture".  Part of being a "subculture" is being somehow distinct from the "dominant culture".  However, hackers don't have a specific term for non-hackers, despite having developed an expansive distinct vocabulary.  This is because the hacker doesn't consider him/her-self not to be part of other cultures due to his/her membership in the hacker culture.  It is not only acceptable that each hacker also belong to one or more other cultures, and that one hacker's "other" culture(s) may conflict with a fellow hacker's "other" culture(s), but it is expected, and believed by some to be the reason hacker culture exists.

One 20th century definition of "culture", however, is a much better match: "the universal human capacity to classify and encode their experiences symbolically, and communicate symbolically encoded experiences socially".  Hackers share a common way of classifying and encoding experiences, a shared symbology and language, and a shared way of communicating all of these things within the hacker social group.

"Programmers" as a group doesn't seem to fit either mold to me.

--Susan

P.S. - I registered just to answer this question, but since I am new I can't link all of my references here.  Please see my comments for URLs (if the system lets me do that).

Links:

Hacker humor and ritual observances (holidays): http://esr.ibiblio.org/?p=2520

Hacker lexicon (dictionary of hacker language): http://catb.org/jargon

How hackers differentiate themselves from other cultures/subcultures: http://catb.org/jargon/html/crackers.html

Hacker folklore: http://catb.org/jargon/html/appendixa.html

Hacker dress, food, habits, etc.: http://catb.org/jargon/html/appendixb.html

Title: Is programming a SubCulture?


问:
How is C++ in QT different from the standard C++ libraries?
I want my app to be able to manipulate images and create watermarks and also needs to run on both windows and mac. Hence I've been investigating QT.

Does QT ship with all the libraries I will need to achieve that? or will I have to get other standard C++ libraries? If so is it worth doing the project in QT?

答:
Not sure about explicit support for watermarks but graphics support in QT is EXCELLENT - I don't believe you'll need anything else outside of QT for graphics, or for just about anything else for that matter. It's a pretty comprehensive computing platform and IMO any project is worth doing in QT - it's a great platform.

But if you're delivering commercial software, it's not always openSource - check out the licensing restrictions - you may have to pay for commercial use.

BTW, if you're looking to go cross platform with QT, I'd look at Python-PyQt. PyQt will make your life much easier - and unless you're doing something that really requires C++ 'down to the metal' performance, the performance hit will be neglible on modern hardware - PyQt is mostly a thin wrapper on native QT but without all extra work of C++, and the Python run-time builds compiled native C libs as it executes.

As for the learning curve, if you're an accomplished C++ developer, Python will be a 'piece of cake'.


答:
The questions reminds me of this answer on Stack Overflow, particularly this quote (substitute quality with simplicity):

Quality -- you know what it is, yet you don't know what it is. But
  that's self- contradictory. But some things are better than others,
  that is, they have more quality. But when you try to say what the
  quality is, apart from the things that have it, it all goes poof!
  There's nothing to talk about. But if you can't say what Quality is,
  how do you know what it is, or how do you know that it even exists? If
  no one knows what it is, then for all practical purposes it doesn't
  exist at all. But for all practical purposes it really does exist.
  What else are the grades based on? Why else would people pay fortunes
  for some things and throw others in the trash pile? Obviously some
  things are better than others -- but what's the ``betterness''? -- So
  round and round you go, spinning mental wheels and nowhere finding
  anyplace to get traction. What the hell is Quality? What is it?

I think that it's important that you keep in mind that a codified coding standard for all its benefits will not make good programmers out of bad ones. A word like 'simple' may be interpreted differently by different people (see Aidan Cully's answer), but that may not be such a bad thing. Junior programmers will still need to have their code reviewed by senior programmers and learn why the senior programmers interpretation of 'simple' is better than their own.


问:
What is richochet frames based hotspot jvm?
In order to implement JSR 292, a.k.a. invoke dynamic, something called richochet frames is introduced into the hotspot vm. I'd like to know more about it, such as invoke dynamic itself, how richochet frames implements it, where the name richochet comes from, etc.

Google seems to be not very helpful here. Any pointers would be appreciated. Or better, someone please writes blogs about it :)

答:
Basically you want to join the mlvm-dev mailing list at openjdk.java.net - here are their archives. You'll also want to join the JVM Languages Google group.

Please do peruse the archives before posting, you'll get a much better reception if you've shown that you did some of your own research first :-)

From John Rose:

The most complicated bit of assembly code in the HotSpot method handle
  implementation is "ricochet frames", which natively implement
  foldArguments.  But it was a good investment, because this particular
  pattern of MH combination is a sort of universal glue for making every
  other kind of recursive combination.


问:
Is there a term used when internal variables are declared public and accessible?
If someone writes code so that an internal variable $_fields is accessible without using getter/setter methods, is there a proper term used to describe that?

Something polite enough to use with management :)

答:
Exposing ones private members is never a good thing in polite society...

This practice is the lack of/poor encapsulation.


答: Besides the lack of encapsulation already mentioned by Oded, depending on the programming language and its paradigms it could also be "plain old data" (where it isn't necessarily an antipattern or code smell).</p>

Title: Is there a term used when internal variables are declared public and accessible?

Body:
If someone writes code so that an internal variable $_fields is accessible without using getter/setter methods, is there a proper term used to describe that?

Something polite enough to use with management :)


答: Choose a language that is designed to solve the problem you have. Then hire people who know that language and like solving that kind of problem. then you will have the right people doing the right job with the right tools.</p>


答:
Its called a property bag.

Usually it is used to hold a set of maybe related properties (were each may potentially be a class object that has appropriate access specifiers or not). But the surrounding structure is just a bag of properties.


问:
Does it make sense to license unit tests?
I am wondering if there are any benefits / risks of (not) putting a licence on test code which mostly consists of unit tests. What do you think?

I am particularly interested in licensing under (L)GPL, Apache, MIT and BSD.

EDIT: The assumption is that non-test code is already published under some licence, but test code is not, so the question is whether to publish it and if so whether to put the same licence on it.

答: It might be a possible business model so release a program as free software (GPL or whatever), but the appertaining unit tests under a commercial license. That way, if someone wants to release an improved version of your software (e.g. embedded in a device), he might be motivated to buy the unit test license for quicker and safer development.</p>

OwnerDisplayName: leden


问:
Who first created or popularized the original XMLHTTPRequest / MSXML?
I'm trying to understand the origins of AJAX, and think MSXML and XMLHTTPRequest were the objects that started it all.

Which came first, and/or became the defacto way to create dynamic pages?

答:
For the origins, see Wikipedia's XMLHttpRequest article, particularly this excerpt:

The concept behind the XMLHttpRequest object was originally created by
  the developers of Outlook Web Access (by Microsoft) for Microsoft
  Exchange Server 2000. An interface called IXMLHTTPRequest was
  developed and implemented into the second version of the MSXML library
  using this concept. The second version of the MSXML library was
  shipped with Internet Explorer 5.0 in March 1999, allowing access, via
  ActiveX, to the IXMLHTTPRequest interface using the XMLHTTP wrapper of
  the MSXML library.

As for the first massive usage, the Wikipedia article on Ajax has the answer:

The utility of background HTTP requests to the server and asynchronous
  web technologies remained fairly obscure until it started appearing in
  full scale online applications such as Outlook Web Access (2000) and
  Oddpost (2002), and later, Google made a wide deployment of Ajax with
  Gmail (2004) and Google Maps (2005).

I am sure there are other examples, but personally the example of Gmail strikes home.
I never used Outlook Web Access, but I clearly remember the first time I gained access to my Gmail mailbox. At that time I really was wondering how they achieved that without iframes...


答:
No.  Programmers are no more a subculture than engineers, doctors, or lawyers.  If professions were actually subcultures then the word wouldn't mean very much.

Let's look at the 6 criteria on the Wikipedia page:

1. through their often negative relations to work (as 'idle', 'parasitic', at play or at leisure, etc.);

This is obviously not the case.  Most decent programmers work reasonably hard and enjoy it to some extent.

2. through their negative or ambivalent relation to class (since subcultures are not 'class-conscious' and don't conform to traditional class definitions);

Most programmers are middle-class, so this doesn't even really apply.

3. through their association with territory (the 'street', the 'hood, the club, etc.), rather than property;

Unless the internet counts as territory, I'd have to say no to this as well.

4. through their movement out of the home and into non-domestic forms of belonging (i.e. social groups other than the family);

A lot of programmers are on the anti-social side but again, and even the internet doesn't really apply here because everybody uses social networks now.

5. through their stylistic ties to excess and exaggeration (with some exceptions);

Most definitely not the case with programmers.

6. through their refusal of the banalities of ordinary life and massification.

Pretty much every programmer I know enjoys the casual comforts of beer, pizza, and computer games.

Verdict:  No, programming isn't a subculture.  It's a career.  What you do for a living has very little to do with how your philosophy on society.

Title: Is programming a SubCulture?

Body:
I was going through this article:

http://en.wikipedia.org/wiki/Subculture

Which got mee thinking is programming a subculture?

After the a while I started thinking it really hard, and if you go really in depth this is a very complex and interesting question to ask.

YOu can even ask yourself if (heavy) internet (social) users are an subculture and programmers a culture within.

I think it might be an interesting discussion, hope you like it!

NOTE:

I linked the wiki article because it might be a good baseline, maybe you can base you answer  on Ken Gelder´s proposal to distinguish subcultures. But it should be based on a little bit more that intuition.

Thanks in advance!

Trufa


答: I've heard the term "naked object" before.</p>


问:
What are some FizzBuzz-type questions for web or SQL developers?
After a while, we are hiring again, and I'm reviewing tests for programmers; some of them are a bit out of date. What are some of the FizzBuzz-type questions for web developers and SQL? That is, not too trivial, but still solvable in five to ten minutes with pen and paper and without Google?

I typically eliminate about two thirds or more of the candidates based on CV, and then all but a few really good candidates in a one-hour interview (which can be over the phone). At this point the candidate is writing a personality test and has a chance to write a bit of FizzBuzz-like code. So, I'm not trying to eliminate a bunch of candidates, but I am trying to validate my initial assessment that candidate is hireable and able to code.

答:
How about fizzbuzz itself? Here's an Oracle version:</p>

```<code>select case when mod(level,35) = 0 then 'fizzbuzz'
            when mod(level,7) = 0 then 'buzz'
            when mod(level,5) = 0 then 'fizz'
            else to_char(level) end fizzbuzz
from dual connect by level <= 100
</code>```

Body:
How about fizzbuzz itself? Here's an Oracle version:

select case when mod(level,35) = 0 then 'fizzbuzz'
            when mod(level,7) = 0 then 'buzz'
            when mod(level,5) = 0 then 'fizz'
            else to_char(level) end fizzbuzz
from dual connect by level <= 100


问:
Stuff every programmer needs while working
I've been tasked with creating a fun and relaxing environment, one thing I know that I want is ergonomic mice and keyboards, others have suggested exercise balls and bands.

What is it that every programmer needs while working? What might not be necessary but would be nice to have anyway?

Note: this question was asked previously, but has been recommended to be posted here. See this link for the previous responses: https://stackoverflow.com/questions/3911911/stuff-every-programmer-needs-while-working-closed

答:
Other beverages (hot water for tea, fridge for cold drinks).  Believe it or not, we're not all coffee nuts.

Customizable workspace: coders have, if nothing else, strong opinions about how we code.  I often walk off with a fountain pen and notebook to start coding (often outside, on the floor, or in other strange places).  The more control coders have over our process, the more productive we can be.

Business processes, etc. that allow us to customize our soft tools as we do our workspace: i.e. don't use proprietary protocols or formats that force us to all use the same client apps.

Work/life balance: despite popular opinion, programmers may have lives.  Some of us have significant others and/or children.  Not only is it hard to attract and keep great coders if you work them 60h/week, but the ones you do keep will often be too burnt out to be productive.

Work/learning/community balance: I think someone already covered this, but coders need chances to grow their skills and network with coders outside their office bubble in order to stay at the top of their game.  This is especially true of coders working primarily on open-source products.  A few hours/week of community coding, and a conference or two a year can make a dramatic difference in your coder's ability and productivity, as well as your company's clout with other programmers, some of whom you might want to hire.


问:
Looking for Case Studies of How TDD Improved Quality and/or Speed of Development
At my company I am trying to make a case for why we should be doing TDD. Currently most developers just do whatever they can to get the project done, then go add unit tests after the fact in order to meet manager metrics. Any examples from reputable companies doing TDD and seeing the benefits would be greatly appreciated.</p>

答:
Definitely check out this: TDD Proven Effective! Or is it?

...when Phil Haack announced that Research Supports the Effectiveness of TDD I was more than a little interested in seeing what the linked report actually contained. Phil quotes from the abstract.

We found that test-first students on average wrote more tests and, in turn, students who wrote more tests tended to be more productive. We also observed that the minimum quality increased linearly with the number of programmer tests, independent of the development strategy employed.

Phil has obviously read the rest of the report and provides his favorite pieces that seem to do as his title suggests. One of the things I worry about when I see things supporting the latest and greatest software development practices, however, is a strong tendency towards confirmation bias — of looking for confirmation of current theories and overlooking counter-indicators.

So, being the curious type and since TDD is something I'm keeping an eye on to see if its something I might want to adopt myself some day, I went into the report...

...without question, testing first leads to having more tests per functional unit. The question is if this is valuable. This study would seem to indicate that this is probably not the case, at least if quality is your intended gain. But then, I'm not that surprised that number of tests doesn't correspond to quality just as I'm not surprised that the number of lines of code doesn't correspond to productivity.

The author has a lot of good points about TDD not being all that effective (imo despite being hyped to death)


答: If your unit tests are well done then they are a blueprint for reproducing your software. If you don't license them equivalently to the code you are inviting someone to just come along and re-implement whatever you did. If you are alright with that then don't bother licensing them.</p>

Title: Does it make sense to license unit tests?

Body:
I am wondering if there are any benefits / risks of (not) putting a licence on test code which mostly consists of unit tests. What do you think?

I am particularly interested in licensing under (L)GPL, Apache, MIT and BSD.

EDIT: The assumption is that non-test code is already published under some licence, but test code is not, so the question is whether to publish it and if so whether to put the same licence on it.


答:
The GCC compiler (mostly GPLv3 licensed) has a quite extensive test suite, which is distributed with the source code. (perhaps some test files are in the public domain, I really don't know their individual legal status).

Why would you want to distribute your test suite separately from your product?


答:
if your setter/getter methods are nothing more than

```<code>void setfoo(bar){foo=bar;}
foo getfoo{return foo;}
</code>```

then just making a pubic variable is just saving some typing outside of a few edge cases where the difference matters.

Body:
if your setter/getter methods are nothing more than

void setfoo(bar){foo=bar;}
foo getfoo{return foo;}

then just making a pubic variable is just saving some typing outside of a few edge cases where the difference matters.


问:
Is a university education worth it for a good programmer?
I've been doing design and programming for about as long as I can remember. If there's a programming problem, I can figure it out. (Though admittedly Stack Overflow has allowed me to skip the figuring out and get straight to the doing in many instances.) I've made games, esoteric programming languages, and widgets and gizmos galore. I'm currently working on a general-purpose programming language. There's nothing I do better than programming.

Is a university education really more than just a formality?

答:
Assuming you are in the US, you might perhaps consider studying Computer Science in some other country?

AFAIK, in France (where I was born, studied, live and work), studying is less expensive than in the US (and you probably would need, as a foreigner, some grant to be allowed to study here). I believe it is also the case in many other European countries.

And perhaps having studied in some other country might give you some small benefit (when returning home and seeking for a job).

Of course, you'll need to learn some foreign language.


问:
What should you include in a development approach document?
I'm in the middle of co-producing a "development approach" document for off-shore resources as they ramp up onto our project.

The most recent (similar) document our company has used is over 80 pages, and that does not include coding standards/conventions documents.

My concern is that this document will not be consumable and will therefore fail.

What should be in a development approach document?
Are there any decent guidelines on this topic?

EDIT: The development approach document should detail the practices and techniques that will be used by software developers while software is designed, built, and tested.

答:
1: If you already are doing projects within your company, get on board with that process.  Maybe even sub-contract out the management of your project development to them.  Don't re-invent the wheel.

2: If you don't already do development in house, insist that the contractor you are using have a good methodology they use for projects.  Then use that methodology.

Trust but verify.  You are trying to weed out the garbage in the long-run.  So don't let them do anything, follow any process with only deliverable at the end.  Insist that early deliverable be done and checked before they move on.

Beyond that I basically ditto on @Dipan


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

答:
A Computer Science Tapestry: Exploring Computer Science in C++

This was assigned reading when I was in college.  Apart from being totally soporific, this book presents things in such a convoluted way, I doubt I could have parsed it without prior programming knowledge: most of my class, in which there was only one experienced coder beside myself, was completely lost.

I gave up after reading only a fraction of the book and tried using it to hold up the end of a wobbly bookcase.  It wasn't great at that, either: a little too thick and the cover was slippery.


问:
How to tackle massive Linux/makefile projects effectively?
I have been developing Windows applications in C++ for like 10 years now. And recently I've started digging into some Linux projects, and I can't stand how unproductive I am...

I'm a fast learner, and I've been using Linux as a primary platform for some time now. And I do feel very comfortable with shell, OS principles and GUI. But when it comes to development, it feels like I'm back to school.

As soon as I open some larger project, I'm stuck. Most of them are makefile based, so basically when I try to navigate them with QT or CodeBlocks, at best, I can use intellisense on a per-file basis. And most of the time variables leak from scope.

Then there is a go-to-definition stuff, which seems nonexistent, try to join some larger project from sourceforge, and you're stuck for days, because navigating to definitions is so hard... grep -r "this_def" . --include "*.cpp" --include "*.h" seems so slow and clumsy.

And then, the debugging, gdb does work, but no matter what I do, it seems like it's light years behind WinDbg or VisualStudio debugger.

And these things are making me desperate, I want to write code, but it just goes so slow... I'm starting to think that Linux developers learn function definitions by heart and analyze code by eyes, but I can't believe it's so.

Has anyone gone through this? Is there something that I'm missing that could make me more productive?

答: For what it is worth, on Linux you have better building systems than plain old GNU make (which often goes with the horrible autoconf), for example omake and many others (cmake, scons ...).


问:
Data Scraping - One application or multiple?
I have 30+ sources of data I scrape daily in various formats (xml, html, csv). Over the last three years Ive built 20 or so c# console applications that go out, download the data and re-format it into a database. But Im curious what other people are doing for this type of task. Are people building one tool that has a lot of variables and inputs or are people designing 20+ programs to scrape and parse this data. Everything is hard-coded into each console and run through Windows Task Manager.

Added a couple additional thoughts/details:

Of the 30 sources, they all have unique properties, all are uploaded into individual MySQL tables and all have varying frequencies. For example, one data source is hit once a minute, another on 5 minute intervals. Majority are once an hour and once a day.

At current I download the formats (xml, csv, html), parse them into a formatted csv and put them into staging folders. Within that folder, I run an application that reads a config file specific to the folder. When a new csv is added to the folder, the application then uploads the data into the specific MySQL tables designated in the config file.

Im wondering if it is worth re-building all this into a larger complex program that is more capable of dynamically adding content+scrapes and adjusting to format changes.

Looking for outside thoughts.

答:
As sbrenton said, this most falls in with ETL. You should check out Talend Open Studio. It specializes in handling data flows like I imagine yours are as well as other things like duplicate removal, normalization of fields; tens/hundreds of drag and drop ETL components, you can also write custom code as Talend is a code generator as well, either Java or Perl are options. You can also use Talend to execute system commands. I use it for my ETL work, although not in production, in production we will use SSIS, mostly due to lots of other Microsoft products in house.

Here is an informative video : http://www.talend.com/demo/


问:
Why is Zend Framework so complicated?
I am web developer and have experience of developing several web applications in PHP. I have an idea of developing a product for myself and decided to use a MVC based framework because I really like the idea of MVC and how one can easily manage and modify the application without any difficulty.

I chose Zend Framework and it seems more difficult than learning a new programming language. There are so many things going at one time even to run a small application.

Similarly the idea of routing is very complex as it is new for a core programmer. I know that the guys here read thousand of such questions like one I am asking but I am not looking to learn Zend Framework overnight. I am willing to give as much time as it needs but until now it's making no sense to me. There are thousand of classes in the Zend library, but how would a noob know where to use a specfic class and how to use it? I am still finding it very difficult to understand the bootstrap of Zend Framework and its mapping. I read the manual, follow it and things start working but I really don't exactly how they are actually happening.

I also still have no clue how models, views and controllers work together and how to plan an application in Zend Framework. When it comes to core php I exactly have the idea in my mind what to do and than easily translate them in code but in Zend Framework I don't know how to translate my idea.

答:
I didn't like the lack of discoverability when I started using the Zend Framework, too many classes rely on arrays and you have to lookup what keys you can/need to define.

There is nothing at all wrong with having clear set methods or named params, it would, imo go a long way to helping with discoverability.

The Yii framework is even worse with this sort of thing.

Title: Why is Zend Framework so complicated?


答:
There is two things you can get.

Degree - probably not worth it, unless you are not self-confident enough to get hired without one. Attending the university will require lots of time and money.

Knowledge - it is very much worth it to learn calculus, algebra, algorithm theory etc. (so CS in general). The advantage of self-education is that you can focus on the relevant subjects. However, it requires quite some self-discipline to keep learning because there is no external pressure (exam) to make you learn when you don't feel like learning.

Title: Is a university education worth it for a good programmer?

Body:
I've been doing design and programming for about as long as I can remember. If there's a programming problem, I can figure it out. (Though admittedly Stack Overflow has allowed me to skip the figuring out and get straight to the doing in many instances.) I've made games, esoteric programming languages, and widgets and gizmos galore. I'm currently working on a general-purpose programming language. There's nothing I do better than programming.

Is a university education really more than just a formality?


问:
Event subscription from nested classes
Is it OK to have a nested class raise an event and for the parent class that subscribes to that event subsequently raise another event, which it's parent class has subscribed to - thus passing the original event up the class hierarchy?

It may be easy to explain like this...

We have...

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

Operation...

Class C raises an event

Class B subscribes to that event, on notification it raises another event

Class A subscribes to Class B event, on notification it does something

So the original event occurred in Class C and Class A is dealing with it.

Using this method means I require event handlers in the middle class (Class B) whose only function is to pass along the notification - this seems a little smelly to me.

答:
Yes, it is OK and it is a good way of hiding the details of your inner events as well as having one class to connect your event listeners to, instead of several one. It does not mean that having multiple events in multiple classes is bad - far from it - just that it helps in increasing the comprehension of your code if all events related to a particular business domain are in the same "place", although the real inner work is done in "child" classes.

There even is a name for it: event bubbling. You may be interested in reading the MSDN article on that subject.

Title: Event subscription from nested classes


问:
Use case notation for login
When a login is needed in a system to perfom any action. How do you express that in a Use Case Diagram?

I have a system that will allow employees to perform sells. They must be logged in, but once they are, it is not necesary to log again until the session ends (typical login).

I do not know how can I express that that login is compulsory, but only once.

答: If the login is part of the system you are creating it should be a use case in itself that is listed as a prerequisite for other use cases. if you are using an outside system (i.e. Windows authentication) you could simply list that the user has authenticated through windows authentication or whatever system you plan to use. Its generally good practice to always have a precondition and post condition sections of your use case.</p>

Title: Use case notation for login


答:
Use Cases form a proper class hierarchy.

Must-be-logged-in Use case can be a super-class of the rest of your use cases.

Some folks like to use <<extends>> to show that a use case extends the login use case.

See this diagram: http://yuml.me/diagram/scruffy/usecase/draw

Title: Use case notation for login

Body:
When a login is needed in a system to perfom any action. How do you express that in a Use Case Diagram?

I have a system that will allow employees to perform sells. They must be logged in, but once they are, it is not necesary to log again until the session ends (typical login).

I do not know how can I express that that login is compulsory, but only once.


问:
Rails generators for subscription and payment processing services?
I've been thinking about making a generator for managing subscriptions with options for a couple different payment processing services, it is something that I would use. Are there any existing examples of this, or any thoughts on a generator. I thought it might work like the scaffold function, similar to the authentication function in nifty-generators.

EDIT: Also, It seems that there should be a lot of security concerns when implementing payment processing, having a consistent and common way to generate this would let me make sure best practices and security are followed the same in all my apps.

答:
For the payment part have a look at ActiveMerchant. If there is a gem for subscriptions you can find at RubyGems.

If it doesn't exist yet, it would really be a good idea to write one. I have seen several sites that could have used one. Though this may become a more complicated task than a simple generator. To handle subscriptions (especially in combination with payments) you would need a process (like cron job) that checks subscriptions in regular intervals and generates payments or mails requests for renewals (and several more tasks, depending on usage scenario)


问:
Entity Framework vs. Linq to SQL?
I'm a little bit confused about these two terms "Linq to SQL" and "Entity Framework".  I have the general idea that both of them somehow allow you to refer to database tables as .net objects or something of the sort, but please explain to me the difference between these two terms.</p>

答:
This subject has already been covered several times, you may be interested in reading:

https://stackoverflow.com/questions/8676/entity-framework-vs-linq-to-sql. The top answer is short and right on the spot although a little bit dated (2008)

https://stackoverflow.com/questions/3293995/what-is-the-difference-between-entity-framework-and-linq-to-sql-by-net-4-0. More specifically related to the 4.0 version of the framework.

http://social.msdn.microsoft.com/Forums/en/adodotnetentityframework/thread/dc83097e-9c70-4970-93e2-dbc8636eb321 (I took this link from the answer provided by @jlnorsworthy in Should I be learning Linq, Direct SQL Commands (in .net), EF or other?)

They are similar in that they both are ORM-based but EF is more "enterprisey" and feature-complete than Linq. EF is   more comparable to NHibernate as for the available features and has matured with the release of .NET 4.0. Also, one of the most important things to keep in mind is that Linq will lead you into trouble if your DBMS is not part of the SQL Server family (be it "Express" or "Compact").

Edit: as @jkohlhepp has stated in the comment below, Linq to SQL is in maintenance mode (not Linq! thanks to Randy), so no more new features only bug corrections will be done. As such, it really is recommended to start new projects with EF.

Title: Entity Framework vs. Linq to SQL?


问:
How can I  define and measure simplicity in code?
There are many answers in my previous question about simplicity relating to readability that helped me see my definition and understanding of simplicity in code was, quite possibly, incorrect.

How can I define simplicity in code? What software measurements and metrics are available to measure code simplicity?

答:
The most common metrics for measuring the complexity (or simplicity, if you take simplicity to be the opposite of complexity) are McCabe's Cyclomatic Complexity and the Halstead Complexity Metrics.

Cyclomatic complexity measures the number of distinct paths through a given unit, usually a method or function, although it can also be computed on a class. As the number of paths increase, it becomes more difficult to remember the flow of data through a given module, which is related to the concept of working memory. High cyclomatic complexity tends to indicate difficulty in the ability to test a module - more test cases are required to cover the various paths through the system. There have also been studies that have linked high cyclomatic complexity to high defect rates. Typically, a cyclomatic complexity of 10 indicates that a unit should be reviewed and possibly refactored.

The Halstead complexity measures use the inputs of total and distinct operators and operands to compute the volume, difficulty, and effort of a piece of code. Difficulty, which is the (number of unique operators / 2) * (total number of operands / number of unique operands), is tied to the ability to read and understand the code for tasks such as learning the system or performing a code review. Again, you can count this on a system level, a class level, or a method/function level. There are a few postings about computing these measurements here and here.

Simply counting lines of code can also give you an idea of complexity. More lines of code means that there is more to read and understand in a module. I would be hesitant to use this as a stand-alone measurement. Instead, I'd use it with other measurements, such as number of defects in a given module to obtain defect density. A high defect density could indicate problems in writing tests and performing code reviews, which may or may not be caused by complex code.

Fan-in and fan-out are two other metrics, related to the flow of data. As defined here, fan in is the sum of the procedures called, parameters read, and global variables read and fan out is the sum of procedures that call a given procedure, parameters written to (exposed to outside users, passed in by reference), and global variables written to. Again, high fan-in and fan-out might be indicative of a module that might be difficult to understand.

In specific paradigms, there might be other measures or metrics that are also useful. For example, in the object-oriented world, monitoring coupling (desire low), cohesion (desire high), and depth of inheritance (desire low) can be used to assess how simple or complicated a system is.

Of course, it's important to realize that a lot of measures and metrics are simply indicators. You need to use your judgement to determine if it's necessary to refactor to increase simplicity or if it's not worth the effort to do so. You can make the measurements, compute the metrics, and learn about your code, but you don't want to design your system by the numbers. Ultimately, do what makes sense.


答:
I am not aware of any good existing metrics for code simplicity (it doesn't mean they don't exist - just that I don't know about them). I could propose some, maybe some will help:

Simplicity of language features used: if the language has features that might be considered "advanced" and "simple" you could count the number of occurrences of the advanced features. How you define "advanced" might be a little more subjective. I supposes some might say this is also like measuring the "cleverness" of a program. A common example: some might say that the ?: operator should be an "advanced" feature, others might disagree. I don't know how easy it would be to write a tool that can test for this.

Simplicity of constructs within the program: You could measure the number of paramters a function will accept. If you have > n % of all functions with > m parameters, you could choose to count it as not simple, depending on how you define n and m (maybe n=3 and m=6?). I think there are some static analysis tools that can measure this - I think JTest simply measured functions with > m parameters.

You could try to count the number of nested loops or control structures. This I think is actually not a bad metric and I think there's a name for it (can't recall off the top of my head). Again, I think there are tools (again, like JTest) that can measure this, to a degree.

You could try to measure "refactorability". If your code contains lots of pieces of code that could be refactored but aren't, maybe that would could as not simple. I also recall from the time I worked with JTest that it tried to measure this too, but I remember I didn't often agree with it in this case, so YMMV.

You could try to measure the number of layers between different parts of your system. For example: how many different pieces of code will touch data that comes from a web form before it gets stored in the database? This could be a tricky one to measure properly...

Title: How can I  define and measure simplicity in code?

Body:
There are many answers in my previous question about simplicity relating to readability that helped me see my definition and understanding of simplicity in code was, quite possibly, incorrect.

How can I define simplicity in code? What software measurements and metrics are available to measure code simplicity?