问:
Which code is better for branch prediction optimization?
Given branch prediction, and also the effect of compiler optimizations, which code tends to offer superior performance?

Note that bRareExceptionPresent represents an uncommon condition. It is not the normal path of logic.

```<code>/* MOST COMMON path must branch around IF clause */

bool SomeFunction(bool bRareExceptionPresent)
{
  // abort before function
  if(bRareExceptionPresent)
  {
     return false;
  }
  .. function primary body ..
  return true;
}

/* MOST COMMON path does NOT branch */

bool SomeFunction(bool bRareExceptionPresent)
{
  if(!bRareExceptionPresent)
  {
    .. function primary body ..
  }
  else
  {
    return false;
  }
  return true;
}
</code>```

答:
My understanding is that the first time the CPU encounters a branch, it will predict (if supported) that forward branches are not taken and backwards branches are.  The rationale for this is that loops (which typically branch backwards) are assumed to be taken.

On some processors, you can give a hint in the assembly instruction as to which path is the more likely.  Details of this escape me at the moment.

Additionally, some C compilers also support static branch prediction so that you can tell the compiler which branch is more likely.  In turn it may reorganize the generated code, or use modified instructions to take advantage of this information (or even just flat out ignore it).

```<code>__builtin_expect((long)!!(x), 1L)  /* GNU C to indicate that <x> will likely be TRUE */
__builtin_expect((long)!!(x), 0L)  /* GNU C to indicate that <x> will likely be FALSE */
</code>```

Hope this helps.

Body:
My understanding is that the first time the CPU encounters a branch, it will predict (if supported) that forward branches are not taken and backwards branches are.  The rationale for this is that loops (which typically branch backwards) are assumed to be taken.

On some processors, you can give a hint in the assembly instruction as to which path is the more likely.  Details of this escape me at the moment.

Additionally, some C compilers also support static branch prediction so that you can tell the compiler which branch is more likely.  In turn it may reorganize the generated code, or use modified instructions to take advantage of this information (or even just flat out ignore it).

__builtin_expect((long)!!(x), 1L)  /* GNU C to indicate that <x> will likely be TRUE */
__builtin_expect((long)!!(x), 0L)  /* GNU C to indicate that <x> will likely be FALSE */

Hope this helps.


问:
Is it OK to split long functions and methods into smaller ones even though they won't be called by anything else?
Lately I've been trying to split long methods into several short ones.

For example: I have a process_url() function which splits URLs into components and then assigns them to some objects via their methods. Instead of implementing all this in one function, I only prepare the URL for splitting in process_url(), and then pass it over to process_components() function, which then passes the components to assign_components() function.

At first, this seemed to improve readability, because instead of huge 'God' methods and functions I had smaller ones with more descriptive names.
However, looking through some code I've written that way, I've found that I now have no idea whether these smaller functions are called by any other functions or methods.

Continuing previous example: someone looking at the code might think that process_components() functionality is abstracted into a function because it's called by various methods and functions, when in fact it's only called by process_url().

This seems somewhat wrong. The alternative is to still write long methods and functions, but indicate their sections with comments.

Is the function-splitting technique I described wrong? What is the preferred way of managing large functions and methods?

UPDATE: My main concern is that abstracting code into a function might imply that it could be called by multiple other functions.

SEE ALSO: discussions on reddit at /r/programming (provides a different perspective rather than most of the answers here) and /r/readablecode.

答:
As people pointed, this improves readability. A person reading process_url() may see more clearly what is the general process to deal with URLs just by reading a few method names.

The problem is that other people may think those functions are used by some other piece of the code, and if some of them need to be changed they may choose to preserve those functions and define new ones. This means some code becomes unreachable.

There are several ways to deal with this. First is documentation and comments in the code. Second, tools that provide coverage tests. In any case, to a great extent this depends on the programming language, these are some of the solutions you can apply depending on the programming language:

object oriented languages can allow to define some private methods, to ensure they are not used elsewhere

modules in other languages may specify which functions are visible from the outside, etc.

very high level languages like Python may eliminate the need to define several functions because they would anyway be simple one liners

other languages like Prolog may require (or strongly suggest) the definition of a new predicate for every conditional jump.

in some cases it's common to define auxiliar functions inside the function that uses them (local functions), sometimes these are anonymous functions (code closures), this is common in Javascript callback functions.

So in short, splitting in several functions is usually a good idea in terms of readability. It may not be really good if the functions are very short and this creates the goto effect or if the names are not really descriptive, in that case reading some code would require jumping among functions, which may be messy. About your concern about scope and usage of these functions, there are several ways to deal with it that are in general language dependent.

In general the best advice is to use common sense. Any strict rule is very likely to be wrong in some case and in the end it depends on the person. I would consider this readable:

process_url = lambda url: dict(re.findall('([^?=&]*)=([^?=&]*)', url))
```

Personally I prefer a one liner even if it is slightly complex rather than jumping and searching across several files of code, if it takes me more than three seconds to find some other part of code I may not even know what was I checking anyway. People who do not suffer from ADHD may prefer more explanatory names that they can remember, but in the end what you are always doing is balancing the complexity in the different levels of the code, lines, paragraphs, functions, files, modules, etc.

So the keyword is balance. A function with one thousand lines is a hell for anyone reading it, because there is no encapsulation and the context becomes just too huge. A function split into one thousand functions each one of them with one line in it may be worse:

you have some names (that you could have provided as comments in the lines)

you are (hopefully) eliminating global variables and do not need to worry about the state (having referential transparency)

but you force readers to jump back and forth.

So there are no silver bullets here, but experience and balance. IMHO the best way to learn how to do this is reading a lot of code written by other people an analyzing why is it hard for you to read it and how to make it more readable. That would provide valuable experience.

ContentLicense: CC BY-SA 3.0

Body:
As people pointed, this improves readability. A person reading process_url() may see more clearly what is the general process to deal with URLs just by reading a few method names.

The problem is that other people may think those functions are used by some other piece of the code, and if some of them need to be changed they may choose to preserve those functions and define new ones. This means some code becomes unreachable.

There are several ways to deal with this. First is documentation and comments in the code. Second, tools that provide coverage tests. In any case, to a great extent this depends on the programming language, these are some of the solutions you can apply depending on the programming language:

object oriented languages can allow to define some private methods, to ensure they are not used elsewhere

modules in other languages may specify which functions are visible from the outside, etc.

very high level languages like Python may eliminate the need to define several functions because they would anyway be simple one liners

other languages like Prolog may require (or strongly suggest) the definition of a new predicate for every conditional jump.

in some cases it's common to define auxiliar functions inside the function that uses them (local functions), sometimes these are anonymous functions (code closures), this is common in Javascript callback functions.

So in short, splitting in several functions is usually a good idea in terms of readability. It may not be really good if the functions are very short and this creates the goto effect or if the names are not really descriptive, in that case reading some code would require jumping among functions, which may be messy. About your concern about scope and usage of these functions, there are several ways to deal with it that are in general language dependent.

In general the best advice is to use common sense. Any strict rule is very likely to be wrong in some case and in the end it depends on the person. I would consider this readable:

process_url = lambda url: dict(re.findall('([^?=&]*)=([^?=&]*)', url))

Personally I prefer a one liner even if it is slightly complex rather than jumping and searching across several files of code, if it takes me more than three seconds to find some other part of code I may not even know what was I checking anyway. People who do not suffer from ADHD may prefer more explanatory names that they can remember, but in the end what you are always doing is balancing the complexity in the different levels of the code, lines, paragraphs, functions, files, modules, etc.

So the keyword is balance. A function with one thousand lines is a hell for anyone reading it, because there is no encapsulation and the context becomes just too huge. A function split into one thousand functions each one of them with one line in it may be worse:

you have some names (that you could have provided as comments in the lines)

you are (hopefully) eliminating global variables and do not need to worry about the state (having referential transparency)

but you force readers to jump back and forth.

So there are no silver bullets here, but experience and balance. IMHO the best way to learn how to do this is reading a lot of code written by other people an analyzing why is it hard for you to read it and how to make it more readable. That would provide valuable experience.


问:
How should I implement code review in this situation?
My question is about how to put code review into practice in a workplace where nobody else has asked for it, I've never done it before, and I'm not entirely sure if it's worthwhile for this type of programming.

I'm a contractor on an assignment that mostly involves tools engineering, data analysis, fixing code when someone's Excel template changes break a macro, etc.  It's total cowboy coding: Requests are more "do what you need to do to hack together something that works ASAP, we need it in production tomorrow morning and we're only going to need it for a couple months" than "make a well-structured application that will be easy to maintain and develop under all foreseeable circumstances."

The software engineering team is me and one other guy whom I supervise.  We don't currently follow any kind of software development methodology beyond "make something that fulfills the functional requirements", and neither of us have ever worked anywhere that had any code review or design principles.  Everything we make is either VBA or C# desktop apps, and each of us is usually working on a separate assignment rather than collaboratively building the same program.  There is no version control system in place and we don't have server access to install any such system.

What I'm trying to figure out is, given that the work is very ad hoc, what kind of code review, if any, should I put in place?  Or is it even necessary for the kind of work we're doing?

答:
Well first thing is to get a SCM of some sort, even if its just git shared between yourselves without any form of central/golden server repo.

Then I'd say install Redmine and use that to track the change requests you get - because you can point redmine at your git repo and see the changes that were committed, but for this to work well you'll need a golden repo and a server to install redmine on! Of course, you can get away with using your own PCs for this task, but one of you will have to be the guy hosting this - and therefore be the guy who 'owns' the definitive repo. I assume this guy would be you as you're interested in it, and I'd really recommend this approach. If you're scared of using git, or don't quite trust yourselves to manage it well (as it can be confusing and complex at first) then install VisualSVN Server and get the other guy to commit to that instead - setting up SVN is easier both from tools PoV and conceptually. You can always change to git later if you realise the benefits and can force the required workflows on the other guy.

This will let you start with the basics of SCM tooling, and maybe in the future you can get a server and do something more organised and 'official'.

Oh yes.. code reviews... until you have more staff, do manual code reviews - look at the changelog in Redmine, double click it and it'll show you a pretty graphical diff of the changes for you to review. No need for a more formal tool that will send you emails, bug tickets or whatever with a link to the checkin diff in this case.


答: If you could design a class that is appropriate for these functions make them private.  Put another way, with a suitable class definition you can expose the only what you need to expose.</p>

Title: Is it OK to split long functions and methods into smaller ones even though they won't be called by anything else?

Body:
Lately I've been trying to split long methods into several short ones.

For example: I have a process_url() function which splits URLs into components and then assigns them to some objects via their methods. Instead of implementing all this in one function, I only prepare the URL for splitting in process_url(), and then pass it over to process_components() function, which then passes the components to assign_components() function.

At first, this seemed to improve readability, because instead of huge 'God' methods and functions I had smaller ones with more descriptive names.
However, looking through some code I've written that way, I've found that I now have no idea whether these smaller functions are called by any other functions or methods.

Continuing previous example: someone looking at the code might think that process_components() functionality is abstracted into a function because it's called by various methods and functions, when in fact it's only called by process_url().

This seems somewhat wrong. The alternative is to still write long methods and functions, but indicate their sections with comments.

Is the function-splitting technique I described wrong? What is the preferred way of managing large functions and methods?

UPDATE: My main concern is that abstracting code into a function might imply that it could be called by multiple other functions.

SEE ALSO: discussions on reddit at /r/programming (provides a different perspective rather than most of the answers here) and /r/readablecode.


问:
Hourly or per project billing?
How do you bill your programming projects? Do you do it per hour? Per job?

Please include what kind of project you are doing in the answer. (Mobile, Web, Desktop, etc... You can be more specific if you want.)

BONUS:

If you'd like to give specific amounts in your answer, you may. ;-)

答:
I used to bill hourly when I was consulting for an on-line start-up several years ago, and it struck me that it really was a big act of trust on both our parts.  The client trusted I wasn't going to charge him for looking up sports scores on ESPN, I trusted he wasn't going to accuse me of the same if the project I was working on took longer than anticipated.

Luckily for both of us, we were both worthy of that level of trust.  But as a general rule, I have to think that billing per project is safer for all parties involved.

ContentLicense: CC BY-SA 2.5

Title: Hourly or per project billing?


问:
What are the worst false economies in software development?
What are the worst false economies (that is ways of saving money that ultimately cost more than they save) prevalent in the software industry and how do you combat them?</p>

答:
Not my own anecdote, but I did once hear of a shop which stopped providing free coffee to its developers, telling them instead that any time they wanted to get coffee, they were free to walk to the nearest coffee shop (something like a ten minute trip each way) and purchase some.

Pretty much the definition of false economy.


问:
What is the best way to prove that in-code documentation is greater than extensive external documentation?
What is the best way to prove to my boss that in code documentation is greater than extensive external documents containing documentation and screenshots of code/ui?

We have a group in the company running SAP code.  Their documentation process involves hours of laborious documentation and screenshots of the code and the interface (before and after).

They want us (C# developers) to follow the same rubric as they do.  I want to argue that using comments in the code, and a great, self documenting language such as C# is fulfilling the need for documentation the same as, or greater than the other team's document method.

Is there any published research by big companies that say external documentation is out dated and that in code comments are more efficient? (or something similar to this point)

This has nothing to do with users.  This is NOT user training documentation. Only internal use.

This has nothing to do with Design Documents or Architectural Documents.  It's comparing screenshots of code, before and after a change, and screenshots of forms, before and after the change, and putting them into a document with extensive documentation, opposed to simply having great incode documentation.

Would you really want to have to screenshot your code before and after every single baby change and then write a document explaining the change in great depth? when no one will ever use these documents as reference material in the future?

答:
What is the best way to prove to my boss that in code documentation is greater than extensive external documents containing documentation and screenshots of code/ui?

It could be, but it is not a rule. What will the documentation be used for? (Who accesses it? How often? What feedback/decisions come out of that activity?)

Their documentation process involves hours of laborious documentation and screenshots of the code and the interface (before and after).

Would you really want to have to screenshot your code before and after every single baby change and then write a document explaining the change in great depth?

Seems like they're doing it wrong'* - they don't need your documentation - they need a note somewhere, saying:

```<code>git/hg/svn/xyz diff -rXXXX -rYYYY # show code differences
git/hg/svn/xyz info XXXX          # show change description and details
</code>```

or something similar. This can easily be automated by any good SCM, or with whatever your deliverables are called ("feature releases", "change requests", "iteration ending reports", "public commits", "solved defects", etc).

when no one will ever use these documents as reference material in the future?

If indeed no one will ever use them, then it's easy to prove: no one will ever use them. Can you speak to them to find out if this is indeed the case?

'* - I am not sure if they're actually doing it wrong. It depends on what this documentation is used for.

Body:
What is the best way to prove to my boss that in code documentation is greater than extensive external documents containing documentation and screenshots of code/ui?

It could be, but it is not a rule. What will the documentation be used for? (Who accesses it? How often? What feedback/decisions come out of that activity?)

Their documentation process involves hours of laborious documentation and screenshots of the code and the interface (before and after).

Would you really want to have to screenshot your code before and after every single baby change and then write a document explaining the change in great depth?

Seems like they're doing it wrong'* - they don't need your documentation - they need a note somewhere, saying:

git/hg/svn/xyz diff -rXXXX -rYYYY # show code differences
git/hg/svn/xyz info XXXX          # show change description and details

or something similar. This can easily be automated by any good SCM, or with whatever your deliverables are called ("feature releases", "change requests", "iteration ending reports", "public commits", "solved defects", etc).

when no one will ever use these documents as reference material in the future?

If indeed no one will ever use them, then it's easy to prove: no one will ever use them. Can you speak to them to find out if this is indeed the case?

'* - I am not sure if they're actually doing it wrong. It depends on what this documentation is used for.


问:
Custom functions in a REST API
Looking at two of our entities Company and Address. A company has a billingAddress and a profileAddress.

I'm unsure of how to implement a function to set the billing address versus the profile. Here are the options I can see:

Create a new address using a POST to /address. Update the company object at /company with profileAddress = {/* the new id of the address */}

Execute /company/:id?function=updateBillingAddress&{/* rest of parameters go here */}

Execute /updateBillingAddress?company={companyId}&{/* rest of parameters go here */}

Execute /company/:id?billingAddress={ /* address data here */ }

The first method requires two calls and more responsibility on the part of the developer hooking up to the API. However, I'm not sure the second two methods are appropriate structure.

The last one seems like it might be okay, it gives flexibility for updates without holding the responsibility of managing pointers or executing two calls.. still unsure.

Has anyone seen use of methods 2 or 3 before. Are they okay to use? Why / why not? Which would you suggest to use and why?

答:
Depends...

How I would do it:

```<code>PUT /company
</code>```

The paramters of the company are in the body of the request in any format you wish to support. Should return a 201 Created with the URL of the new company in the Location header.

```<code>PUT /address
</code>```

Same as PUT /company. Same functionality.

Billing address is a sub resource of /company/[company-id] so:

```<code>PUT /company/[company-id]/billingAddress
</code>```

The parameters of the new billing address could be just the URL of the address you created initially.

Title: Custom functions in a REST API

Body:
Depends...

How I would do it:

PUT /company

The paramters of the company are in the body of the request in any format you wish to support. Should return a 201 Created with the URL of the new company in the Location header.

PUT /address

Same as PUT /company. Same functionality.

Billing address is a sub resource of /company/[company-id] so:

PUT /company/[company-id]/billingAddress

The parameters of the new billing address could be just the URL of the address you created initially.


答:
Requests are more "do what you need to do to hack together something that works ASAP, we need it in production tomorrow morning and we're only going to need it for a couple months

Based on this, the focus of your code reviews is probably not maintainable, stable code. However, you may still profit from code reviews as a means to further develop your and your colleague's programming abilities and to develop a common understanding of the problem. As @Mike suggests, pair programming on specific problems might turn out to be a very effective way of employing some sort of code review in your scenario. Pair programming will lead you to discuss the approaches to solve a problem and therefore may help you to "hack together something" with less bugs even faster, which is something that directly translates to business value.

Title: How should I implement code review in this situation?

Body:
My question is about how to put code review into practice in a workplace where nobody else has asked for it, I've never done it before, and I'm not entirely sure if it's worthwhile for this type of programming.

I'm a contractor on an assignment that mostly involves tools engineering, data analysis, fixing code when someone's Excel template changes break a macro, etc.  It's total cowboy coding: Requests are more "do what you need to do to hack together something that works ASAP, we need it in production tomorrow morning and we're only going to need it for a couple months" than "make a well-structured application that will be easy to maintain and develop under all foreseeable circumstances."

The software engineering team is me and one other guy whom I supervise.  We don't currently follow any kind of software development methodology beyond "make something that fulfills the functional requirements", and neither of us have ever worked anywhere that had any code review or design principles.  Everything we make is either VBA or C# desktop apps, and each of us is usually working on a separate assignment rather than collaboratively building the same program.  There is no version control system in place and we don't have server access to install any such system.

What I'm trying to figure out is, given that the work is very ad hoc, what kind of code review, if any, should I put in place?  Or is it even necessary for the kind of work we're doing?


问:
What is the preferred method for an application to get settings which should not be stored in version control?
Let's say an application I'm writing requires a password for something but I don't want that password to be saved in version control (so no hard-coding the password). What I've been doing is creating a file called PASSWORD which is read in once by the application and ignored by version control. Is there a more preferential method to handle this situation?

答:
For Windows applications, there is the registry or various config files,e.g. app.config or web.config, that could be used to store this kind of data. AppSettings is the collection used within Windows code to access the config file in .Net for example.

I'd suspect there are similar files and locations on systems using other operating systems for where this information would be stored.

While you may disagree about storing a web.config in version control, I have had more than a few times where a developer got upset that I committed the "web.config" and thus at times it is worth considering what is the code and what is configuration that administrators can handle.  If you have a better solution, why aren't you posting it?


答:
Are you doing your own QA as well?  Your situation sounds a lot like the last 3 I've been in, and I suspect it's a lot more common than all the documentation on best practices (code reviews, documentation, SCM etc) would seem to imply.

My input is that at least you have the other guy!  Better than it being all on you.  I'd suggest each of you doing the QA on the other guys code and giving it a quick read to make sure each of you can understand what the other guy has written. This will get you better code because the other guy doing the QA may not make the same assumptions as the author and might catch more bugs than the author would, and since you each may end up working on the other guy's stuff, you want to ensure at least a minimal level of readability / maintainability.  I've inherited stuff that was obtuse and barely documented and the only way I could figure it out was to painfully step through the debugger. Readable / maintainable code is not a luxury, it's an investment.

I agree with the other guys too - pair programming might be a good fit, and definitely get at least an SCM.


答:
In my mind, you have two different ways to handle this:

1) One resource to rule them all:

To create a new company:

```<code> `POST /company`
</code>```

POST body has full details of the company, including both profile address and billing address. As noted by v0idnull, return value should be a 201 Created with a Location header with the URL of the newly created resource.

To set the billing address:

Fetch the current company representation:

```<code>GET /company/123
</code>```

Update the representation with the new billing address, and do:

```<code>PUT /company/123
</code>```

With the full new representation of the company.

PROS

Reduce the number of requests for some workflows.

Caching is "easier" as you need to only worry about the caching of the one resource.

Easier to understand for more API customers.

CONS

If you have frequent updates to the company resource for different reasons, you can hit issues with concurrent updates

No ability to have fine grained cache control for the different aspects of the company.

2) Separate sub-resources for billing address and profile address

To create a new company:

```<code>POST /company
</code>```

Response looks something like:

```<code>201 Created
Location: /company/123
Link: </company/123/billing_address>;rel=billing_address
Link: </company/123/profile_address>;rel=profile_address
</code>```

Clients can then follow the billing_address or profile_address link relations to update those attributes respectively.

PROS

Allows fine grained updates to different aspects of the company with potentially less concurrent update failures.

Fine grained caching of each resource.

By using hypermedia/links, can restructure URLs/application later.

CONS

Requires multiple requests for many workflows (Mobile clients?)

Harder to grok for some API consumers not familiar with hypermedia APIs.

Title: Custom functions in a REST API

Body:
Looking at two of our entities Company and Address. A company has a billingAddress and a profileAddress.

I'm unsure of how to implement a function to set the billing address versus the profile. Here are the options I can see:

Create a new address using a POST to /address. Update the company object at /company with profileAddress = {/* the new id of the address */}

Execute /company/:id?function=updateBillingAddress&{/* rest of parameters go here */}

Execute /updateBillingAddress?company={companyId}&{/* rest of parameters go here */}

Execute /company/:id?billingAddress={ /* address data here */ }

The first method requires two calls and more responsibility on the part of the developer hooking up to the API. However, I'm not sure the second two methods are appropriate structure.

The last one seems like it might be okay, it gives flexibility for updates without holding the responsibility of managing pointers or executing two calls.. still unsure.

Has anyone seen use of methods 2 or 3 before. Are they okay to use? Why / why not? Which would you suggest to use and why?

Body:
In my mind, you have two different ways to handle this:

1) One resource to rule them all:

To create a new company:

 `POST /company`

POST body has full details of the company, including both profile address and billing address. As noted by v0idnull, return value should be a 201 Created with a Location header with the URL of the newly created resource.

To set the billing address:

Fetch the current company representation:

GET /company/123

Update the representation with the new billing address, and do:

PUT /company/123

With the full new representation of the company.

PROS

Reduce the number of requests for some workflows.

Caching is "easier" as you need to only worry about the caching of the one resource.

Easier to understand for more API customers.

CONS

If you have frequent updates to the company resource for different reasons, you can hit issues with concurrent updates

No ability to have fine grained cache control for the different aspects of the company.

2) Separate sub-resources for billing address and profile address

To create a new company:

POST /company

Response looks something like:

201 Created
Location: /company/123
Link: </company/123/billing_address>;rel=billing_address
Link: </company/123/profile_address>;rel=profile_address

Clients can then follow the billing_address or profile_address link relations to update those attributes respectively.

PROS

Allows fine grained updates to different aspects of the company with potentially less concurrent update failures.

Fine grained caching of each resource.

By using hypermedia/links, can restructure URLs/application later.

CONS

Requires multiple requests for many workflows (Mobile clients?)

Harder to grok for some API consumers not familiar with hypermedia APIs.


问:
How does Facebook strip html/apostrophes for XSS but also display it?
I'm not quite sure if this is a question for programmers.se rather than stackoverflow, but here goes.  So Facebook [or any other large company] when given something like an apostrophe or html, can strip it of its malicious intent, but still display it properly.  My current sanitizing function in PHP just strips those characters/makes them harmless via htmlentities() and such.  So if I wrote an HTML tag, I would want it to be sanitized but also displayed on the website.  How do I do this?</p>

答:
In general anything entered by a user (or untrusted machine or software using an API) needs to be escaped before embedding it within code (HTML, JavaScript, etc.) that is interpreted. Escaping is I think what you mean by "making it harmless". Most libraries have APIs (like htmlentities()) to facilitate this.

If you don't escape it, storing it is basically the only safe thing you can do. Analysis can be OK, as long as the analyzer cannot be commandeered by its input (i.e. it is robust and defensive and has no exploit).

Modifying input (e.g. stripping dangerous characters) can also be effective, but it is hard to do it in such a way that legitimate characters are suppressed (false positives). For example, if someone's name is John O'Malley-O'Hara, you don't want the system to remove the apostrophes (or the text between them), even though they look like single-quote delimiters common in code. In other words, it is so hard to make sure that input modification is done right that is it perhaps better to not do it at all.

I think the best approach is to treat all input carefully and escape it when displaying it. Some languages and frameworks can assist you with this (see "taint mode").


问:
What is detailed design? what are the advantage disadvantages using it?
Im really not getting  the idea:

What is Detailed Design.

Why use Detailed Design.

Advantages/Disadvantage of using Detailed Design.

Any alternative methods other than using Detailed Design.

Could some one please guide/explain me ?

答:
1) When most people talk about detailed design, they are referring to a process known as top-down design.  In short, when you think about the problem you are trying to solve, you start at the highest level and then work yourself into the details.  This approach works very well when you have an overall structure you want your application to live within.  At the macro level you are considering how many machines will be needed to host your application, which existing services you will need to use, etc.  As you dive deeper, you are looking at use cases (or user stories if you prefer that terminology), and error handling (use cases have both normal and error condition paths to worry about).  As you go even further into the details, you are looking at your algorithm, state transitions, logical sequence, and how internal parts of the code work together.

2) The classic top-down approach to detailed design is what is taught with the "waterfall" methodology, IEEE process guides, UML vendors, universities, and CMMI among others.  In many of these heavy processes they have you writing two design documents.  One is the overall architectural diagram (the top level design).  The other is the detailed design where you go further down the rabit hole.  In many cases it is the only approach to design many people know.  It is a very logical and methodical approach to breaking down a software problem.

3) The main advantage is that you have identified what the critical sections are likely going to be.  If you will need to start working on how your software will be using another existing service, you have compiled your list of integration points.  You would be able to start talks with the owners of those services to plan your integration along with how to handle unexpected events.

The main disadvantage is that many times people go too far down the rabit hole, and the design document takes a life of its own.  While it is advantageous to have an overall vision and architecture for how an application will work, you will invariably find your initial thoughts on the core details were flat wrong.  When that happens, either the design document is neglected or you have whole teams maintaining the paper and slowing progress on work.

4) I've already mentioned top-down design, so it follows there must be a "bottom-up" approach, right?  As it turns out, there is.  Essentially, the "bottom-up" approach is the core thought process behind Test Driven Development and Continuous Design methodologies.  Essentially, the details of working code start driving the design of how larger chunks of working code cooperate and interface with each other.  With TDD, you have unit tests to ensure that the details behave properly and keep validating your design.  Continous design teaches us that we will never truly know the details until the software is done.  Therefore, why try to fight the fact?  Instead of a big up-front design stage, the design is built in increments over several iterations of design/code and testing.  It is actually a very liberating concept that lets you concentrate on solving problems.

Bottom line, there is no perfect answer.  For me, I find a healthy balance between top-down and bottom-up design works well.  Essentially, I still take the time to think about the big picture.  I even map out a plan for the user interface idioms and my best ideas for it's design.  However, I don't go into great detail because I know the details will change.  Basically, you need to stop the top-down process when you are getting to areas you are not sure about.  Once you get to those areas, start with the bottom-up approach.  This lets you try different things, verify with the customer if it makes sense to them, and continue to improve over time.


问:
Preferrable Method to record Documentation
As any taught Software Engineer knows how important Documentation for good software projects is. Could you show me best practices for assure good documentation beside of JavaDoc comments?

In my opinion the documentation should not only contain javadoc comments to assure good human readable text for future and present programmers.

My thought would be to assure maybe some paper or wiki. Is there maybe any Software that helps recording documentation beside the standart solutions like JavaDoc, etc.

答:
JavaDoc documentation may be more or less detailed. For example, the inline documentation (in .NET, similar to JavaDoc) is pretty verbose on one of the projects I'm working on, containing not only the description of a method, but also the list of possible exceptions, the examples showing how to use a method (with demo source code in comments), etc.

Having even verbose inline documentation is a good thing, but don't forget that:

Many things cannot be described in source code (and documentation in source code files). What about:

Security concerns?

Instructions about how to deploy the project?

Details about the environment?

Style guidelines?

etc.

Good inline documentation is a good thing, but this is not an excuse to avoid writing good, readable code. Especially, think about ways the code can be improved in order to avoid explicit documentation. For example, .NET has code contracts which increase the clearness of the code while ensuring that the contracts will never (or rarely) be outdated.


问:
How to reject a code review that you believe is unnecessary?
I am in a position where I have been asked to review some code that fixes a problem that I don't believe exists.

The fixer, who is more senior than me, insists his fix is necessary but it appears to be no more than C++ sophistry to me.  Part of our deployment process is a code review, and as the 2nd highest engineer in a small company I am expected to review changes.

I believe that reviewers are just as responsible for code changes as the original coder, and I am unwilling to accept responsibility for this change. How would you go about rejecting this review?

答:
Write down your reasons for rejection and defenses for likely counter arguments.  Then discuss rationally with the fixer and if necessary escalate to management.

If you have sufficient documentation (including code listings, test results, and objective arguments), you'll be well covered.

You will cause some ill will with the fixer, so be sure the issue is worth it (i.e., does the non-fix cause harm?)

Also, if the fixer is in any way related to the owners, forget this answer.


答:
This sounds more like a problem with your team policy than with this specific review.  When I worked at a large software shop on a team of 9, a reviewer flat-out had veto power over code, and this was a standard we all respected.  We were a talented and savvy enough - viz. "mature", but more in the sense of "not childish" than "seasoned" - that our team lead could reasonably expect us to always be able to come to an agreement without devolving into arguments in a prudent time period.

Simply based on your language in your post, I might warn you that it sounds like you're going to approach this situation in a way that might lead to a devolved argument.  Perhaps it is "intellectual masturbation," but there is probably a reason he or she did it, and the burden on you will be to come up with a simpler way to solve that problem - and if no such way exists, document in comment why the masturbatory code was, in fact, necessary.

Title: How to reject a code review that you believe is unnecessary?

Body:
I am in a position where I have been asked to review some code that fixes a problem that I don't believe exists.

The fixer, who is more senior than me, insists his fix is necessary but it appears to be no more than C++ sophistry to me.  Part of our deployment process is a code review, and as the 2nd highest engineer in a small company I am expected to review changes.

I believe that reviewers are just as responsible for code changes as the original coder, and I am unwilling to accept responsibility for this change. How would you go about rejecting this review?


答:
Ask for a test case that fails without the change that succeeds with the change.

If he can't produce one, you use that as justification.

If he can produce one then you need to explain why the test is invalid.


答:
There is a lot of information that could be considered "documentation". Here's my summary, with some best practices for each:

Class, method, function, and variable names. This is critical to having readable code. All other documentation can easily get out of date, but the text that the compiler actually compiles almost by definition cannot. It is the ultimate reference to what the software does, and good naming should be a priority here.

In-line comments. Within functions and methods, having good comments to separate functional sections and explain tricky algorithms are valuable. Make sure they don't go out of date.

JavaDoc-style comments. These are great for generating web pages for easy perusal of a stable codebase, but can be of limited value with code in active development. They are best created and elaborated after code stabilizes, especially for code that is used systemwide. They are less valuable for code used in only one place.

Developer documentation. This includes guides for getting started developing the software (packages to install, build procedures, debugging tips, coding styles, etc.). This is valuable when you first start a project (or return to it after an absence), but is seldom used at other times. In a pinch, this information can be obtained from other team members.

User/Administrator/Operator documentation. This includes information about how to install, administer, and use the software. Customers value this when they are having trouble, so it should be good. Ideally, the software should be self-explaining, but sometimes that is not possible or appropriate. This should be written by someone with good writing skills.

All these kinds of documentation contribute to the value of the software, but of the five groups, I would say that 1 and 5 are the most important, and 3 is the least important. Unfortunately, except for 3, I know of no software (beyond text editors) to facilitate generating the documentation in question. There are lots of good books about documentation and writing high-quality code in general. One of my favorites is Code Complete.

Title: Preferrable Method to record Documentation

Body:
As any taught Software Engineer knows how important Documentation for good software projects is. Could you show me best practices for assure good documentation beside of JavaDoc comments?

In my opinion the documentation should not only contain javadoc comments to assure good human readable text for future and present programmers.

My thought would be to assure maybe some paper or wiki. Is there maybe any Software that helps recording documentation beside the standart solutions like JavaDoc, etc.


问:
Use of pirated/cracked software for development
Disclaimer: I by no means condone the use of pirated software.

Have you ever witnessed the use of pirated software for development purposes? May be a company didn't have enough money to buy a piece of software and there were no free alternatives? May be a company wanted to try something out before buying and there were no trial licenses for that product. Whatever the circumstances, have you worked at a company where using pirated/cracked software was accepted? Were there any consequences to doing this?

答: One of the major benefits of doing Java development is that you can get very high quality tools for free.  You can then get very high quality POWER tools for money if you need them.</p>


答:
This is a perennial problem. At some point, when software needs to access something protected by a password, the software needs that password. And for the software to get that password, and not require a user to enter it manually, it has to be stored in persistent storage of some sort. I see several options:

Use a hand-created (or copied) password file, ignored by the version control system, and perhaps with limited readability (just the owner (0400 on Unix), for example). I do this myself sometimes these days.

Encrypt the password file somehow. Technically, this doesn't actually solve the problem, as the decryption key needs to be stored somewhere, too, but it means that the password is no longer stored in cleartext. The decryption key could be baked into the software that reads the encrypted password file, and an encryption key baked into a small utility that generates encrypted password files. This might be pretty good. I did this in earlier days when I was more paranoid.

Use a pre-shared key mechanism similar to what people do to ssh to remote machines without needing a password. This might be harder to set up, but can be elegant.

Title: What is the preferred method for an application to get settings which should not be stored in version control?

Body: Let's say an application I'm writing requires a password for something but I don't want that password to be saved in version control (so no hard-coding the password). What I've been doing is creating a file called PASSWORD which is read in once by the application and ignored by version control. Is there a more preferential method to handle this situation?


问:
Should I Do Calculations in T-SQL or Program?
I am creating a stored procedure that is logging some data. The data ultimately needs to end up in 2 tables. The incoming data is coming from a JSON string containing 15 parameters, and the data is then logged to the database using the stored procedure I'm writing. I would like to send the data into 1 stored procedure and INSERT it into both tables.

The first table is a raw data logging table. It will be used for debug and troubleshooting.

The second table will be used for report generation. This table requires some simple mathematical calculations to be done on incoming data. For example:

DECLARE @Table2Fld3 DECIMAL = @IncomingFld9 - @IncomingFld4;

I'll have about 8 of these calculations to do to compute the values for table 2, then I'll do an INSERT to save the data.

So my question is, is it a good practice to do these calculations in the T-SQL? Or would it be better for me to create 2 separate stored procedures and do the calculations in my code?

One trade-off I see is that if I do it all in the code then I have to create 2 database connections.

EDIT

I should elaborate on the "2 database connections" comment. The application in question is a windows service that establishes multi-threaded server/client communication. The logging system is asynchronous to the server/client communication. Using that existing system, in order for me to target multiple stored procedures, it would require 2 calls to the logger which would spin up 2 connections to the database.

答: It seems to me that these simple calculations should be done as part of the report and don't need to be stored in a reporting table.  This gives the flexibility of letting the calculations change and not having to re-created the data in the reporting table.</p>


答:
Make the submitter show proof that his code fixes his problem. If he can test, and show you proof, then you are the one who is wrong and should just quit your complaining and deal with it. If he cannot show proof to support his claim there is a problem, and show proof that his patch fixes the problem, then I'd send him back to the drawling board.

Of course there could be sensitive internal political-ness around this. But this is the way i'd go (delectably).


答:
In today's world, it doesn't matter much, if it at all.

Dynamic branch prediction (something thought about for decades (see An Analysis of Dynamic Branch Prediction Schemeson System Workloads published in 1996)) are fairly common place.

An example of this can be found in the ARM processor.  From the Arm Info Center on Branch Prediction

To improve the branch prediction accuracy, a combination of static and dynamic techniques is employed.

The question then is "what is dynamic branch prediction in the arm processor?"  Contiuned reading of Dynamic branch prediction shows that it uses a 2 bit prediction scheme (described in the paper) builds information about if the branch is strongly or weakly taken or not taken.

Over time (and by time I mean a few passes through that block) this builds up information as to which way the code will go.

For static prediction, it looks at the way the code looks itself and which way the branch is made on the test - to a previous instruction or one further in the code:

The scheme used in the ARM1136JF-S processor predicts that all forward conditional branches are not taken and all backward branches are taken. Around 65% of all branches are preceded by enough non-branch cycles to be completely predicted.

As mentioned by Sparky, this is based on the understanding that loops more often than not, loop.  The loop branches backwards (it has a branch at the end of the loop to restart it at the top) - it normally does this.

The danger of trying to second guess the compiler is that you don't know how that code is actually going to be compiled (and optimized). And for the most part, it doesn't matter.  With dynamic prediction, twice through the function it will predict a skip over the guard statement for a premature return.  If the performance of two flushed pipelines is of critical performance, there are other things to worry about.

The time it takes to read one style over the other is likely of greater importance - making code clean so that a human can read it, because the compiler is going to do just fine no matter how messy or idealized you write the code.

Title: Which code is better for branch prediction optimization?

Body:
Given branch prediction, and also the effect of compiler optimizations, which code tends to offer superior performance?

Note that bRareExceptionPresent represents an uncommon condition. It is not the normal path of logic.

```<code>/* MOST COMMON path must branch around IF clause */

bool SomeFunction(bool bRareExceptionPresent)
{
  // abort before function
  if(bRareExceptionPresent)
  {
     return false;
  }
  .. function primary body ..
  return true;
}

/* MOST COMMON path does NOT branch */

bool SomeFunction(bool bRareExceptionPresent)
{
  if(!bRareExceptionPresent)
  {
    .. function primary body ..
  }
  else
  {
    return false;
  }
  return true;
}
</code>```


答:
Why?

The best documentation is clearly-written code with an obvious purpose and process. Comments to explain what is being done are then superflous. Comments to explain why the code exists are useful, if not obvious from context.

The underlying question is: what is the purpose of the documentation you have in mind?

Documentation for its own sake may be a waste of effort.


答:
Reviewers should be objective.

It's clear that you've formed an opinion about the code in question before you've even reviewed it, and it sounds like you and the fixer have staked out positions. If that's so, then you're going to have a difficult time appearing objective, and an even more difficult time being objective. None of that helps the process, and it may be that the best, most objective thing you can do is to bow out on the grounds that you're too close to the issue.

Consider a team approach.

If it's not possible to remove yourself, perhaps you can have several other engineers review the code at the same time. Either they'll agree with you that the code should be rejected or they won't. If they agree with you, then it will no longer be just you vs. the fixer, and you'll be able to make a stronger case that the team looked at the fix objectively and decided against accepting it. On the other hand, if they decide to accept the fix then that too will be a team decision. It should go without saying that you should participate with as open a mind as you can manage, and that you shouldn't try to influence the other team members' opinions by anything other than rational discussion. Important: if there's a bad outcome later, don't throw the team under the bus by saying "Well I always said it was bad code, but I was outnumbered by the other team members."

Rejections are a natural part of the code review process.

The code review process isn't there to rubber stamp fixes from more senior people; it's there to protect and improve the quality of the code. There's nothing wrong with rejecting a fix provided you do it for the right reason, i.e. that the fix doesn't improve the code. If, after an open-minded review of the code, you still feel that the fix doesn't reduce the risk and/or magnitude of a demonstrable problem, then you should reject it. It's not personal, just your honest opinion. If the fixer disagrees, that's okay too, and at that point it becomes a problem for management to figure out. Just be sure to remain honest, open, and professional.

Responsibility cuts both ways.

You said that you don't want to be responsible for this change, apparently because you don't believe that there's a problem. However, you need to realize that if you're wrong and there is a problem, then you may end up being responsible for rejecting the code that would have avoided the problem.

Take notes.

Keeping a written log of the review process will help you keep your facts straight. Write down your thoughts and concerns while reviewing, description and results of any tests that you might run to measure the alleged problem and the fix, etc. If the issue escalates, you'll have a record of what you've done to support your position. If the matter comes up again in the future (it probably will if the fixer is attached to his own view), you'll have something to jog your memory.


问:
Is the algorithm more important than the programming language?
During the current (2013) Google Code Jam contest, there was a problem that took C++ and Java people 200+ lines of code as compared to Python people that solved the same problem only using 40 lines of code.

Python is not directly comparable with C++ and Java but the difference in verbosity I thought might perhaps have an influence on the efficiency of the algorithm.

How important is knowing the right algorithm compared to the choice of language? Could an excellently implemented Python program be implemented in C++ or Java in a better way (using the same algorithm) and does this have any relation to the natural verbosity of certain programming languages?

答:
Obviously, if you consider this question in the context of something like Google Code Jam, then algorithmic thinking is clearly more important when having to solve algorithmic problems.

In everyday life, however, about a million other factors have to be considered as well, which makes the question much less black vs white.

Just a counter-example: If you need 200 more lines in Java, but everyone in your company knows Java, this isn't a big deal. If you could write it in 5 lines of Python or any other language, but you would be the only one in the company to know that language - it is a big deal. Such big a deal in fact, that you will not even be allowed to do so and instead have to write it in Java.

From a craftman's perspective, we always try to approach with the right tool for the job, but the word right in there is so tricky that one can easily get it wrong.

On the contrary, I found algorithmic thinking in companies to be almost absent. Only few select people possess it, whereas the average joe often already has troubles estimating runtime complexities of loops, searches, etc.

In terms of algorithmic competitions, however, my personal experience from competing in them for several years, clearly tells me that you should stick to one language. Speed is a major factor and you simply cannot afford to waste time on your tools, when you should dedicate it to solving the problems within the time limit. Also consider that writing 200 lines of Java code without thinking is still much faster than hand-crafting 50 lines of complicated python code requiring a lot of thinking, yet both solving more or less the same problem.

Oh and finally, make sure you understand the major differences between algorithmic competition code and company production code. I have seen fantastic algorithmic coders, that wrote horrible code I would not ever accept in a product.


问:
Is it a bad idea to sync file system with remote server using HTTP?
I have started a project which will duplicate Dropbox or Google Drive behavior but using Amazon S3 az a backend.

Idea is very simple, a Node.js server that watchs a directory for file changes and PUT them on the S3. Or it will look at S3 for changes and applies them to file system structure. I'be uploaded very early version of my app to Github. You can find it here.

Because I am a web developer, I am using web technologies to solve the problem. I'm afraid of my limited mindset and picking wrong tools for the job. There are other solutions to this problem. One is S3FS which is a FUSE file system for Unix systems. In my opinion that is very hard to use and limited to platform. My solution uses Node.js to overcome cross-platform issues. I can pack my Node.js app with App.js and make it an easy to use software.

To clarify, my questions are:

Is HTTP/HTTPS good enough for file transfer?

Is Node.js good enough for working with File System?

Scalability: can this approach fail in large file sizes?

答:
Is HTTP/HTTPS good enough for file transfer?

Many applications rely on HTTP/HTTPS for file transfers, best example is mega.com. So as you mentioned there may be better ways to keep it in sync, but it's not definitely wrong to use HTTP/HTTPS for file transfers.

Is Node.js good enough for working with File System?

Node.js is a really great system and of course you can solve that problem, but again is it really the best way to solve it?`A dedicated sync application like S3FS definitely prevents you from doing some big mistakes.

Scalability: can this approach fail in large file sizes?

I don't know how you're doing the file exchange, but think of two most common problems: Too less memory (if you load all the file into the memory) and timeouts, if the download takes too long or the connection is interrupted.


答:
The more concrete responsability a method has, more easy to test, read and maintain will be the code. Although no other calls them.

If in the future, you need to use this functionality from other places, you can then easy extract those methods.


问:
Spring - Confusion over configuration?
Somewhere I read Spring offers convenience over configuration. But Spring folks are bringing in so much changes over the configuration , that I am now really getting confused to use the xml configuration or the annotation.

I would like anyone to suggest a surefire methodology or rule of thumb in using xml and annotations.

Examples at SO to show that many beginners like me are getting confused over the configuration.

link-1

I don't seem to grasp the functionality behind <context:annotation-config> and <context:component-scan>.

From what I've read they seem to handle different annotations (@Required, @Autowired etc vs @Component, @Repository, @Service etc) but also from what I've read they register the same bean post processor classes.

To confuse me even more, there is an annotation-config attribute on <context:component-scan>...

link 2

I still have  the component scan tag:

```<code><context:component-scan base-package="com.mycompany.maventestwebapp" />
</code>```

but I have also another tag (that look like have similar task), this one:

```<code><annotation-driven />
</code>```

What is the difference between these two tags?
  An other "strange" thing is that the previous example (that don't use the annotation-driven tag) is very similar to the project create by STS using the Spring MVC Template project but if I delete the annotation-driven tag from its configuration file the project don't run and give me the following error: HTTP Status 404 -...

Spring 3.2 no longer need cglib for proxying , but lower versions uses cglib. A quote from the springsource blog

In order to generate such proxies, Spring uses a third party library
  called cglib. Unfortunately, this project is not active anymore. In
  Spring 3.2, it is very likely that Spring will be using Javassist
  instead by default.

Are these enough to suggest that Spring is Confusion over configuration ?

答:
Spring offers options, originally there was only the xml based wiring. Later annotation based wiring was added.

It is now possible (and many people do so) to use a mix of both.

There is ample documentation included with Spring and/or downloadable from the springsource website. There's professional training (never done it, can't vouch for it), and quite a few good books (I like APress' Pro Spring, pick the right release for the version of Spring you're employing).

Title: Spring - Confusion over configuration?


问:
Repetitive Drawing in Javascript & Canvas
Creating an HTML5 page using canvas and javascript to draw a set number of musical staves on the page, spaced a pre-determined amount in between.

What I have is re-drawn on top of the canvas 10 times, and what I really need is something that's spaced out apart every time the loop is drawn.

I tried to create  a JSFiddle, but it doesn't draw anything (which I'm sure is user-error), so here's the js file:

```<code>window.onload = function(){

var canvas = document.getElementById('sheetmusic');
    c = canvas.getContext('2d');

c.fillStyle = 'white';
c.fillRect(0,0, canvas.width, canvas.height);

//  Draw staves
for (var i=0; i<10; i++){
    c.strokeStyle = 'black';
    c.beginPath();
    c.moveTo(0,10);
    c.lineTo(canvas.width,10);
    c.stroke();
    c.moveTo(0,20);
    c.lineTo(canvas.width,20);
    c.stroke();
    c.moveTo(0,30);
    c.lineTo(canvas.width,30);
    c.stroke();
    c.moveTo(0,40);
    c.lineTo(canvas.width,40);
    c.stroke();
    c.moveTo(0,50);
    c.lineTo(canvas.width,50);
    c.stroke();
    // staff whitespace
    c.fillStyle = 'white';
    c.fillRect(0,52, canvas.width, 50);
    }
};
</code>```

I'm just not certain how to append i from my loop into the height attribute of my stroke.

答:
You need to change the x, might help to visualize on a piece of paper or paint with grids what your doing.

This will make lines from top to the bottom

```<code><!DOCTYPE HTML>
        <html>
        <head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <span id=dbg
    ></span>
    <br>
        <canvas id=sheetmusic  width="800" height="625"></canvas>
    <br>
    <div id=dbgD></div>

        <script language="Javascript">

    dbr =  document.getElementById('dbgD');
    function dbg(s){
    dbr.innerHTML = dbr.innerHTML + "<br>" + s
    }
    window.onload = function(){

    var canvas = document.getElementById('sheetmusic');

    c = canvas.getContext('2d');
    dbg(" canvas " + canvas + "; 2d " + c);
    //c.fillStyle = 'white';
    //c.fillRect(0,0, canvas.width, canvas.height);
    canvas.width = canvas.width //clears

    c.fillStyle = 'green';

    heightDiff = 15;
    numberLines = canvas.height / heightDiff
    //  Draw staves
    for (var i=0; i< numberLines; i++){
        c.strokeStyle = 'black';
        c.beginPath();
        c.moveTo(0,10 + (i * heightDiff));
        c.lineTo(canvas.width, 10 + (i * heightDiff));
        c.stroke();

        /*

        c.moveTo(0,20);
        c.lineTo(canvas.width,20);
        c.stroke();
        c.moveTo(0,30);
        c.lineTo(canvas.width,30);
        c.stroke();
        c.moveTo(0,40);
        c.lineTo(canvas.width,40);
        c.stroke();
        c.moveTo(0,50);
        c.lineTo(canvas.width,50);
        c.stroke();
        */

        // staff whitespace, not sure what you want to do here
        c.fillStyle = 'white';
        //c.fillRect(0,52, canvas.width, 50);
        }
    };

    </script>
</code>```

Maybe a few tutorials on loops and using their vars will help ? http://www.echoecho.com/javascript9.htm not sure exactly what you want to achieve except make some lines that look like music notes?

Body:
You need to change the x, might help to visualize on a piece of paper or paint with grids what your doing.

This will make lines from top to the bottom

<!DOCTYPE HTML>
        <html>
        <head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <span id=dbg
    ></span>
    <br>
        <canvas id=sheetmusic  width="800" height="625"></canvas>
    <br>
    <div id=dbgD></div>

        <script language="Javascript">

    dbr =  document.getElementById('dbgD');
    function dbg(s){
    dbr.innerHTML = dbr.innerHTML + "<br>" + s
    }
    window.onload = function(){

    var canvas = document.getElementById('sheetmusic');

    c = canvas.getContext('2d');
    dbg(" canvas " + canvas + "; 2d " + c);
    //c.fillStyle = 'white';
    //c.fillRect(0,0, canvas.width, canvas.height);
    canvas.width = canvas.width //clears

    c.fillStyle = 'green';

    heightDiff = 15;
    numberLines = canvas.height / heightDiff
    //  Draw staves
    for (var i=0; i< numberLines; i++){
        c.strokeStyle = 'black';
        c.beginPath();
        c.moveTo(0,10 + (i * heightDiff));
        c.lineTo(canvas.width, 10 + (i * heightDiff));
        c.stroke();

        /*

        c.moveTo(0,20);
        c.lineTo(canvas.width,20);
        c.stroke();
        c.moveTo(0,30);
        c.lineTo(canvas.width,30);
        c.stroke();
        c.moveTo(0,40);
        c.lineTo(canvas.width,40);
        c.stroke();
        c.moveTo(0,50);
        c.lineTo(canvas.width,50);
        c.stroke();
        */

        // staff whitespace, not sure what you want to do here
        c.fillStyle = 'white';
        //c.fillRect(0,52, canvas.width, 50);
        }
    };

    </script>

Maybe a few tutorials on loops and using their vars will help ? http://www.echoecho.com/javascript9.htm not sure exactly what you want to achieve except make some lines that look like music notes?


答:
If you want to compete in timed programming competitions, you should learn the most expressive language allowed in the competition.  Perl would probably be best, followed by Ruby or Python.  You will still need good facility with algorithms, but at least you won't get bogged down writing something like

```<code>Integer prev = b.get(k)
if (prev == null) prev = 0
Integer v = a.get(k);
if (v == null) v = 0;
b.put(prev + v);
</code>```

instead of

```<code>b[k] += a[k]
</code>```

Don't worry about learning several libraries.  They are all very similar and the documentation is online.  Becoming fluent in more expressive languages will make you a better (but possibly frustrated) programmer in less expressive languages.  The opposite is not true.

N.B.

The difference between 200 lines of code and 40 lines of code is huge, and it's even bigger when it's the difference between a 200,000 line program and an 40,000 line program.  Then it's the difference between a team of five plus a manager, and a team of one or two.

Title: Is the algorithm more important than the programming language?

Body:
During the current (2013) Google Code Jam contest, there was a problem that took C++ and Java people 200+ lines of code as compared to Python people that solved the same problem only using 40 lines of code.

Python is not directly comparable with C++ and Java but the difference in verbosity I thought might perhaps have an influence on the efficiency of the algorithm.

How important is knowing the right algorithm compared to the choice of language? Could an excellently implemented Python program be implemented in C++ or Java in a better way (using the same algorithm) and does this have any relation to the natural verbosity of certain programming languages?

Body:
If you want to compete in timed programming competitions, you should learn the most expressive language allowed in the competition.  Perl would probably be best, followed by Ruby or Python.  You will still need good facility with algorithms, but at least you won't get bogged down writing something like

Integer prev = b.get(k)
if (prev == null) prev = 0
Integer v = a.get(k);
if (v == null) v = 0;
b.put(prev + v);

instead of

b[k] += a[k]

Don't worry about learning several libraries.  They are all very similar and the documentation is online.  Becoming fluent in more expressive languages will make you a better (but possibly frustrated) programmer in less expressive languages.  The opposite is not true.

N.B.

The difference between 200 lines of code and 40 lines of code is huge, and it's even bigger when it's the difference between a 200,000 line program and an 40,000 line program.  Then it's the difference between a team of five plus a manager, and a team of one or two.


答:
I would argue that, even outside competitions, algorithmic thinking is more important than knowing every trick for a specific language.

Of course, you want to know the language you work with as well as possible, but languages come and go, while the ability to think abstractly in terms of algorithms is a highly transferable skill.

Case in point: if I recall correctly, there was a post here on Programmers a while ago in which someone complained about failing FizzBuzz in an interview and blamed his lack of knowledge about Java's modulo operator for it.
This conclusion is wrong -- the lack of knowledge about how modulo works made him unable to think algorithmically about the problem and solve it, even in the absence of a dedicated modulo operator.
Going further: Java has a Tree class -- what if, in future, you have to work with a language that does not implement this class? Again, the ability to think about the problem trumps language-specific details.

I admit that the examples are simplistic, but they help to bring the point across.


问:
Best way to implement a website login and database tables for a small shop
I'm building a website for a small store and I was told that its better not to keep the login and the rest of the users information in the same table.

Now im wondering, what is the best way to implement this website's database?

Some of the database tables are:

Customers

Providers

Products

Etc..

I need to have different users, after someone is logged in the site, depending on their rights they can do a series of things:

If they are a customer they can order stuff

If they are employees they can order stuff, manage stock, add customers, etc

If they are the owner or administrator they can add employees and everything else.

Should I keep the login and the rest of the information of the user in the same table?

答:
There is no security reason to separate the login information from the rest of the user information.  It doesn't make your site safer in any meaningful way, so you should just organize the tables by what is most logical.

The real security issue in this domain is that you should not be storing plain text passwords.  Only store a salted hash of the password.

That being said, it probably makes logical sense to separate the user information into a few tables, because you have different users with different roles.  Have a user table with all the common information, then customer, employee, etc.

ContentLicense: CC BY-SA 4.0


答:
The problems that I have is getting funding for the unsexy programs like Resharper and Red Gate's SQL Prompt.  I've had developers magically appear with Resharper on their machines and honestly I don't ask too much.  I have said in the past that if you obtain a license that at some point the company will reimburse so buy it and pray (of get your own copy and keep it when/if you leave).

I guess it's blind ignorance.

Title: Use of pirated/cracked software for development

Body:
Disclaimer: I by no means condone the use of pirated software.

Have you ever witnessed the use of pirated software for development purposes? May be a company didn't have enough money to buy a piece of software and there were no free alternatives? May be a company wanted to try something out before buying and there were no trial licenses for that product. Whatever the circumstances, have you worked at a company where using pirated/cracked software was accepted? Were there any consequences to doing this?


答:
Some points:

The top positions tend to be C++ / C / Java, regardless of how many lines of code the difference is between that and some other language. This may be more about that the top coders tend to pick these languages over some others, probably because of their raw speed.

Unfortunately you can't easily see the programming language on Google Code Jam, but I downloaded a few of the top ones and, as far as I remember, these are mostly C / C++. TopCoder (a popular online programming contest hosting site) mostly has similar results.

Because they are pretty low level, I'm pretty sure you're not going to easily beat C / C++ in terms of raw running time (and Java's doesn't trail too far behind). From my experience, dynamically typed languages tend to be significantly slower than statically typed languages. The optimal solution may not even be fast enough in some languages, but this shouldn't be a general rule.

The right algorithm is vital. If you knew how to solve all the problems (in high detail) from the start, and you're a good, fast coder, you'll most likely win, regardless of which language you code in (assuming the optimal solution in that language is fast enough).

Straight number of lines isn't such a big deal. Once you get enough programming experience, you'll know that you can spend 10 minutes programming 10 lines or 200 lines, it all depends how complex the lines are. Also, if you've coded up similar code hundreds of times, you'll be able to do so pretty quickly. Not too mention all the macro's that top C / C++ coders often use to optimise their coding time.

Frank makes a good point - (outside of programming competitions) you can't go about coding in Python for your company if their entire code base is in C or whatever, you need to conform to their language.

It's reasonably easy to switch between languages, it's not easy to build up years of algorithmic thinking knowledge. I'm willing to bet almost any excellent programmer can switch to another (vaguely similar) language in, let's say, a week. Maybe he/she won't be good enough to win programming competitions in that language (give it another 2 weeks), but will have the basics down.


问:
How to find the running time of an algorithm that involves heuristics
I am working with A* algorithm, in which I have a 2D grid and given two points, find the shortest distance between them, while not running into any obstruction.

Now, for each cell, I find the distance from the source, and calculate the distance from destination. Add the two quantities, and the one that has the minimum value, that cell is considered next.

Now, How do I calculate the running time of such an algorithm, since I'll never know how many times this process will be repeated. i.e how many cells will I have to work, with, before I reach my destination. Kindly help.

I am looking for the upper bound of running time. In terms of the length of side of grid, i.e. N.

Thanks.

答:
Your 2D grid obviously has N^2 points.

The absolute worst case is that the heuristic always misdirects the algorithm, so the algorithm avoids the target point. With A*, that can happen with an extremely complex set of barriers, so that trying to move towards the target is generally a bad search strategy.

It's possible to construct a map where the only route to the target visits every single non-target cell before the reaching the target. Having constructed that map, you can remove the barriers that aren't really affecting how the algorithm searches (the algorithm still does the same search even with those barriers removed) to superficially allow more freedom, yet that freedom is never exploited.

Basically, that means the worst case is quadratic - the algorithm may search every one of those N^2 cells before finding the target.

One way to improve the algorithm is to use a measure of distance that's sensitive to the barriers - not just as-the-crow-flies. Obviously if the only route to the target requires visiting every cell that makes no difference, but the heuristic is much less likely to misdirect the search if there's some freedom to choose.

The problem is that getting a perfect measure of distance is as complex as finding the perfect route to the target anyway. However, you could precompute a shortest possible distance for each cell if the target is always in the same place, and use that as a lookup table later.


答:
Bad project managers/team lead.

Since one incompetent person’s have the power to ruin the work of a group of people. In the end, the project would do much better without upper management(project/team lead) decisions.

Dose the "Just do it quickly, we'll refactor later" decides.

Title: What are the worst false economies in software development?

Body: What are the worst false economies (that is ways of saving money that ultimately cost more than they save) prevalent in the software industry and how do you combat them?</p>


问:
Coarse grained remote interface vs encapsulating business logic
I'm writing a Web Service that will be consumed by a Mobile client.

The Mobile client has to make several chained requirements checks to determine whether the user may initiate a request, and if so what type.  If any of the checks fail then the user is redirected to a UI explaining why.

I can't decide whether I should expose an operation for each check on my Web Service, or expose a single coarse-grained interface that simply returns all the check value results in a single DTO.

Is the coarse-grained interface premature optimisation? I can always provide both the fine-grained and coarse-grained interfaces because the coarse-grained interface will use the local fine-grained methods to build its DTO.

答:
It depends on what the checks actually are and how they will be used.

If the checks will always occur together, then you should only expose a single method that does all of the checks.

If individual checks will be needed separately, then of course you will need individual methods available.  You might also want a single method that does them all together, depending on how complicated that is.


答:
Can same logic be implemented better in C++? Of course it can, if by better you mean faster and more memory efficient. Problem is that amount of effort required to do so is significantly higher. Furthermore, theoretically you could still go lower level and implement it in pure C or even ASM, which would take even longer, but you could have even more optimized code.

Of course, in case of competitions like Code Jam or TopCoder it isn't a biggie, as it's just 40 lines vs 200 lines. On the other hand in this type of competition what matters the most is the time/space complexity of the algorithm. While in real life application, YMMV, in these types of competitions O(n) algorithm written in slowest of languages will always beat O(n²) written in fastest of languages. Especially that there will be multiple test that are the worst case scenario.

But apart the competitions, if we're talking real life big projects, then it's no longer 40 lines vs 200 lines. In big projects it huge code base starts to be a problem. At which point you get to:

C++ vs Python?

Pure Python is slow. That's why standard Python interpreter (CPython) is written in C. Practically all with built-in functions written as highly optimized C. Python also can be easily used in conjunction with C libraries (via ctypes or as native cpython modules) and with C++ libraries via Boost::Python. This way you can write your high level logic in Python, a language that is flexible, allows quick prototyping and adaptation (meaning that you can spend more time tweaking and improving your algorithm). OTOH, you can write your lower level library functions in C or C++ module. Great example of such a approach is SciPy, which is Python library, yet under the hood it uses highly optimized numeric libraries such as ATLAS, LAPACK, Intels MKL or AMD's ACML.


答:
No, it isn't.

Optimization means changing the implementation of a bit of code so that it does the same thing, runs faster, and is harder to read or write. (And premature means doing it before you know that it will speed things up, and that a speed-up is needed here.)

What you propose are two different, fairly equally complicated ways of doing things, so whether to choose one or the other depends on the operations you'll likely need. If you may need all the checks anyway, and computing and returning them all together isn't obviously much more cumbersome, then there isn't any reason not to do that in the first place - it's just good common sense.

Title: Coarse grained remote interface vs encapsulating business logic

Body:
I'm writing a Web Service that will be consumed by a Mobile client.

The Mobile client has to make several chained requirements checks to determine whether the user may initiate a request, and if so what type.  If any of the checks fail then the user is redirected to a UI explaining why.

I can't decide whether I should expose an operation for each check on my Web Service, or expose a single coarse-grained interface that simply returns all the check value results in a single DTO.

Is the coarse-grained interface premature optimisation? I can always provide both the fine-grained and coarse-grained interfaces because the coarse-grained interface will use the local fine-grained methods to build its DTO.


问:
Why do most java classes end with "ers"?

...Provider

...Searcher

...Resolver

...Builder

...Manager

...Importer

...Descriptor

...Helper

...Indexer

Is it a global convention to refer a thing with "..ers" or "..ors". In contrast, a "thing" that composes with behaviors (habits) or attributes (properties) doesn't go with such naming convention.

It is fun to think that we named the classes based on their behaviors. The "Manager" classes are always resembles my Project Manager.

答:
Because you're writing procedural code in an OO language.

That Xer naming pattern indicates that the class is conceptually something that "does X" rather than something that "is X". Sometimes the former really is what you need, and the "Kingdom of Nouns" article from the comment rightly criticizes that Java forces you to create a class of objects anyway (The closure feature in the upcoming Java 8 should help with this a lot).

But if most of your classes are that way, you're doing something wrong. Look at the list of classes in the Java standard API. There are certainly quite a lot of "ers", but they are a clear minority.


问:
Is it OK to split long functions and methods into smaller ones even though they won't be called by anything else?
Lately I've been trying to split long methods into several short ones.

For example: I have a process_url() function which splits URLs into components and then assigns them to some objects via their methods. Instead of implementing all this in one function, I only prepare the URL for splitting in process_url(), and then pass it over to process_components() function, which then passes the components to assign_components() function.

At first, this seemed to improve readability, because instead of huge 'God' methods and functions I had smaller ones with more descriptive names.
However, looking through some code I've written that way, I've found that I now have no idea whether these smaller functions are called by any other functions or methods.

Continuing previous example: someone looking at the code might think that process_components() functionality is abstracted into a function because it's called by various methods and functions, when in fact it's only called by process_url().

This seems somewhat wrong. The alternative is to still write long methods and functions, but indicate their sections with comments.

Is the function-splitting technique I described wrong? What is the preferred way of managing large functions and methods?

UPDATE: My main concern is that abstracting code into a function might imply that it could be called by multiple other functions.

SEE ALSO: discussions on reddit at /r/programming (provides a different perspective rather than most of the answers here) and /r/readablecode.

答:
I'd say it depends.

If you're just splitting it for the sake of splitting and calling them names like process_url_partN and so on, then NO, please don't. It just makes it harder to follow later when you or someone else needs to figure out what is going on.

If you're pulling out methods with clear purposes that can be tested by themselves and makes sense on their own (even if nobody else are using them) then YES.

For your particular purpose it seems you have two goals.

Parse a URL and return a list of its components.

Do something with those components.

I'd write the first part separate and have it return a fairly general result that could be easily tested and potentially be reused later. Even better, I'd look for a built-in function that already does this in your language/framework and use that instead unless your parsing is super special. If it's super special I'd still write it as a separate method, but probably "bundle" it as a private/protected method in the class that handles the second (if you're writing object oriented code).

The second part I'd write as its own component which uses the first for the URL parsing.


问:
Beautiful Erlang Code
I'm trying to learn more about Erlang than the toy projects I've been playing with. To this end, I'm reading through Programming Erlang and some of the archives from Armstrong on Software.

I would also like to read over some example (preferably production) code that showcases the sorts of things you can build with Erlang that would be disproportionately difficult in other languages. Aside from (I assume) Yaws, are there any publicly available examples of beautiful Erlang code that I could read through to gain a better understanding of the language and/or see the idiomatic uses for various language constructs?

I'm specifically not looking for code that "gets the job done" but uses questionable practices, or examples along the lines of "here's how you write factorial in Erlang".

In the same vein, can anyone recommend any good literature for learning this language (other than the mentioned "Programming Erlang")? For preference, something you yourself used to learn it, but if there's some community standard books for it, throw those in too.

答:
Another good reference is Erlang and OTP in Action.

About the code samples: it is kind of hard to find best practices for Erlang, but I would suggest you try these websites:

Trapexit

Erlang Programming Language

Erlang Factory

Planet Erlang

Erlang Solutions

Check the links from this article (open source software written in erlang) and you might find interesting code.

Title: Beautiful Erlang Code


问:
Should my async task library swallow exceptions quietly?
I've just learned that .NET 4.5 introduced a change to how exceptions inside a Task are handled. Namely, they are quietly suppressed.

The official reasoning for why this was done appears to be "we wanted to be more friendly to inexperienced developers":

In .NET 4.5, Tasks have significantly more prominence than they did in .NET 4, as they’re baked in to the C# and Visual Basic languages as part of the new async features supported by the languages.  This in effect moves Tasks out of the domain of experienced developers into the realm of everyone.  As a result, it also leads to a new set of tradeoffs about how strict to be around exception handling.

(source)

I've learned to trust that many of the decisions in .NET were made by people who really know what they're doing, and there is usually a very good reason behind things they decide. But this one escapes me.

If I were designing my own async task library, what is the advantage of swallowing exceptions that the developers of the Framework saw that I'm not seeing?

答:
For what it's worth, the document you linked to gives an example case as justification:

```<code>Task op1 = FooAsync();
Task op2 = BarAsync();
await op1;
await op2;
</code>```

In this code, the developer is launching two asynchronous operations
to run in parallel, and is then asynchronously waiting for each using
the new await language feature...[C]onsider what will happen if both
op1 and op2 fault.  Awaiting op1 will propagate op1’s exception, and
therefore op2 will never be awaited.  As a result, op2’s exception
will not be observed, and the process would eventually crash.

To make it easier for developers to write asynchronous code based on
Tasks, .NET 4.5 changes the default exception behavior for unobserved
exceptions.  While unobserved exceptions will still cause the
UnobservedTaskException event to be raised (not doing so would be a
breaking change), the process will not crash by default.  Rather, the
exception will end up getting eaten after the event is raised,
regardless of whether an event handler observes the exception.

I'm not convinced by this.  It removes the possibility of an unambiguous, but hard to trace error (mysterious program crash that might occurs long after the actual error), but replaces it with the possibility of a completely silent error--which might become an equally hard to trace problem later on in your program.  That seems like a dubious choice to me.

The behavior is configurable--but of course, 99% of developers are just going to use the default behavior, never thinking about this issue. So what they selected as the default is a big deal.

Body:
For what it's worth, the document you linked to gives an example case as justification:

Task op1 = FooAsync();
Task op2 = BarAsync();
await op1;
await op2;

In this code, the developer is launching two asynchronous operations
to run in parallel, and is then asynchronously waiting for each using
the new await language feature...[C]onsider what will happen if both
op1 and op2 fault.  Awaiting op1 will propagate op1’s exception, and
therefore op2 will never be awaited.  As a result, op2’s exception
will not be observed, and the process would eventually crash.

To make it easier for developers to write asynchronous code based on
Tasks, .NET 4.5 changes the default exception behavior for unobserved
exceptions.  While unobserved exceptions will still cause the
UnobservedTaskException event to be raised (not doing so would be a
breaking change), the process will not crash by default.  Rather, the
exception will end up getting eaten after the event is raised,
regardless of whether an event handler observes the exception.

I'm not convinced by this.  It removes the possibility of an unambiguous, but hard to trace error (mysterious program crash that might occurs long after the actual error), but replaces it with the possibility of a completely silent error--which might become an equally hard to trace problem later on in your program.  That seems like a dubious choice to me.

The behavior is configurable--but of course, 99% of developers are just going to use the default behavior, never thinking about this issue. So what they selected as the default is a big deal.


答:
Both. It's a question of Single Responsibiliy Principle

That is; you need the coarse grained ones to meet requirements for use cases it sounds like you're saying, and you need the fine grained ones that the coarse grained ones will rely on.

My suggestion: Expose them both, and do so well separated in different classes. If you only expose the coarse grained ones, you're not putting a boundary between the coarse and fine grained work. In the future this may likely result in the multiple individual responsibilities of the fine grained work bleeding into the coarse grained ones which would be an SRP violation.

So:

Expose them both to ensure the boundary's are maintained, and you have clean separation of concerns and responsibilities.


问:
Are there any large scale enterprise frameworks for PHP
I'm curious if there are any commonly used large enterprise frameworks for PHP that would be your whole or most of your environment if you were working in PHP. Something comparable to ASP.NET's WebForms or MVC in that when you're working in either one, most of your code and system is based off of working integratively within that framework.

Edit:
Specifically I'm looking for a framework that fit's the bill of basically being what you would use for 99% of your work in writing your website, this means:

data retrieval, some kind of ORM in the framework

data representation, some kind of data aware automatically configured UI controls that make reading and writing to a DB easy

data caching

data serialization

data communication, an easy way to generate and host web services of various sorts

答:
The most used frameworks are:

Zend Framework http://framework.zend.com/

Symfony http://symfony.com/

Both have already a second version out there and a big community supporting them.

Edit: They support almost all your listed features:

data retrieval

in ZF via Table Data Gateway Pattern

Symfony can integrate Doctrine, which is a full ORM

Both are only frameworks and have no integrated admin frontend to edit the data, but provide easy-to-use formular and element classes, to set them up on your own

Both have multiple ways to implement data caching, serialization and comunication


问:
How should I implement code review in this situation?
My question is about how to put code review into practice in a workplace where nobody else has asked for it, I've never done it before, and I'm not entirely sure if it's worthwhile for this type of programming.

I'm a contractor on an assignment that mostly involves tools engineering, data analysis, fixing code when someone's Excel template changes break a macro, etc.  It's total cowboy coding: Requests are more "do what you need to do to hack together something that works ASAP, we need it in production tomorrow morning and we're only going to need it for a couple months" than "make a well-structured application that will be easy to maintain and develop under all foreseeable circumstances."

The software engineering team is me and one other guy whom I supervise.  We don't currently follow any kind of software development methodology beyond "make something that fulfills the functional requirements", and neither of us have ever worked anywhere that had any code review or design principles.  Everything we make is either VBA or C# desktop apps, and each of us is usually working on a separate assignment rather than collaboratively building the same program.  There is no version control system in place and we don't have server access to install any such system.

What I'm trying to figure out is, given that the work is very ad hoc, what kind of code review, if any, should I put in place?  Or is it even necessary for the kind of work we're doing?

答:
I agree with the pair programming suggestion, however if you can't afford it, I find pre-commit one-on-one code reviews to be a good compromise collaboration wise. If you don't have a source control system and thus don't do commits, well first of all you should absolutely get one (a DVCS in your case ?) :) and in the mean time you can do these code reviews just before release, i.e. before publishing the application installer on a server, handing over the Excel template with the updated macro to the user, etc.

Each time a significant, complex enough update to a program has been written and needs to go live, the author should from his own initiative ask for a complete collaborative review of that code. This takes time but it takes that to spread the knowledge across all team members, establish collective code ownership and perform a first pass of internal quality control on what's produced.