答:
End tags for p elements were optional in HTML, and were only required in XHTML. However, the HTML5 draft introduces a set of conditions for when the p end tag is actually optional:

A p element's end tag may be omitted if the p element is immediately followed by an address, article, aside, blockquote, dir, div, dl, fieldset, footer, form, h1, h2, h3, h4, h5, h6, header, hgroup, hr, menu, nav, ol, p, pre, section, table, or ul, element, or if there is no more content in the parent element and the parent element is not an a element.

Source: HTML5 specification

That said, the only argument I've ever heard for omitting the end tags for p elements is document size. It's completely up to you to decide if that makes sense for your document or not. Personally I tend to include all optional end tags, just in case I don't meet the requirements for when the end tag is optional.

Body:
tl;dr

Some widely used programs, which generate html, will only generate opening paragraph tags, and not closing ones, assuming that the browser will properly close paragraphs.

On the face of it, it seems to me that the assumption that browsers will properly close paragraphs is not correct. Is my interpretation correct? More generally, what tradeoffs are involved in this kind of decision?

Browsing through moinmoin source code, the following line of code caught my eye:

```<code># We only open those tags and let the browser auto-close them:
_auto_closing_tags = set(['p'])
</code>```

(source)

After reading throug the rest of the implementation, I've convinced myself that yes, indeed, when moinmoin generates html code for one of its pages, it will correctly generate paragraph open tags, where appropriate, while at the same time purposefully avoiding any of the paragraph close tags (despite being able to trivially do so).

For my specific, rather unusual, use case, this behaviour is not correct. I'm tempted to submit a bug report and/or change the behaviour. However, it looks like this design decision was thoughtfully made. I'm not well enough versed in the intricacies of the html standard, or the various browser implementations, to be able to tell if this is correct behaviour in general, and I have the feeling that my instinct to correct/change this behaviour might be misguided.

Is this code making a valid assumption about browser implementations? Is the generated html valid? More generally, what tradeoffs might I be missing here?


问:
Does Lisp still have any special feature which has NOT been adopted by other programming languages?
Does Lisp still have any special feature which has NOT been adopted by other programming languages?

By Lisp, I mean all the Lisp programming languages as a whole. I've been told how amazing Lisp is and know that many languages have been inspired by Lisp. But does Lisp still have any exclusive design feature that just cannot be done in any other language?

The reason I asked the question is that recently, being an amateur programmer myself, I began to learn Clojure just for fun, and the result is that I found lots of Lisp-related posts and comments, saying but one thing: "Lisp is unique", but other modern programming languages have already adopted and stolen lots of ideas from Lisp, like conditionals, recursion, and the function as a first-class citizen. And even metaprogramming can be done by many languages.

Did I miss out something and is "Lisp still different"?

Or I'm lucky because other modern languages have stolen all the good parts from Lisp so that it's not necessary to dig into the parentheses Lisp world, and "Lisp was different".

答:
It's not necessarily a certain single feature. It's the whole look and feel, and how certain sets of features work together.

JavaScript or Java have a lot of features of Lisp (virtual machine, compiler/evaluator, garbage collection, etc.). But JavaScript for example lacks the symbolic programming part, it lacks mathematic capabilities (internally it has only floats), it lacks the error handling, and so on.

Many Common Lisp systems are optimized for a development way where one extends new software incrementally, by extending the Lisp language in various dimensions using various meta-programming techniques - without restarting the software for a long time. Thus it needs to be flexible and extensible - but at the same time it needs to be robust. Changing the language (macros are basically a way for the user to extend the compiler) without crashing the program.

Now something like JavaScript is also used to extend a program, typically a web browser. But most of the time one does not much meta-programming in JavaScript - besides some OOP hackery.

Example:

One can implement a general advanced mathematics software for the domain of computer algebra in mostly two ways: write the engine in C with a specialized language on top (like Mathematica) or in some more advanced Lisp dialect. Macsyma/Maxima in Common Lisp, Reduce in Standard Lisp, Axiom in Common Lisp.

(There are also one or more written in Python.)

There are not many systems which offer the feature set of something like Axiom, which runs on top of Common Lisp.

What made Lisp attractive for these types of applications is a mix of features: advanced basic maths (bignums, ratios, ...), symbolic computation, interactive compiler, etc. It's quite possible to get these things by implementing them in a low-level language. That way, one will have implemented 50% or more of a typical Lisp system.

ContentLicense: CC BY-SA 3.0


问:
Sleeping Web Server?
Are there any languages or even servers that instead of running a script on page load, (Apache/PHP, Ruby on Rails, ...) actually keep the code loaded and running forever, and when it receives a connection it calls a function of that code? (Like a PageLoad event basically?)

I didn't really know how to call this so I went for Passive Web Server because the code is basically sleeping till an event occurs, instead of fully unloaded or just cached.

答:
PHP and scripts run through CGI (not FastCGI) are about the only things that work this way.  Almost everything else has a long-lived process that runs & responds to requests.  A typical web application will have a static server (Apache, Nginx...) in front, handling client requests directly.  For static files (Javascript, CSS and so on), it'll just send the file; for things that require your app to respond, it will pass the request on to your application & then forward the response to the client.

One example would be a simple Python/Django install.  We have Apache running on the server.  As part of our Apache configuration, we're running mod_wsgi.  The mod_wsgi module allows Apache to fire up a number of Python interpreters that have long-running jobs in them.  When a request comes in, Apache sees that it should go to Python & hands the request over to mod_wsgi and mod_wsgi passes the request into your already loaded & running Django application.

Another example would be a Ruby on Rails application running behind Nginx and Mongrel.  Mongrel is a web server that lets Ruby applications live inside of it.  It's really good at serving dynamic pages but it's a little slow at static stuff, so we set up Nginx for that.  Nginx serves the static content (like Apache did in the last example) but whenever a request for one of the dynamic pages comes in, Nginx just acts as a proxy and forwards the request to Mongrel.

There's a minor difference between the two cases but it's not really worth delving into unless you're handling server architecture for a high-volume website.

A third setup comes in with Node.js.  With Node, the web server is your application.

Title: Sleeping Web Server?


问:
Stopping developers committing to the wrong branch on DVCS

The problem

I am on a software project which has about 10 developers, we share source code via Mercurial. We have a development and production branch per release. Repeatedly during the course of the project we have had source code from one branch i.e. v1 getting into patch and maintenance branches for earlier releases of software i.e. v2.

This results in either time spent backing out the wrong commit, or wrong (possibly non-QAd) code reaching and getting deployed in the wrong branch if we don't notice that the code has gone into the wrong branch.

Our branch and merge design/method

```<code>               v1-test   v1-patch1   v1-patch2
               ^---------^-----------^                v1-prod
              /         / \           \
-----------------------/   \           \              v1-dev
              \             \           \
               --------------------------\            v2-dev
                             \       \    \
                              ^-------^-------------  v2-prod
                              v2-test v2-patch1
</code>```

Hence we will work on a release development branch, until it's deemed ready, branch it off for a single testing/UAT/Production branch, where all releases and maintenance is done. Tags are used to build releases of this branch. While v1 is being tested, a branch will have been made for v2 and developers will start working on new features.

What tends to happen is that a developer commits work due for v2-dev branch into v1-dev or v1-prod, or worse, they merge v2-dev into v1-prod (or similar such mistakes).

We tell most developers not to access the -prod branches, however code still sneaks in. A group of more senior developers `look after' the -prod branch.

It should be noted that while v2 has just started development, there may still be some quite hefty patches going into v1 to fix issues. I.e. v1 may not just be getting the odd small patch.

What we've tried so far

Having a separate -prod branch, with gatekeepers. A -prod branch should raise warnings through its name and most developers don't need to ever be in that branch. This has not really reduced the problem.

Raised awareness of this problem amongst the developers, to try and make them more vigilant. Again this has not been very successful.

Possible reasons I see for developers committing to the wrong branch

Too complex a branch design

Having active development in multiple branches in parallel. (The project does exhibit symptoms of using the avalanche-model.)

Developers don't understand the DVCS well enough

Questions I've read which were somewhat relevant

I've read this question on not committing to the wrong branch and I feel that the answers regarding visual cues may be helpful. However I am not entirely convinced that the problems we're experiencing are not symptoms of a more fundamental problem.

With the visual clues, we can incorporate them into the command line easily, however about half the team use eclipse which I'm unsure how to incorporate visual cues.

Question

What methods, in the form of software, project management or governance can we use to reduce (ideally stop) commits to the wrong branch taking up our time or dirtying our deployed code?

Specific comment on the reasons I believe may be contributing as outlined above would be appreciated, but this shouldn't limit your reply.

答:
While you have tried using a separate -prod branch with gatekeepers, it sounds as though the one repository is used to actually do the production builds. If the production builds were only done from a production repository, writable only by it's gatekeeper then the devs wouldn't be able to push to it. This puts a load on the gatekeeper, who would only push to the production repo after review. Of course people would still be able to pull from the production repo when needed.

As people gain experience, they should be rotated through the gatekeeper role, to gain the deeper understanding or care that they seem to lack.

And as a general rule, apply Occam's Razor: the entire repo structure should as simple as possible to do it's job.

See also Sean's comment.


问:
Self Documenting Code Vs. Commented Code
I had a search but didn't find what I was looking for, please feel free to link me if this question has already being asked.

Earlier this month this post was made:

http://net.tutsplus.com/tutorials/php/why-youre-a-bad-php-programmer/

Basically to sum it up, you're a bad programmer if you don't write comments. My personal opinion is that code should be descriptive and mostly not require comment's unless the code cannot be self describing.

In the example given

```<code>// Get the extension off the image filename
$pieces = explode('.', $image_name);
$extension = array_pop($pieces);  </code>```

The author said this code should be given a comment, my personal opinion is the code should be a function call that is descriptive:

```<code>$extension = GetFileExtension($image_filename);
</code>```

However in the comments someone actually made just that suggestion:

http://net.tutsplus.com/tutorials/php/why-youre-a-bad-php-programmer/comment-page-2/#comment-357130

The author responded by saying the commenter was "one of those people", i.e, a bad programmer.

What are everyone elses views on Self Describing Code vs Commenting Code?

答:
The Short, Better, and Correct Answer

The idea that well-written, "self-documented code" is all you need is an anti-pattern and should die, even when it makes exceptions for comments that explain "why". It's a myth that you can always write all code for any algorithm clear enough for any programmer to glance at and get it (or that it won't require refactoring or organizational time you don't have).  Even more importantly, more often than not, programmers who think they write clear code do not.

A much better answer than comments should only be used to explain "why" is that comments should:

explain "why" (of course)

explain "what" on individual lines only when the code is complex or the purpose is unclear and it can't be or isn't worth simplifying further

explain "what" for blocks of code to speed up comprehension and locating what you need

The Explanation to Back It Up

People erroneously think the only reason people use comments is to explain what a line of code means.  The truth is a large purpose of commenting code is to make it quicker to glance through your code and find what you're looking for. When I come back to code later or read someone else's code, sure, I can read and understand a section of well written code - but isn't it faster and easier to read the comment at the top saying what that section of code does and skip it altogether if it's not what I'm looking for?  Why sit there and figure out code at all, even if it's well written, if you can glance at a couple comments and understand an entire function?  That's why we use descriptive names for functions - no one says I don't need to use a descriptive name for my function because someone can just look through my cleanly written code to see what it does.

For example, if I'm looking through someone else's function, is it easier to go line by line through the code to see what it's doing or to glance at three well written comments throughout the function to see exactly what the function is doing and where it's doing it?

Another anti-pattern is the overuse of functions to comment your code.  Well named functions are an important part of code documentation, but sometimes programmers separate 2-3 lines of code that will never be used anywhere else into a function for documentation purposes.  Why is overusing functions any better than overusing comments?  Using functions like that is the same as embracing GOTO statements - it creates spaghetti code that can be a pain to follow.

Essentially, when you work in an enterprise environment, where people are constantly sharing code and people don't always have the time to make their code perfect, a few good comments can save tons of time and frustration.  And remember, while you may be a guru who can read through code at light speed, not everyone in your office probably is.

ContentLicense: CC BY-SA 2.5


问:
What project meeting structure should a single developer choose?
I am a solo developer working on a decently small project with about 3 other people (non-developers). These other people are involved in the project in non-development ways and one is also my manager. Everyone is pretty open to ad hoc discussions, too.

My manager just gave me what seems like a dream come true - I was tasked with determining what meeting structure would work best for the project. This seems like a wonderful way to deal with meeting overload and/or pointless meetings.

With great power comes great responsibility, as now, if I suggest something which ultimately results in much wasted time it's my fault.

I have never had such a blank slate to think how I would structure meetings. My thoughts are:

Daily "touch base/status update" meeting for 15min or less (similar to standup meetings) to communicate daily objectives and review previous day. Or, it seems I could just get a whiteboard and put it at my desk to communicate this info.

As needed meetings to make specific decisions or address questions any of the team has

... I don't see the need for a weekly "status" project meeting. I'm also not sure the second bullet would require many formally scheduled meetings.

My concern is these "developer focused" (ie me) might cause alienation with others or make my manager feel a loss of control on the project, as this structure would be considerably different than most projects are run.

What project meeting structure should a single developer choose?

Addressing comments:

What are the other people contributing? Are they the intended users of this project? Working on non-development aspects of it (such as website themes & images or a DBA, or QA testing)? Other levels of management/administration?

They are some of the eventual users and are interested in the overall workflow. They are also contributing to several areas of forms/documents (the format of which will not affect any development work).

Are you able to get feedback from the other two members? Some managers need to have a regularly scheduled meeting or they'll never be able to fit it into their schedule.

Getting time does not seem to be a problem going forward.

答:
None

Unless you have something that requires a highly interactive group discussion (such as demonstrating an iteration), or just need to be seen working, tying up 4 people in a meeting, even for 15 minutes, will be wasteful.

In-person meetings are the highest-bandwidth form of communication available; they are also the most expensive form of communication. Use them wisely, and only when necessary.


答:
It's possible that the devs simply don't get DVCS well enough, but I think it's far more likely that you've simply got too much going on, and the devs can't keep track of what they are doing from moment to moment. They forget what branch they are supposed to be working in, and their changes end up in the wrong place.

I'd suggest that you've got a problem with the fact that everyone is working in all of these branches on a regular basis.

@andy256's suggestion of a separate repository for prod would certainly help, but you might need to consider parceling out the work differently, or perhaps arranging things so that no dev is working on more than one branch in a given week.

Title: Stopping developers committing to the wrong branch on DVCS

Body:
The problem

I am on a software project which has about 10 developers, we share source code via Mercurial. We have a development and production branch per release. Repeatedly during the course of the project we have had source code from one branch i.e. v1 getting into patch and maintenance branches for earlier releases of software i.e. v2.

This results in either time spent backing out the wrong commit, or wrong (possibly non-QAd) code reaching and getting deployed in the wrong branch if we don't notice that the code has gone into the wrong branch.

Our branch and merge design/method

```<code>               v1-test   v1-patch1   v1-patch2
               ^---------^-----------^                v1-prod
              /         / \           \
-----------------------/   \           \              v1-dev
              \             \           \
               --------------------------\            v2-dev
                             \       \    \
                              ^-------^-------------  v2-prod
                              v2-test v2-patch1
</code>```

Hence we will work on a release development branch, until it's deemed ready, branch it off for a single testing/UAT/Production branch, where all releases and maintenance is done. Tags are used to build releases of this branch. While v1 is being tested, a branch will have been made for v2 and developers will start working on new features.

What tends to happen is that a developer commits work due for v2-dev branch into v1-dev or v1-prod, or worse, they merge v2-dev into v1-prod (or similar such mistakes).

We tell most developers not to access the -prod branches, however code still sneaks in. A group of more senior developers `look after' the -prod branch.

It should be noted that while v2 has just started development, there may still be some quite hefty patches going into v1 to fix issues. I.e. v1 may not just be getting the odd small patch.

What we've tried so far

Having a separate -prod branch, with gatekeepers. A -prod branch should raise warnings through its name and most developers don't need to ever be in that branch. This has not really reduced the problem.

Raised awareness of this problem amongst the developers, to try and make them more vigilant. Again this has not been very successful.

Possible reasons I see for developers committing to the wrong branch

Too complex a branch design

Having active development in multiple branches in parallel. (The project does exhibit symptoms of using the avalanche-model.)

Developers don't understand the DVCS well enough

Questions I've read which were somewhat relevant

I've read this question on not committing to the wrong branch and I feel that the answers regarding visual cues may be helpful. However I am not entirely convinced that the problems we're experiencing are not symptoms of a more fundamental problem.

With the visual clues, we can incorporate them into the command line easily, however about half the team use eclipse which I'm unsure how to incorporate visual cues.

Question

What methods, in the form of software, project management or governance can we use to reduce (ideally stop) commits to the wrong branch taking up our time or dirtying our deployed code?

Specific comment on the reasons I believe may be contributing as outlined above would be appreciated, but this shouldn't limit your reply.


问:
Is it *ever* okay to catch StackOverflowError in Java?
I used to think that it's not, but yesterday I had to do it. It's an application that uses Akka (an actor system implementation for the JVM) to process asynchronous jobs. One of the actors performs some PDF manipulation, and because the library is buggy, it dies with a StackOverflowError every now and then.

The second aspect is that Akka is configured to shutdown its whole actor system if any JVM fatal error (e.g. StackOverflowError) is caught.

The third aspect is that this actor system is embedded inside a web app (for WTF-ish, legacy, reasons), so when the actor system is shut down, the web app is not. The net effect is that on a StackOverflowError our job processing application becomes just an empty web app.

As a quick fix I had to catch the StackOverflowError being thrown, so that the thread pool of the actor system isn't torn down. This lead me to think that maybe it's sometimes okay to catch such errors especially in contexts like this? When there's a thread pool processing arbitrary tasks? Unlike an OutOfMemoryError I can't imagine how a StackOverflowError can leave an application in an inconsistent state. The stack is cleared after such an error, so computation can go on normally. But maybe I'm missing something important.

Also, let it be noted that I'm all for fixing the error in the first place (as a matter of fact I have already fixed an SOE in this same app a few days ago), but I really don't know when this kind of situation might arise.

Why would it be better to restart the JVM process instead of catching the StackOverflowError, mark that job as failed, and continue with my business?

Is there any compelling reason to never catch SOEs? Except "best practices", which is a vague term that tells me nothing.

答:
I don't know if there are any JVM-specific risks here, but overall it seems quite sensible.

For example there are recursive algorithms, like naive quicksort, that have log(n) stack depth in a typical case, but in the worst case they degrade to depth n that can blow up the stack.

The worst case is rare, and unlikely to happen again if you restart sort on the partially-sorted set, so it makes a lot of sense to catch stack overflow exception when it happens and restart work instead of trying to prevent error from happening or killing entire application.


问:
Why are we supposed to use short functions to sectionalize our code?
I've seen an increasing trend in the programming world saying that it is good practice to separate code blocks into their own functions.  Obviously, if that code block is reusable, you should do that.  What I do not understand is this trend of using a function call as essentially a comment that you hide your code behind if the code is not reusable.  That's what code folding is for.

Personally, I also hate reading code like this because it feels like it has the same problem as the GOTO statement - it becomes spaghetti code where if I'm trying to follow the program's flow I'm constantly jumping around and can't logically follow the code.  It is much easier to me to follow code that is linear but has a single comment over sections of code labeling what it does.  With code folding, this is essentially the same exact thing, except the code stays in a nice linear fashion.  When I try to explain this to my colleagues, they say comments are evil and clutter - how is a comment on top of a block of folded code any different from a function call that will never get called more than once? How is overusing functions different than overusing comments? How are frequent use of functions different from the problems with GOTO statements? Can someone please explain the value of the programming paradigm to me?

答:
I believe this approach is done primarily to make code easier to read. And yes, I agree, it is possible to go too far down this road, where every function only contains 2-3 lines and the result is that the main function is no easier to read. Doing this well is more an art than anything else.

My personal guide is that I only split code out to a separate and (most likely) single-use function if it will reduce the length of the main function by 10 lines or more, if the lines being separated out are all logically part of the same task, and if that task can be given an easy-to-understand name (because otherwise the main function won't be any more readable).


答:
Code organization is all about displaying enough information to convey a single idea. The sweet spot is getting your code pared down enough that a single idea can fit in a single unit of code. Your unit of code can be a function, a class, etc. These are merely tools of organization. As with any tool, it can be over used or used incorrectly.

Having a one line function makes no sense unless the function conveys a meaningful idea. Having a large imperative function that conveys many ideas is hard to digest and reuse. It's all about striking the right balance, and even that is subjective.

Title: Why are we supposed to use short functions to sectionalize our code?

Body:
I've seen an increasing trend in the programming world saying that it is good practice to separate code blocks into their own functions.  Obviously, if that code block is reusable, you should do that.  What I do not understand is this trend of using a function call as essentially a comment that you hide your code behind if the code is not reusable.  That's what code folding is for.

Personally, I also hate reading code like this because it feels like it has the same problem as the GOTO statement - it becomes spaghetti code where if I'm trying to follow the program's flow I'm constantly jumping around and can't logically follow the code.  It is much easier to me to follow code that is linear but has a single comment over sections of code labeling what it does.  With code folding, this is essentially the same exact thing, except the code stays in a nice linear fashion.  When I try to explain this to my colleagues, they say comments are evil and clutter - how is a comment on top of a block of folded code any different from a function call that will never get called more than once? How is overusing functions different than overusing comments? How are frequent use of functions different from the problems with GOTO statements? Can someone please explain the value of the programming paradigm to me?


答:
The problem is you are changing what the meaning of a branch is part way through the process.

Initially, the v1 dev branch is for development.  All new features go there.  At some point in the future, it becomes a maintenance branch for the v1 release branch. This is the crux of the problem.

Its not that the developers are sloppy, its that the permissions and roles of the branch are sloppy and subject to change.

What you need to do is establish what role each branch as, and maintain that role.  If the role changes, branch.

For example:

```<code> developer
  commits    |   |  |   |    |     |   |     |
             v   v  v   v    v     v   v     v
 dev  +--+---------------------+------------------->
         |           ^    ^    |           ^    ^
         |           |    |    |           |    |
 v1      +----+------+----+    |           |    |
           prod  patches       |           |    |
                               |           |    |
                               |           |    |
 v2                            +-----+-----+----+
                                  prod  patches
</code>```

In this model, developers always commit to dev.  If you are building a patch, you check the patch into that release's branch (or better yet, branch the release branch for a patch and then merge it back into the release branch).

One article that you should read (and its probably an understatement for 'should') is Advanced SCM Branching Strategies by Stephen Vance.

In this paper, I first define branching in a general sense. I then discuss various strategies for branching, starting with the obvious and moving up to several that are more appropriate for larger development efforts. Along the way, I discuss the pros and cons of each strategy, using them to motivate the changes that compose the more complex strategies...

In this article, he identifies five roles that branches may have.  Sometimes a branch may fill two roles and roles do not necessarily need a new branch as long as the role policies do not change mid branch (you will occasionally see mention of "branch on incompatible policy").

These roles are:

Mainline.  This is where branches are made from.  Always branching from the mainline makes merges easier since the two branches will have a common ancestor that isn't branch upon branch upon branches.

Development.  This is where developers check in code.  One may have multiple development branches to isolate high risk changes from the ones that are routine and mundane.

Maintenance. Bug fixes on an existing production environment.

Accumulation.  When merging two branches, one may not want to risk destabilizing the mainline.  So branch the mainline, merge the branches into the accumulator and merge back to the mainline once things are settled.

Packaging.  Packaging a release happens in the packaging branches.  This often becomes the release and serves to isolate the release effort from development.  See How to deal with undesired commits that break long-running release builds? for an example of where the packaging conflicts with development.

In your example, you've got a cascading mainline (this is a problem - it makes merges more difficult - what happens if you want to merge a fix for v1 into v2 and v3?), a dev branch that becomes a maintenance branch (change of policy, this is a problem).

Ok, you say, thats great, but this was written for perforce which is a centralized VCS - I'm using DVCS.

Lets look at the git-flow model and see how it applies.

The master branch (blue) is the release branch - for tagging.  It is not the mainline.  The mainline is actually the develop branch (yellow).  The release branches (green) are the packaging role.  Low risk development happens in the mainline, high risk development happens in the feature branches (pink).  In this model, accumulation is done in the develop branch.  Maintenance are considered 'hot fixes' which are red.

While the role policies aren't exact match (each product has its own slightly different lifecycle), they are a match.

Doing this should simplify your branching policy and make it easier for everyone involved.

Body:
The problem is you are changing what the meaning of a branch is part way through the process.

Initially, the v1 dev branch is for development.  All new features go there.  At some point in the future, it becomes a maintenance branch for the v1 release branch. This is the crux of the problem.

Its not that the developers are sloppy, its that the permissions and roles of the branch are sloppy and subject to change.

What you need to do is establish what role each branch as, and maintain that role.  If the role changes, branch.

For example:

 developer
  commits    |   |  |   |    |     |   |     |
             v   v  v   v    v     v   v     v
 dev  +--+---------------------+------------------->
         |           ^    ^    |           ^    ^
         |           |    |    |           |    |
 v1      +----+------+----+    |           |    |
           prod  patches       |           |    |
                               |           |    |
                               |           |    |
 v2                            +-----+-----+----+
                                  prod  patches

In this model, developers always commit to dev.  If you are building a patch, you check the patch into that release's branch (or better yet, branch the release branch for a patch and then merge it back into the release branch).

One article that you should read (and its probably an understatement for 'should') is Advanced SCM Branching Strategies by Stephen Vance.

In this paper, I first define branching in a general sense. I then discuss various strategies for branching, starting with the obvious and moving up to several that are more appropriate for larger development efforts. Along the way, I discuss the pros and cons of each strategy, using them to motivate the changes that compose the more complex strategies...

In this article, he identifies five roles that branches may have.  Sometimes a branch may fill two roles and roles do not necessarily need a new branch as long as the role policies do not change mid branch (you will occasionally see mention of "branch on incompatible policy").

These roles are:

Mainline.  This is where branches are made from.  Always branching from the mainline makes merges easier since the two branches will have a common ancestor that isn't branch upon branch upon branches.

Development.  This is where developers check in code.  One may have multiple development branches to isolate high risk changes from the ones that are routine and mundane.

Maintenance. Bug fixes on an existing production environment.

Accumulation.  When merging two branches, one may not want to risk destabilizing the mainline.  So branch the mainline, merge the branches into the accumulator and merge back to the mainline once things are settled.

Packaging.  Packaging a release happens in the packaging branches.  This often becomes the release and serves to isolate the release effort from development.  See How to deal with undesired commits that break long-running release builds? for an example of where the packaging conflicts with development.

In your example, you've got a cascading mainline (this is a problem - it makes merges more difficult - what happens if you want to merge a fix for v1 into v2 and v3?), a dev branch that becomes a maintenance branch (change of policy, this is a problem).

Ok, you say, thats great, but this was written for perforce which is a centralized VCS - I'm using DVCS.

Lets look at the git-flow model and see how it applies.

The master branch (blue) is the release branch - for tagging.  It is not the mainline.  The mainline is actually the develop branch (yellow).  The release branches (green) are the packaging role.  Low risk development happens in the mainline, high risk development happens in the feature branches (pink).  In this model, accumulation is done in the develop branch.  Maintenance are considered 'hot fixes' which are red.

While the role policies aren't exact match (each product has its own slightly different lifecycle), they are a match.

Doing this should simplify your branching policy and make it easier for everyone involved.


答:
I don't see the need to read every single line of code to understand what a program does. If the functions are named appropriately, why even look at the contents unless it does not give you the result you expect?

Another advantage of writing smaller functions is for unit testing. Write a small function that passes its test(s) and forget about the details. The key to debugging and trouble-shooting is review and change as few lines of code as possible.

The GOTO analogy may explain the "jump to" part of your problem, but you know exactly where a function is going to return. That is a huge difference.

It's very easy to get accustomed to a lot of things in programming. Designing with a GUI is no help when you eventually have to look at the underlying code and are completely lost.


答:
It is easier to bust things out and re-use them as-needed than it is to read and understand a cacophony of completely pointlessly busted out micro-ideas that will never get re-used and represent very little on their own merit.

Always err on the side of clarity but when it helps nothing, leave the un-reused stuff inside the one func. You Ain't Going to Need It in that state.


答:
As a sole developer, your biggest issue is visibility.  My recommendation is to do full sprint cycles, like in an Agile project.  Every two weeks, demo a little bit more functionality (this could be in a half hour to hour long meeting.  Every day have a standup explaining what you did yesterday, what you'll be doing today and any roadblocks you have.

By doing this you will be communicating to the others exactly where the product is at at any one time.  They will feel involved, everyone will know exactly where the progress of building the product is at and decisions can be made to scrap/introduce features as necessary.

And a 10 minute standup on a daily basis only "wastes" an hour a week.  Having an hour long demo once a fortnight limits your meeting exposure to an average of 1.5h per week, which isn't a lot.

Body:
I am a solo developer working on a decently small project with about 3 other people (non-developers). These other people are involved in the project in non-development ways and one is also my manager. Everyone is pretty open to ad hoc discussions, too.

My manager just gave me what seems like a dream come true - I was tasked with determining what meeting structure would work best for the project. This seems like a wonderful way to deal with meeting overload and/or pointless meetings.

With great power comes great responsibility, as now, if I suggest something which ultimately results in much wasted time it's my fault.

I have never had such a blank slate to think how I would structure meetings. My thoughts are:

Daily "touch base/status update" meeting for 15min or less (similar to standup meetings) to communicate daily objectives and review previous day. Or, it seems I could just get a whiteboard and put it at my desk to communicate this info.

As needed meetings to make specific decisions or address questions any of the team has

... I don't see the need for a weekly "status" project meeting. I'm also not sure the second bullet would require many formally scheduled meetings.

My concern is these "developer focused" (ie me) might cause alienation with others or make my manager feel a loss of control on the project, as this structure would be considerably different than most projects are run.

What project meeting structure should a single developer choose?

Addressing comments:

What are the other people contributing? Are they the intended users of this project? Working on non-development aspects of it (such as website themes & images or a DBA, or QA testing)? Other levels of management/administration?

They are some of the eventual users and are interested in the overall workflow. They are also contributing to several areas of forms/documents (the format of which will not affect any development work).

Are you able to get feedback from the other two members? Some managers need to have a regularly scheduled meeting or they'll never be able to fit it into their schedule.

Getting time does not seem to be a problem going forward.


问:
Why is NoSQL faster than SQL?
Recently I was asked:

Why is NoSQL faster than SQL?

I didn't agree with the premise of the question... it's just nonsense for me personally. I can't see any performance boost by using NoSQL instead of SQL. Maybe SQL over NoSQL, yes but not in that way.

Am I missing something about NoSQL?

答:
NoSql supported by column oriented databases where RDBMS is row oriented database... And say for example we have a Employee table with Name, Age, Salery, Address, EmployeeId etc... we put same table in MySql (RDBMS support) and HBase (NoSQL support). If a customer/client writes a query to get the average Age or Salery details from 1Lakh employees records... what happens?

In RDBMS it will go around each row and collects the value and sum & divide for resulting. When it comes to Columnar database no need to worry about all one lakh row iterations. But deal with only one Row which is faster to compute. So this way sometimes NoSQL is faster than SQL. This case NoSQL don't care about ACID complaints are worth!

Title: Why is NoSQL faster than SQL?


问:
Can Scrum use technical specifications in the Product Backlog rather than user stories?
At the company I am currently working for we started to do Scrum projects. It was not so hard to convince the managers to move from waterfall to Scrum. We're doing a project where we rebuild our platform from scratch. So (most) functionality is known and most improvements are rather technical.

In this it could be justified to have technical tasks rather than user stories. Our backlog has got all kinds of technical tasks like:

Rewrite DB class from MySQL to PostgreSQL.

Implement system logging.

Rewrite object cache.

Things that come up during the stand-ups include that long "research tasks" are wanted, but they are never done. Also, the team members claim in the middle of the sprint that unplanned tasks need to be added.

How should a Scrum Master deal with this? Could it be that for this kind of project, Scrum is NOT the way to go?

答:
Some of the below strategies may help,

Yes, you can Have a backlog with with Technical stories.

Like a user story this also should be Technical Stories, focusing on the benefits it will be bring to the end user. Here is some tips writing it. These are stories which will bring intrinsic value to the product like you want to move to a better back-end etc.

For Investigation (Research) Tasks Use Spike

A spike is an experiment that allows developers to learn just enough about something unknown in a user story, e.g. a new technology, to be able to estimate that user story. A spike must be time-boxed. This defines the maximum time that will be spent learning and fixes the estimate for the spike.


答: A well defined identifier for the function must give you a wide knowledge about the function without go into it. Reusable or not, a function is intended to follow the divide and conquer principle, and in most cases a programmer start designing/implementing/coding a non-main function and only then a call is necessary.


答:
Which NoSQL database? Which SQL database? If someone tells you that NoSQL is faster than SQL then you should walk away. Or better yet watch this video:

http://www.youtube.com/watch?v=b2F-DItXtZs

I won't say half the things claimed about NoSQL are wrong, but I will say that there is a lot of NoSQL fanboyism out there from people who really don't understand it very well.

SQL has its limits (of course) but it also is a very mature technology, which is well understood, and has a large pool of developers who understand how to use it well. I can not say the same for all forms of NoSQL.

Title: Why is NoSQL faster than SQL?

Body:
Recently I was asked:

Why is NoSQL faster than SQL?

I didn't agree with the premise of the question... it's just nonsense for me personally. I can't see any performance boost by using NoSQL instead of SQL. Maybe SQL over NoSQL, yes but not in that way.

Am I missing something about NoSQL?


答:
I've seen an increasing trend in the programming world saying that it is good practice to separate code blocks into their own functions.

I wouldn't have called this an "increasing trend".  I was taught that splitting overly large methods into smaller methods improved readability ... ummm ... nearly 40 years ago.  And I was taught the design-time equivalent ... functional decomposition.

What I do not understand is this trend of using a function call as essentially a comment that you hide your code behind if the code is not reusable. That's what code folding is for.

No.  Functional decomposition is not primarily about creating reusable components / functions / methods / whatever.  What is actually about is making the codebase easier to understand by reducing it into "bite sized chunks" that make it easier to understand.

IMO, you can't achieve the same thing with IDE code folding. Code folding typically does not take account of the effects of folded code on other code.  For example:

```<code>    int a = 1;
    if (something()) {
        a = a + 1;
    }
    print(a);
</code>```

If the IDE decided to fold the body of the if statement then the programmer is liable to not notice that a may change from its initial value.  If it was up to the programmer to decide what to fold, then he / she has to understand the code in order to decide ... which makes the process circular.

By contrast, if the code was written like this:

```<code>   int a = 1;
   a = someMethod(a);
   print(a);
</code>```

where

```<code>   function someMethod(a):
       return something() ? a + 1 : a;
</code>```

you don't have the same "surprise".

(Obviously this is a highly unrealistic example ... but it illustrates the problem with code folding.)

Body:
I've seen an increasing trend in the programming world saying that it is good practice to separate code blocks into their own functions.

I wouldn't have called this an "increasing trend".  I was taught that splitting overly large methods into smaller methods improved readability ... ummm ... nearly 40 years ago.  And I was taught the design-time equivalent ... functional decomposition.

What I do not understand is this trend of using a function call as essentially a comment that you hide your code behind if the code is not reusable. That's what code folding is for.

No.  Functional decomposition is not primarily about creating reusable components / functions / methods / whatever.  What is actually about is making the codebase easier to understand by reducing it into "bite sized chunks" that make it easier to understand.

IMO, you can't achieve the same thing with IDE code folding. Code folding typically does not take account of the effects of folded code on other code.  For example:

    int a = 1;
    if (something()) {
        a = a + 1;
    }
    print(a);

If the IDE decided to fold the body of the if statement then the programmer is liable to not notice that a may change from its initial value.  If it was up to the programmer to decide what to fold, then he / she has to understand the code in order to decide ... which makes the process circular.

By contrast, if the code was written like this:

   int a = 1;
   a = someMethod(a);
   print(a);

where

   function someMethod(a):
       return something() ? a + 1 : a;

you don't have the same "surprise".

(Obviously this is a highly unrealistic example ... but it illustrates the problem with code folding.)


答:
The act of splitting up your functions and methods into smaller ones is not just for re-usability.  It is a good general design practice because it encourages de-coupled code.  De-coupled code is easier to read and maintain.

What do I mean by this?

If I have a 100 line of code function.  It handles what happens when the user makes a change to a domain object.  This function is long and is doing 100 discrete things.

If I split that into two functions, one inside the other, the first function is now doing 51 discrete things and the second function is doing 50 discrete things.  However, the second function is probably doing only one thing that can cause side-effects for the other 50 things.  If there is a bug in the main function, I can probably isolate it to either my new method call or one of the other 50 lines of code.  In one simple refactoring, I've cut the amount of code that I have to grok to find my bug in half.

As an industry, we have worked harder and harder to remove things like global variables and system-wide dependencies out of our languages and code.  To some extent, we can consider every chunk of procedural code as its own global scope.  When framed this way, it becomes very easy to see that we wish to cut down the size of this scope as much as is possible.  Using small methods which do one thing helps with this a lot.  It's not just a readability issue.


问:
Subtractive color mixing algorithm
Here is my problem:

I have a set of 'n' colors including the primary colors and their codes in hexadecimal. Now given another color 'x' I wonder if it's actually possible to come up with a mix between two or more of the colors of the set that will produce 'x'. The mix should be subtractive.

Here is an example of the result of the algorithm:

My set of colors is: c1, c2, c3, c4, c5, c6.
I am trying to find the mix to produce the color x.
The result could be: 50% of c1, 25% of c4 and 25% of c5.

If anyone could point me in the right direction (or at least tell me if it is unfeasible), any help would be gladly appreciated!

答:
This is a basic linear algebra problem. Let b = [ b1, b2, b3 ] be your mixed colour, x = [ x1, x2, ... xn ] be your solution, I = [ 1, 1, 1 ] (or whatever your white value is), and A = [ c1, c2, ..., cn ] be your colour set where each ci is a column vector in the matrix A. You must solve for x in the the equation I - Ax = b or Ax = I - b. You can check out the Khan Academy video about how to do that here if you do not already know how.

If there is no solution to this equation there is also no subtractive mix (obviously), but there is also no subtractive mix if there is a value in x, xi, that is negative or greater than one. If there is a negative value then you are actually adding the colour, and if there is one greater than one, you are subtracting the colour more than once. Otherwise your solution is the vector x.

Title: Subtractive color mixing algorithm


问:
Where should I put methods that make an Http Request to get data from a web service in iOS development?
I have a Model Car in my iOS application where it's parameters like name, year, value etc are fetched from a web service in order to fill a list with cars data.

Where should I put the method that asynchronously goes to the server and returns an array of cars (this method already converts the JSON to a Car array)?

My current approach is a static method in my Car class that receives an HttpClient (so I'm able to unit test it mocking the client) and returns an NSArray of cars, is this good?

What have you guys done in this situation?

I'm concerned because I recently started reading clean code which says that a Class should do only one thing, and the way I have it now appears to do 2 things (hold information about a Car and get a list of cars).

答: You can call asynchronous method inside of ViewDidLoad method when array returns from web, refresh the view.You can save the array in database, so you will need not to load data from web every time the Viewcontroller load.</p>

OwnerDisplayName: Raphael Oliveira


问:
Importance of stored procedures and triggers in building web applications?
Almost in every interview for the position of web developer, they ask about stored procedures and triggers well I am aware from their definition and basic usage but the truths is I have never used any of them in any of my project. Well I have seen other developers who used them but only when they were the only solution.

My question is are they really important and interview is incomplete without asking questions about triggers and stored procedures. I tend to do keep almost all my logics in PHP, like if change in one database table row will require change in other database table row, I run another query from PHP rather than writing trigger, is it wrong or bad practice? do I need to change my approach? any examples in which use of stored procedures and triggers are better than performing similar operations in PHP?

答:
I like using stored procedures when using MSSQL, because in MSSQL, you can assign user permissions only to stored procedure. My limited experience with MySQL and Postgres show that stored procedures are still a good practice, but permissions must always be granted on tables used by procedure.

Basically, I use stored procedures to separate SQL syntax from the project itself. You know, get rid of all SELECT statements in code. It is also easier to change a stored procedure than it is to locate the correct SQL statement in code.

As for triggers, we are abusing them at current gig to log data on insert and update to log tables (company policy, not my idea). Otherwise, I would advise to stay away from them, unless they are absolutely necessary.


答:
First, as @Stephen C said, this isn't a new idea.  It's old, and the reason it's been around so long is that it works.

Secondly, the reason it works is the same reason functional programming is becoming a bit of a hot topic -- it makes the program easier to reason about.  It may make it harder to physically trace (sounds like an opportunity for a tool), but it makes the individual pieces easier to grok.

Take a function that takes a dozen parameters and returns a boolean -- right off the bat, you know that it will return one of two values.  You don't need to trace it out, see that it calls sixteen methods on 7 objects plus 4 utility functions, all of that is irrelevant as it returns either true or false.

Now, you may be asking how return values coorespond to breaking up functions, but really they are the same thing -- a function that takes a dozen parameters and returns a boolean, is just another way of saying that you have a series of calculations that culminate in a single result that is then used elsewhere.  A void function is simply a series of operations that logically hang together and can be treated as one.

Breaking up a large function, even if none of the pieces are reusable, means that you can hold the pieces in mind better at the appropriate level of abstraction.  A function named F which consits of nothing but 10 calls to F1, F2 and so forth, is hard to reason about only while you are trying to figure out what F does -- which a good name would reduce to a time best measured in fractions of a second.  But even a bad naming convention will make it easier to ignore the rest of the program while you focus on the step that follows 4 and precedes 6. And being broken down into steps, either the state of an object is being changed, globals are being abused, or any information that F1 wants to provide to F10 is returned and then kept in a local variable...In all cases it's going to be easier to keep track of where things are changed in smaller parts.


答:
Well I have seen other developers who used them but only when they were the only solution.

Stored procedures and queries are never the only solution. No one forces you to enforce consistency in the database. Hell, you don't even have to be using database in the first place. Or can be using one that does not have either feature.

But there are many situations where they provide some useful benefits:

Security. Many database engines can grant permission to run a stored procedure without granting general permissions to the underlying tables. Even more so using triggers to write history records (what was changed when and by whom, also called audit trail) has the big advantage that even if the application is compromised, the attackers won't be able disable the logging.

Complicated consistency rules. Sometimes you have useful integrity constraints that can't be expressed by simple foreign key, unique and similar constraints. Than it's time to check them with trigger.

Consistency between multiple applications. When you have complex query that needs to be done consistently by different clients, you can put it in stored procedure.

Shielding multiple clients from changes in the schema. If you have database accessed by multiple clients, than if you need to change the schema for one of them, stored procedures and views can hide change from the others so you don't have to update them immediately.

There are however some disadvantages, especially to stored procedures:

They make the code difficult to understand. To understand code processing a query you need to know the query and the query rarely makes sense without the code around it that processes it. For very complex schemas sometimes you can put a simpler layer of views and stored procedures on it, but definitely avoid policy of placing everything in stored procedures.

They are pain the the backside to version. Versioning application code is well mastered, but handling the database schema requires either writing lots of upgrade scripts and some machinery to apply them or lot of error prone manual work. Since triggers and stored procedures are subject to this as well, having many of them increases the work.

Title: Importance of stored procedures and triggers in building web applications?

Body:
Almost in every interview for the position of web developer, they ask about stored procedures and triggers well I am aware from their definition and basic usage but the truths is I have never used any of them in any of my project. Well I have seen other developers who used them but only when they were the only solution.

My question is are they really important and interview is incomplete without asking questions about triggers and stored procedures. I tend to do keep almost all my logics in PHP, like if change in one database table row will require change in other database table row, I run another query from PHP rather than writing trigger, is it wrong or bad practice? do I need to change my approach? any examples in which use of stored procedures and triggers are better than performing similar operations in PHP?


问:
After years of working alone, other developers will finally see my (buggy) code. What should I do?
I have been working on a system alone for about four years. I have built it from the ground up. It is not a perfect system. It is very complex, it is buggy, and the business is now becoming aware of this.

After all this time, other developers at the company are getting interested in the project, and they are becoming more involved. I am a bit worried they will blame me for the problems.

Am I being paranoid? Have others experienced a similar situation? How can I soften the glare of the spotlight on my buggy code?

答:
Its Not your Code. It is the companies Code.

They are the ones who allowed you to go 4 years without serious outside inspection of the code, they should bear responsibility. (That said, you wrote it so some of the shit will stick).

I would take this as an opportunity to embark on a really great (if painful) learning experience. If you can be harder on your code than your reviewers, then you will be seen as a positive driver of this phase, rather than a negative, defensive factor.


问:
What product is better: ADFSv2, Ping Identity, CS Siteminder?
I'm comparing different STS's for claims based authentication and am trying when it's appropriate to use each one.

It appears that ADFSv2 should be used in all Windows Environments.  Ping and Siteminder are more for the Unix side... although a sales rep said Ping was better for Windows, I didn't really understand "why"

Any comparative information is much appreciated!

答:
We are in the middle of doing SSO where I'm at right now.  We couldn't get Site Minder to let us pay for a developer license; they literally didn't return the numerous calls we made begging to use their software (one of our clients was using it and we figured it would be the easiest path).

We went with Ping Identity's Pingfederate product (or is it the other way around)?

The documentation isn't amazing, but it's working for us.  When you can get past first-level support, they have been very helpful and getting us going.  Your application will be dependent upon their APIs, but your application will also support numerous open standards for SSO.  They also have consulting available to do the heavy lifting if you have the budget.


答:
I'm in the very same situation as you are. The place I'm at is where I've been for the last 5 years, and I've spent 80% of my time building a system for internal use from scratch - on my own.

This is my first job, meaning that it is the first job I got after i graduated. I, just as you, know that if I were to begin work on the very same system today I would to things differently. However, that's the beauty of experience. As long as you are able to identify the mistakes you've done, it's a good sign. It means that you've learnt something.

As for the things you have not identified yourself, but which the others probably will : embrace the feedback you get and learn from it. Don't be afraid of the feedback you get. You did things for a reason when you built it, and as long as you explain why things were made a certain way, then there's ground for a good discussion. After all, you're all grown ups so I assume you will talk about it the way grown ups do. As for the question of "blame"; you're the one who built the system so it's pointless to even talk about that. You all know that it's your "fault". The focus should be on how to improve it, and you will get a great learning opportunity for free.

I'd love if someone else would take a look at the system I've built. I, just as you, work alone and if there is something I miss it's being able to discuss my work with a colleague. I'd say you should value the opportunity :-)

Title: After years of working alone, other developers will finally see my (buggy) code. What should I do?

Body:
I have been working on a system alone for about four years. I have built it from the ground up. It is not a perfect system. It is very complex, it is buggy, and the business is now becoming aware of this.

After all this time, other developers at the company are getting interested in the project, and they are becoming more involved. I am a bit worried they will blame me for the problems.

Am I being paranoid? Have others experienced a similar situation? How can I soften the glare of the spotlight on my buggy code?


答:
Writing short functions has a few direct benefits and a lot of indirect benefits, as explained at length in Robert C. Martin's book Clean Code. Off memory:

Improves readability, because short functions are easier to read at a glance

Makes it easier to reuse those smaller functions later (I know you eliminated this possibility as a presupposition, but...)

The indirect benefits are legion, and can be rephrased as "what you don't get if you are unable to refactor a large function into smaller functions":

Minimises side effects (if you're in a long function, it's entirely possible for a variable to be modified hundreds of lines later - very difficult to track in your head)

Makes it obvious which variables are used, and for what - input, output - which makes it easy to track dependencies

By using meaningful function names, it encourages clear code (if you can't summarise what a function does in a few words...)

Hopefully, when you've refactored your big function into small functions that do very little, you will notice common patterns, such that those functions that you thought couldn't be reused, can. Or at least replaced with generic algorithms.

These reasons are well-understood and you can read all about them through the books or related answers. You are on to something with the second paragraph though, which I'll highlight here:

Short functions are great, but our IDEs are designed to make them harder!

You hinted at this with your mention of code folding. Why is it that we can do this:

```<code>SomeLongFunction(doohickey) {
    [+] /// Frobnicate the doohickey
    foreach (d : doohickeys) {
        [+] /// Reticulate the doohickey
    }
}
</code>```

... and expand to see the actual code, in-line, by unfolding the [+]s, but we can't have this:

```<code>SomeLongFunction(doohickey) {
    splines = FrobnicateTheDoohickey(doohickey);
    foreach (d : doohickeys) {
        ReticulateTheDoohickey(d);
    }
}
</code>```

... and "expand" the function calls? We could ask the IDE to take us to those function definitions, but depending on where that is, we could be taken to a new class in a new file, or a new location in the same file, and lose the calling context! Sure there are tools that let you easily jump between contexts, but why can't we view all the code in-line, like we would have if we used code-folding? This is entirely backwards; IDEs should help us write clean code by making things easiest when we do, and not encourage us to write bad code by introducing features that do so such as code folding.

Here are the advantages of being able to view code in-line (whether that's folding or calling other functions):

Gives me the choice of viewing the code at any granularity - I can traverse it BFS, DFS, or any combination in between.

With the code in one context, I can easily find code that is executed earlier, or later, by (gasp) scrolling up or down

By expanding certain folded sections (again, at my choice) I have a better sense of the complexity of the code, so it's easier to grok it. Being limited to viewing one function at a time hinders this by hiding the complexity.

Another way of looking at it is that it's analogous to having larger or multiple monitors - you are able to see more at a time, so you can understand better, even though it's often not "necessary", because good code should have short lines and short functions. By the way, multiple monitors has been proven to improve productivity. By a lot.

So why don't our editors or IDEs allow for this kind of in-line function call expansion? (if there is one please, PLEASE let me know!) I have no idea. It's clear to me that short functions has tremendous benefits. It's also clear to me that being able to view lots of code together is also beneficial. Why can't we have both?

Body:
Writing short functions has a few direct benefits and a lot of indirect benefits, as explained at length in Robert C. Martin's book Clean Code. Off memory:

Improves readability, because short functions are easier to read at a glance

Makes it easier to reuse those smaller functions later (I know you eliminated this possibility as a presupposition, but...)

The indirect benefits are legion, and can be rephrased as "what you don't get if you are unable to refactor a large function into smaller functions":

Minimises side effects (if you're in a long function, it's entirely possible for a variable to be modified hundreds of lines later - very difficult to track in your head)

Makes it obvious which variables are used, and for what - input, output - which makes it easy to track dependencies

By using meaningful function names, it encourages clear code (if you can't summarise what a function does in a few words...)

Hopefully, when you've refactored your big function into small functions that do very little, you will notice common patterns, such that those functions that you thought couldn't be reused, can. Or at least replaced with generic algorithms.

These reasons are well-understood and you can read all about them through the books or related answers. You are on to something with the second paragraph though, which I'll highlight here:

Short functions are great, but our IDEs are designed to make them harder!

You hinted at this with your mention of code folding. Why is it that we can do this:

SomeLongFunction(doohickey) {
    [+] /// Frobnicate the doohickey
    foreach (d : doohickeys) {
        [+] /// Reticulate the doohickey
    }
}

... and expand to see the actual code, in-line, by unfolding the [+]s, but we can't have this:

SomeLongFunction(doohickey) {
    splines = FrobnicateTheDoohickey(doohickey);
    foreach (d : doohickeys) {
        ReticulateTheDoohickey(d);
    }
}

... and "expand" the function calls? We could ask the IDE to take us to those function definitions, but depending on where that is, we could be taken to a new class in a new file, or a new location in the same file, and lose the calling context! Sure there are tools that let you easily jump between contexts, but why can't we view all the code in-line, like we would have if we used code-folding? This is entirely backwards; IDEs should help us write clean code by making things easiest when we do, and not encourage us to write bad code by introducing features that do so such as code folding.

Here are the advantages of being able to view code in-line (whether that's folding or calling other functions):

Gives me the choice of viewing the code at any granularity - I can traverse it BFS, DFS, or any combination in between.

With the code in one context, I can easily find code that is executed earlier, or later, by (gasp) scrolling up or down

By expanding certain folded sections (again, at my choice) I have a better sense of the complexity of the code, so it's easier to grok it. Being limited to viewing one function at a time hinders this by hiding the complexity.

Another way of looking at it is that it's analogous to having larger or multiple monitors - you are able to see more at a time, so you can understand better, even though it's often not "necessary", because good code should have short lines and short functions. By the way, multiple monitors has been proven to improve productivity. By a lot.

So why don't our editors or IDEs allow for this kind of in-line function call expansion? (if there is one please, PLEASE let me know!) I have no idea. It's clear to me that short functions has tremendous benefits. It's also clear to me that being able to view lots of code together is also beneficial. Why can't we have both?


问:
Architecturally speaking, does a database abstraction layer, such as Microsoft's Entity Framework, void the need for a separate Data Access Layer?

The way it was

For years, I have organized my software solutions as such:

Data Access Layer (DAL) to abstract the business of accessing data

Business Logic Layer (BLL) to apply business rules to data sets, handle authentication, etc.

Utilities (Util) which is just a library of common utility methods I have built over time.

Presentation Layer which could of course be web, desktop, mobile, whatever.

The way it is now

For the past four years or so I have been using Microsoft's Entity Framework (I am predominately a .NET dev) and I am finding that having the DAL is becoming more cumbersome than clean on account of the fact that the Entity Framework has already done the job that my DAL used to do: it abstracts the business of running CRUDs against a database.

So, I typically end up with a DAL that has a collection of methods like this one:

```<code>public static IQueryable<SomeObject> GetObjects(){
    var db = new myDatabaseContext();
    return db.SomeObjectTable;
}
</code>```

Then, in the BLL, this method is used as such:

```<code>public static List<SomeObject> GetMyObjects(int myId){
    return DAL.GetObjects.Where(ob => op.accountId == myId).ToList();
}
</code>```

This is a simple example of course as the BLL would typically have several more lines of logic applied, but it just seems a bit excessive to maintain a DAL for such a limited scope.

Wouldn't it be better to just abandon the DAL and simply write my BLL methods as such:

```<code>public static List<SomeObject> GetMyObjects(int myId){
    var db = new myDatabaseContext();
    return db.SomeObjectTable.Where(ob => op.accountId == myId).ToList();
}
</code>```

I am considering dropping the DAL from future projects for the reasons stated above but, before doing so, I wanted to poll the community here for your hindsight/foresight/opinions before I get down the road on a project and discover a problem I didn't anticipate.

Any thoughts are appreciated.

Update

The consensus seems to be that a separate DAL isn't necessary but (making my own inference here) is a good idea to avoid vendor lock in.  For example, if I have a DAL that is abstracting EF calls as illustrated above, if I ever switch to some other vendor I don't need to rewrite my BLL.  Only those basic queries in the DAL would need to be rewritten.  Having said that, I am finding it tough to envision a scenario in which this would happen.  I can already make an EF model of an Oracle db, MSSQL is a given, I am pretty sure that MySql is possible as well (??) so I am not sure if the extra code would ever grant a worthwhile ROI.

答:
Nowadays the question of whether or not you are going to change data storage is more interesting than it used to be, since the question might not be just whether or not you would swap between MS SQL or Oracle SQL, but the bigger question of whether you might use on of the various NoSQL data storage offerings as your data repository.

If there was a serious possibility of that kind of change it might be valuable to keep your EF code isolated within your DAL so that you could introduce a new DAL in the future which mapped your repository requests to a NoSQL database. It might be that such a change would end up with a wholesale rewrite of your BLL anyway because of db related assumptions which creep in of course.

Similarly, EF within a DAL would probably make mocking of data access for your BLL code unit tests more straightforward.

So my view is that EF (or other ORMS) does not necessarily void the need for a data access layer.


问:
Storing a drawn graph information in database for web application
Well while developing a web application that allow users to draw graphs (flow charts, ER diagram , UML, .... etc) the information of drawn items and their relation to each other and position on canvas is expressed as JSON object

The question is:

1- is saving such graph in database as raw (json object text) is enough (in one field of a table)
2- or is it always required to break down the json object into logical pieces and store them into a well built database structure!

option 1- other than making devilopers life easier it will eleminate the need of recreating json object from small bits and pieces of information when the user open a graph he have built and saved long time ago

option 2- will have fine grain details in proper structure but will cost kind of heavy processing while opening a saved graph from Database

which way is correct way to go ?

答:
Some considerations against one giant object are:

1-Time to do specific queries (for example list properties of Customer object should not require loading a model with 200 objects)

2-Time to save changes in small number of items (for example when you change the Customer object's name, you only need to save that and not the entire model)

3-If more than 1 user will be interacting with your system, you can't use 1 huge object without the appropriate concurrency checking otherwise some users work may be lost due to overwrites.

Now if you want save the user's model into separate objects, you need to have good database design for your meta model. Such a meta model is not trivial to design.


答:
If the code is "good code" otherwise, is there a real difference in cognition between the action of expanding a code block with a purposeful comment on the one hand, and following the debugger into a well-named function on the other?

You may lose context when following the debugger into a function call - but if that makes a significant difference to the understanding of the function you are looking at then that indicates that the context is important - which implies that the purpose of the function being called isn't clear, so the code isn't "good code".  In other words, you don't really trust what the function does from its name, which is a separate issue.

A code block might be using any variables or parameters from the current function, and you will not know for sure without expanding the code block.  The comment will explain what the block does, but a function call's parameters also show the dependencies from the current context that are passed to the function.  This is actually more context while looking at less code, which is a good thing (still assuming the code is actually good, of course).

The context you are working in may force the use of a non-folding editor, in which case larger code blocks may obscure the overall structure of a function - for example if the function would fit onto a single screen with all blocks collapsed, but covers many screens with them expanded.

A nice middle ground would be to have IDEs / editors that can "inline" the code of small functions being called, so that you are looking at the context, even if that context is spread over multiple files.


问:
Why is Python written in C and not in C++?
In Python's tutorial one can read that Python's original implementation is in C;

On the other hand, the Python implementation, written in C, (...)

I'm very curious why was Python written in C and not C++?

I'd like to know the reasoning behind this decision and the answer should be supported by historical references (and not opinion based).

答:
I think the reason why it was originally written in ANSI C89 is quite simply because back then, C++ was just not a workable choice what with incompatibilities between different compilers and such. I mean, it took until, what was it, 2005, to come up with an ABI specification that would allow code compiled with one compiler to call code compiled with a different compiler?

The more interesting question is why it is still written in C89.

And there is a surprising answer: because people actually use Python on platforms for which no C++ and no C99 compiler exists! When the Forth-inspired threaded-code interpreter optimizations were merged, there was a huge discussion about it, because the code (necessarily) used computed goto which is not a part of C89. There were apparently real fears that this feature might not be available on some of the platforms that Python is currently used on.

The same thing happened with Unladen Swallow, wich uses LLVM, which is written in C++. It was made very clear that a requirement for merging Unladen Swallow into CPython would be that you can compile it without the JIT compiler, since there are platforms people run Python on, for which no C++ compiler exists.

Of course, nowadays, CPython is no longer the only Python implementation. There is PyPy, which is written in RPython (a statically typed subset of Python), Jython in Java, IronPython in C#, Pynie in NQP and PIR and so on.

ContentLicense: CC BY-SA 4.0


问:
"Extends is evil" vs. OCP?
As far as I have understood(?), the "Extends is evil" idea is in direct opposition to the Open Closed Principle?

In here, the concept of OCP is presented as inherently using Extends:

http://www.oodesign.com/open-close-principle.html

While in for example this article, the act of extending is considered a capital offense?

http://www.javaworld.com/javaworld/jw-08-2003/jw-0801-toolbox.html?page=1

What is the correct way to satisfy both OCP and not using Extends? Consider a simple BulletinBoard class that has Posts, which can be either NewsPosts or GuestbookPosts with different properties, but same methods/behaviour.

答:
The first link actually uses the strategy pattern (abstract method with implementation in each Shape subclass), so there's nothing evil going on there, because as the author says, you don't have to modify the GraphicEditor to support new shapes. Keep in mind though, that in that example, you are interested in a shared, common interface (the draw() method). You can obtain that by using an abstract method and inheritance, but you could achieve the same thing with regular interfaces.

OCP and extends are not per definition orthogonal to each other; it's just that a lot of people instinctively resort to inheritance for common properties, not for common behaviour. This can often lead to all sorts of mangled spaghetti code.

As per your example: you're not talking about behaviour, only about properties, so the question is: what kind of logic is there, and where, that would differ based upon the type of Post?

Title: "Extends is evil" vs. OCP?


答:
No, it is not.

Open-closed principle calls for encapsulating functionality in the classes. It does not say whether the interface should be defined by base class or interface.

"extends is evil" tells you to prefer implementing interfaces over extending base classes.

Since open-closed principle is fine with either, they are not opposed.

As for the "extends is evil", there are several reasons for which inheritance is used and Java does not let you distinguish them (C++ has protected and private inheritance that helps here):

Implementing common interface for other code to use.

Reusing base functionality.

Specializing behaviour of mostly generic class.

You should use interfaces for the first so you don't tie yourself into single inheritance hierarchy. That's the main message of "extends is evil".

For the second the preferred method is composition, again so you don't tie yourself to single inheritance hierarchy.

But for the thirds, extending (abstract) base class is appropriate. Your example falls in the third case.

Note however, that the abstract base class should probably still implement an interface and the code should use it whenever it does not need the particular base class, which is most of the time.

Note:

evil, adj.: Something you should avoid most of the time, but not something you should avoid all the time. For example, you will end up using these "evil" things whenever they are "the least evil of the evil alternatives." (C++ FAQ)

That applies in all similar cases where somebody calls some technique "evil". It does not mean you must not use it, ever. Just points out there is a preferred alternative.

Title: "Extends is evil" vs. OCP?

Body:
As far as I have understood(?), the "Extends is evil" idea is in direct opposition to the Open Closed Principle?

In here, the concept of OCP is presented as inherently using Extends:

http://www.oodesign.com/open-close-principle.html

While in for example this article, the act of extending is considered a capital offense?

http://www.javaworld.com/javaworld/jw-08-2003/jw-0801-toolbox.html?page=1

What is the correct way to satisfy both OCP and not using Extends? Consider a simple BulletinBoard class that has Posts, which can be either NewsPosts or GuestbookPosts with different properties, but same methods/behaviour.


答:
Well, my 2c is, following Joshua Bloch's guide lines as written in his book Effective Java:

Prefer Interfaces To Abstract Classes (it's the title of the 4.18 Chapter in that book's 2nd edition)

The key word here is "Prefer" in the same way that the principles you quote are principles and not laws. They are guide lines, to be used more often than not, but to always take into consideration if the current situation really is pertinent to a given principle or another.

More to the point, yes "extends" is evil, we should use interfaces to declare base types. How ever the point made in the book I quote (and which I personally like a lot) is that given an interface, you do get benefits from making some abstract implementations of it as helper classes for the extension of that interface. Imagine you make a Shape interface, which, amongst others, has a "setColor(Color)" method. If you know that in the context in which your interface will be used (by either you or somebody else), there's a big chance that most of the shapes will be black, you can make an abstract class called BlackShape (implements Shape) which asigns Black to the shape's color right from the start, and only leaves other methods as abstract. The important thing in such a case is to properlly document the fact that the Shape interface should be the base of any concrete Shape implementation in general, and only those who need black shapes should use the BlackShape abstract class if they so prefer. This way you ensure that noone will inadvertently think that BlackShape is the base of all shapes, and you'll avoid Liskov Substitution Principle-like violations (for example) where a Red Shape is created by extending the BlackShape class and overriding the setColor(Color) method.

Title: "Extends is evil" vs. OCP?


答:
I work with young programmers that have been taught in school that functions should be short but lack of experience to correctly factorize their code.

I'm quite often doing exactly the opposite: inlining at call sites those functions or methods to make the code readable.

While it is true that well structured code should usually be concise, probably not larger than a screen for a given function or method which functions matters.

What I do is follow code smells rules to organize my code.

Long function is a well known code smell, but it's not the only one, and certainly not the most important.

For instance if you randomly take code blocks and change then to methods as do many inexperienced programmers, you just exchange long functions with large class. Even worse, this can lead to methods receiving parts of their data through method parameters and parts from object instance. Avoiding that smell (Temporary Fields... an object oriented way of programming with globals) is much more important to me than short methods.

Also a function or method should perform some clearly identifiable task, and only one such task. I have very often seen a function perform half a task and return some parameter passed to another function a few lines later performing the other half of the task (this may be a case of Data Clumps smell). Or function whose only task is to call another one, doing basically nothing (Lazy method). This also is horrible. You can usually easily detect that looking at the use of local variables (if these local variables haven't been put in object instance as in the previous case, Temporary Field smell).

Another common smell is passing a boolean to a function: in many cases it hides a function performing one task or another depending on the provided boolean. It would probably be better to split that in two functions (I call that schizophrenic method smell).

What is interesting in that the choice of functions is not always so bad at start, but code evolution over time often lead to above problems.

My explanation of why it happens lies in programmers psychology and is probably the main drawback of splitting the code between many methods or functions.

You can easily blind yourself with functions/methods and basically forget there is code inside these methods. Some (inexperienced) programmers once they created a method take it for granted as if it were a new library calls. They won't allow themselve to change it any more they would do for some third-partu library call.
(same problem also occurs with user defined classes).

Astonishingly enough is also works the other way around: some inexperienced programmers won't create a logicaly necessary method or class if the code initial is short (typical case for curryfying a function by setting some parameters to initial values)!!!

This can become really bad if you are not aware of it and cautious.

Summarily what I'm saying is that spliting code between many methods/functions/classes can be a really good thing if you know what you are doing, or a real problem if you don't.

Because of this I put this particular smell quite low on my personal list.

Too bad it's often near head of list in code smell lists on the net. I guess it's because it is one of the easier smells to detect, both by humans and automated tools.


答:
As others said, this is the perfect opportunity to learn and improve the project.

Additionally, I would also try to document the current state from a high architectural standpoint, if that is not already done. I am not talking about class diagrams here, but more the kind of package or component diagrams or probably some very coarse (data) flow charts.

This will help your new fellows to grasp an overview of the project in a short time and will quite automatically show the spots you probably want to to some cleanup work first.


问:
Is try-finally expensive
In case of code where you have to do a resource cleanup before exiting a function, is there a major performance difference between these 2 ways of doing it.

Cleaning the resource before every return statement

```<code>void func()
{
    login();

    bool ret = dosomething();
    if(ret == false)
    {
        logout();
        return;
    }

    ret = dosomethingelse();
    if(ret == false)
    {
        logout();
        return;
    }

    dootherstuff();

    logout();
}
</code>```

Cleaning the resource in a finally block

```<code>void func()
{
    login();

    try
    {
        bool ret = dosomething();
        if(ret == false)
            return;

        ret = dosomethingelse();
        if(ret == false)
            return;

        dootherstuff();

    }
    finally
    {
        logout();
    }
}
</code>```

I did some basic tests in sample programs and there doesn't seem to be much of a difference. I so much prefer the finally way of doing this - but I was wondering if it will cause any performance hit in a big project.

答:
Assumption:  You are developing in C# code.

The quick answer is that there is no significant performance hit from using try/finally blocks.  There is a performance hit when you throw and catch exceptions.

The longer answer is to see for your self.  If you look at the underlying CIL code generated (e.g red-gate reflector then you can see the underlying CIL instructions generated and see the impact that way.

Title: Is try-finally expensive


答:
Instead of optimising - think of what your code is doing.

Adding the finally block is a different implementation - it means that you will logout on every exception.

Specifically - if login throws an exception, the behaviour in your second function will be different than your first.

If login and logout are not actually part of the function behaviour then I would suggest that the method should do one thing and one thing well:

```<code>    void func()
    {
            bool ret = dosomething();
            if(ret == false)
                return;

            ret = dosomethingelse();
            if(ret == false)
                return;

            dootherstuff();

    }
</code>```

and should be in a function which is already encapsulated in a context which manages login / logout since these seem fundamentally different from what your main code is doing.

Your post is tagged as Java which I'm not super familiar with but in .net I would use a using block for this:

ie:

```<code>    using(var loginContext = CreateLoginContext())
    {
            // Do all your stuff
    }
</code>```

And the login context has a Dispose method which will logout and clean up the resources.

Edit: I didn't actually answer the question!

I have no measurable evidence but I would not expect this to be any more expensive or certainly not significantly enough expensive for it to be worthy of premature optimisation.

I'm going to leave the rest of my answer because although not answering the question, I think it is helpful for the OP.

Title: Is try-finally expensive

Body:
In case of code where you have to do a resource cleanup before exiting a function, is there a major performance difference between these 2 ways of doing it.

Cleaning the resource before every return statement

```<code>void func()
{
    login();

    bool ret = dosomething();
    if(ret == false)
    {
        logout();
        return;
    }

    ret = dosomethingelse();
    if(ret == false)
    {
        logout();
        return;
    }

    dootherstuff();

    logout();
}
</code>```

Cleaning the resource in a finally block

```<code>void func()
{
    login();

    try
    {
        bool ret = dosomething();
        if(ret == false)
            return;

        ret = dosomethingelse();
        if(ret == false)
            return;

        dootherstuff();

    }
    finally
    {
        logout();
    }
}
</code>```

I did some basic tests in sample programs and there doesn't seem to be much of a difference. I so much prefer the finally way of doing this - but I was wondering if it will cause any performance hit in a big project.

Body:
Instead of optimising - think of what your code is doing.

Adding the finally block is a different implementation - it means that you will logout on every exception.

Specifically - if login throws an exception, the behaviour in your second function will be different than your first.

If login and logout are not actually part of the function behaviour then I would suggest that the method should do one thing and one thing well:

    void func()
    {
            bool ret = dosomething();
            if(ret == false)
                return;

            ret = dosomethingelse();
            if(ret == false)
                return;

            dootherstuff();

    }

and should be in a function which is already encapsulated in a context which manages login / logout since these seem fundamentally different from what your main code is doing.

Your post is tagged as Java which I'm not super familiar with but in .net I would use a using block for this:

ie:

    using(var loginContext = CreateLoginContext())
    {
            // Do all your stuff
    }

And the login context has a Dispose method which will logout and clean up the resources.

Edit: I didn't actually answer the question!

I have no measurable evidence but I would not expect this to be any more expensive or certainly not significantly enough expensive for it to be worthy of premature optimisation.

I'm going to leave the rest of my answer because although not answering the question, I think it is helpful for the OP.


问:
Should I extract specific functionality into a function and why?
I have a large method which does 3 tasks, each of them can be extracted into a separate function. If I'll make an additional functions for each of that tasks, will it make my code better or worse and why?

Obviously, it'll make less lines of code in the main function, but there'll be additional function declarations, so my class will have additional methods, which I believe isn't good, because it'll make the class more complex.

Should I do that before I wrote all the code or should I leave it until everything is done and then extract functions?

答:
Aside: I wrote this in response to dallin's question (now closed) but I still feel it could be helpful to someone so here goes

I think that the reason for atomising functions is 2 fold, and as @jozefg mentions is dependent on the language used.

Separation of Concerns

The main reason to do this is to keep different pieces of code separate, so any block of code that doesn't directly contribute to the desired outcome/intent of the function is a separate concern and could be extracted.

Say you have a background task that also updates a progress bar, the progress bar update isn't directly related to the long running task so should be extracted, even if it's the only piece of code that uses the progress bar.

Say in JavaScript you have a function getMyData(), which 1) builds a soap message from parameters, 2) initializes a service reference, 3) calls the service with the soap message, 4) parses the result, 5) returns the result. Seems reasonable, I've written this exact function many times--but really that could be split into 3 private functions only including code for 3 & 5 (if that) as none of the other code is directly responsible for getting data from the service.

Improved Debugging Experience

If you have completely atomic functions, your stack trace becomes a task list, listing all the successfully executed code, i.e:

Get My Data

Build Soap Message

Initialise Service Reference

Parsed Service Response - ERROR

would be allot more interesting then finding out that there was an error while getting data. But some tools are even more useful for debugging detailed call trees then that, take for example Microsofts Debugger Canvas.

I also understand your concerns that it can be difficult to follow code written this way because at the end of the day, you do need to pick an order of functions in a single file where as your call-tree would be allot more complex then that. But if functions are named well (intellisense allows me to use 3-4 camal case words in any function I please without slowing me down any) and structured with public interface at the top of the file, your code will read like pseudo-code which is by far the easiest way to get a high level understanding of a codebase.

FYI - this is one of those "do as I say not as I do" things, keeping code atomic is pointless unless your ruthlessly consistent with it IMHO, which I'm not.