问:
When to use HTTP status code 404 in an API
I am working on a project and after arguing with people at work for about more than a hour. I decided to know what people on stack-exchange might say.

We're writing an API for a system, there is a query that should return a tree of Organization or a tree of Goals.

The tree of Organization is the organization in which the user is present, In other words, this tree should always exists. In the organization, a tree of goal should be always present. (that's where the argument started). In case where the tree doesn't exist, my co-worker decided that it would be right to answer response with status code 200. And then started asking me to fix my code because the application was falling apart when there is no tree.

I'll try to spare flames and fury.

I suggested to raise a 404 error when there is no tree. It would at least let me know that something is wrong. When using 200, I have to add special check to my response in the success callback to handle errors. I'm expecting to receive an object, but I may actually receive an empty response because nothing is found. It sounds totally fair to mark the response as a 404. And then war started and I got the message that I didn't understand HTTP status code schema. So I'm here and asking what's wrong with 404 in this case? I even got the argument "It found nothing, so it's right to return 200". I believe that it's wrong since the tree should be always present. If we found nothing and we are expecting something, it should be a 404.

More info,

I forgot to add the urls that are fetched.

Organizations

```<code>/OrgTree/Get
</code>```

Goals

```<code>/GoalTree/GetByDate?versionDate=...
/GoalTree/GetById?versionId=...
</code>```

My mistake, both parameters are required. If any versionDate that can be parsed to a date is provided, it will return the closes revision. If you enter something in the past, it will return the first revision. If by Id with a id that doesn't exists, I suspect it's going to return an empty response with 200.

Extra

Also, I believe the best answer to the problem is to create default objects when organizations are created, having no tree shouldn't be a valid case and should be seen as an undefined behavior. There is no way an account can be used without both trees. For that reasons, they should be always present.

also I got linked this (one similar but I can't find it)

http://viswaug.files.wordpress.com/2008/11/http-headers-status1.png

答:
When in doubt, consult the documentation. Reviewing the W3C definitions for HTTP Status codes, gives us this:

200 OK - The request has succeeded. The information returned with the response is dependent on the method used in the request.

404 Not Found - The server has not found anything matching the Request-URI.

In the context of your API, it very much depends on how queries are created and how objects are retrieved. But, my interpretation has always been that:

If I ask for a particular object, and it exists return 200 code, if it doesn't exist return the correct 404 code.

But, if I ask for a set of objects that match a query, a null set is a valid response and I want that returned with a 200 code. The rationale for this is that the query was valid, it succeeded and the query returned nothing.

So in this case you are correct, the service isn't searching for "a specific thing" it is requesting a particular thing, if that thing isn't found say that clearly.

I think Wikipedia puts it best:

200 OK - ... The actual response will depend on the request method used. In a GET request, the response will contain an entity corresponding to the requested resource.

404 Not Found - The requested resource could not be found but may be available again in the future. Subsequent requests by the client are permissible.

Seems pretty clear to me.

Regarding the example requests

```<code>/GoalTree/GetByDate?versionDate=...
/GoalTree/GetById?versionId=...
</code>```

For the format, you said, you always return the nearest revision to that date. It will never not return an object, so it should always be returning 200 OK. Even if this were able to take a date range, and the logic were to return all objects within that timeframe returning 200 OK - 0 Results is ok, as that is what the request was for - the set of things that met that criteria.

However, the latter is different as you are asking for a specific object, presumably unique, with that identity. Returning 200 OK in this case is wrong as the requested resource doesn't exist and is not found.

Regarding choosing status codes

2xx codes Tell a User Agent (UA) that it did the right thing, the request worked. It can keep doing this in the future.

3xx codes Tell a UA what you asked probably used to work, but that thing is now elsewhere. In future the UA might consider just going to the redirect.

4xx codes Tell a UA it did something wrong, the request it constructed isn't proper and shouldn't try it again, without at least some modification.

5xx codes Tell a UA the server is broken somehow. But hey that query could work in the future, so there is no reason not to try it again. (except for 501, which is more of a 400 issue).

You mentioned in a comment using a 5xx code, but your system is working. It was asked a query that doesn't work and needs to communicate that to the UA. No matter how you slice it, this is 4xx territory.

Consider an alien querying our solar system

Alien: Computer, please tell me all planets that humans inhabit.

Computer: 1 result found. Earth

Alien: Computer, please tell me about Earth.

Computer: Earth - Mostly Harmless.

Alien: Computer, please tell me about all planets humans inhabit, outside the asteroid belt.

Computer: 0 results found.

Alien: Computer, please destroy Earth.

Computer: 200 OK.

Alien: Computer, please tell me about Earth.

Computer: 404 - Not Found

Alien: Computer, please tell me all planets that humans inhabit.

Computer: 0 results found.

Alien: Victory for the mighty Irken Empire!

Body:
When in doubt, consult the documentation. Reviewing the W3C definitions for HTTP Status codes, gives us this:

200 OK - The request has succeeded. The information returned with the response is dependent on the method used in the request.

404 Not Found - The server has not found anything matching the Request-URI.

In the context of your API, it very much depends on how queries are created and how objects are retrieved. But, my interpretation has always been that:

If I ask for a particular object, and it exists return 200 code, if it doesn't exist return the correct 404 code.

But, if I ask for a set of objects that match a query, a null set is a valid response and I want that returned with a 200 code. The rationale for this is that the query was valid, it succeeded and the query returned nothing.

So in this case you are correct, the service isn't searching for "a specific thing" it is requesting a particular thing, if that thing isn't found say that clearly.

I think Wikipedia puts it best:

200 OK - ... The actual response will depend on the request method used. In a GET request, the response will contain an entity corresponding to the requested resource.

404 Not Found - The requested resource could not be found but may be available again in the future. Subsequent requests by the client are permissible.

Seems pretty clear to me.

Regarding the example requests

/GoalTree/GetByDate?versionDate=...
/GoalTree/GetById?versionId=...

For the format, you said, you always return the nearest revision to that date. It will never not return an object, so it should always be returning 200 OK. Even if this were able to take a date range, and the logic were to return all objects within that timeframe returning 200 OK - 0 Results is ok, as that is what the request was for - the set of things that met that criteria.

However, the latter is different as you are asking for a specific object, presumably unique, with that identity. Returning 200 OK in this case is wrong as the requested resource doesn't exist and is not found.

Regarding choosing status codes

2xx codes Tell a User Agent (UA) that it did the right thing, the request worked. It can keep doing this in the future.

3xx codes Tell a UA what you asked probably used to work, but that thing is now elsewhere. In future the UA might consider just going to the redirect.

4xx codes Tell a UA it did something wrong, the request it constructed isn't proper and shouldn't try it again, without at least some modification.

5xx codes Tell a UA the server is broken somehow. But hey that query could work in the future, so there is no reason not to try it again. (except for 501, which is more of a 400 issue).

You mentioned in a comment using a 5xx code, but your system is working. It was asked a query that doesn't work and needs to communicate that to the UA. No matter how you slice it, this is 4xx territory.

Consider an alien querying our solar system

Alien: Computer, please tell me all planets that humans inhabit.

Computer: 1 result found. Earth

Alien: Computer, please tell me about Earth.

Computer: Earth - Mostly Harmless.

Alien: Computer, please tell me about all planets humans inhabit, outside the asteroid belt.

Computer: 0 results found.

Alien: Computer, please destroy Earth.

Computer: 200 OK.

Alien: Computer, please tell me about Earth.

Computer: 404 - Not Found

Alien: Computer, please tell me all planets that humans inhabit.

Computer: 0 results found.

Alien: Victory for the mighty Irken Empire!


问:
If my team has low skill, should I lower the skill of my code?
For example, there is a common snippet in JS to get a default value:

```<code>function f(x) {
    x = x || 'default_value';
}
</code>```

This kind of snippet is not easily understood by all the members of my team, their JS level being low.

Should I not use this trick then? It makes the code less readable by peers, but more readable than the following according to any JS dev:

```<code>function f(x) {
    if (!x) {
        x = 'default_value';
    }
}
</code>```

Sure, if I use this trick and a colleague sees it, then they can learn something. But the case is often that they see this as "trying to be clever".

So, should I lower the level of my code if my teammates have a lower level than me?

答:
Comment Well

Should you lower the skill of your code? Not necessarily, but you should definitely raise the skill of your comments. Be sure to include good comments in your code, especially around the sections you think might be more complicated. Don't use so many comments that the code becomes hard to follow, but be sure to make the purpose of each section clear.

The reality is that being slightly more verbose with comments can be useful with less skilled team members, but those with the lowest skill with ignore them, especially if there's too many, so don't overdo it.

A Matter of Style?

The example you provided is somewhat basic, but also rather stylistic. A comment around every variable default would be pretty tedious to maintain and read. Instead, stylistic or repeated shortcuts or code patterns should probably be established as a standard. If you think something like that form of parameter defaulting should be understood by all and used every time, write these ideas down and take them to your team lead. It's possible all it will take to teach your teammates is a simple meeting where you discuss the standards you proposed.

As another answer already stated, keep it consistent.

Teach a Man To Fish...

Teaching your teammates is probably the best way you can help everyone involved. Make it clear that if anyone has a question over a piece of code with your name in the commit log or timestamps they should feel free to ask you about it. If your team has code reviews, this is a great opportunity to explain any possibly confusing (ahem) well-commented code to your teammates. If your team does not have code reviews, why not? Get to it!

You need to be careful, though. You might not always be around to teach people and you may even forget what you were originally trying to do in a given section of code.

"Clever" Tricks

Keeping the abilities of your teammates in mind is definitely important, but writing maintainable code often means not using arcane shortcuts to problems which might have more common solutions. This is important even when your teammates are intelligent. You do not want to make the code take too long to grasp or to have subtle but important side effects that could be missed. In general, it's best to avoid "clever" tricks when there are suitable alternatives. You never know who might have to maintain the code down the line - often times the older versions of ourselves will not remember the details or reasons for these tricks.

If you find that you must implement a clever trick, at least follow the next bit of advice...

KISS

When in doubt, keep it simple. Whether code is simple or not doesn't necessarily correspond to programmer skill like you might think. In fact some of the most brilliant solutions to a problem are the simplest ones, and some of the more complicated solutions end up on TheDailyWTF. Keeping your code simple and concise can make some of the more intelligent but possibly counter-intuitive decisions easier to grasp.

ContentLicense: CC BY-SA 3.0


答:
Ignoring the fact that /GoalTree/Get* looks like a verb, not resources, you should always return 200 because the URI /GoalTree/Get* represent resources that's always available for access and it's not client error if there's no tree as a result of a request. Just return 200 with empty set when there's no entity to be returned.

You use 404 if the resource is not found, not when there's no entity.

Put it in another way, if you want to return 404 for your objects, then give them their own URIs.

Title: When to use HTTP status code 404 in an API

Body:
I am working on a project and after arguing with people at work for about more than a hour. I decided to know what people on stack-exchange might say.

We're writing an API for a system, there is a query that should return a tree of Organization or a tree of Goals.

The tree of Organization is the organization in which the user is present, In other words, this tree should always exists. In the organization, a tree of goal should be always present. (that's where the argument started). In case where the tree doesn't exist, my co-worker decided that it would be right to answer response with status code 200. And then started asking me to fix my code because the application was falling apart when there is no tree.

I'll try to spare flames and fury.

I suggested to raise a 404 error when there is no tree. It would at least let me know that something is wrong. When using 200, I have to add special check to my response in the success callback to handle errors. I'm expecting to receive an object, but I may actually receive an empty response because nothing is found. It sounds totally fair to mark the response as a 404. And then war started and I got the message that I didn't understand HTTP status code schema. So I'm here and asking what's wrong with 404 in this case? I even got the argument "It found nothing, so it's right to return 200". I believe that it's wrong since the tree should be always present. If we found nothing and we are expecting something, it should be a 404.

More info,

I forgot to add the urls that are fetched.

Organizations

```<code>/OrgTree/Get
</code>```

Goals

```<code>/GoalTree/GetByDate?versionDate=...
/GoalTree/GetById?versionId=...
</code>```

My mistake, both parameters are required. If any versionDate that can be parsed to a date is provided, it will return the closes revision. If you enter something in the past, it will return the first revision. If by Id with a id that doesn't exists, I suspect it's going to return an empty response with 200.

Extra

Also, I believe the best answer to the problem is to create default objects when organizations are created, having no tree shouldn't be a valid case and should be seen as an undefined behavior. There is no way an account can be used without both trees. For that reasons, they should be always present.

also I got linked this (one similar but I can't find it)

http://viswaug.files.wordpress.com/2008/11/http-headers-status1.png


答:
This may have already been said in another answer, but I would like to answer this question my own orders.

General Guideline

When you work on a team, you are not the target audience of a piece of code. Your audience is the developers of your team. Don't write code they can't understand without good reason.

Unless there is a specific downside to it, all of the code should be written following a specific pattern or guideline that will allow easy maintenance by the developers who will be maintaining it. (A caveat: Following bad patterns just because they are currently in the code base is terrible practice.)

If you can find a good reason to use a language specific idiom that isn't easily readable by the target audience, add a comment. If you find that you need to add a comment to every other line, you may want to rewrite your code to be more readable by your audience. I don't find it valuable to be idiomatic for the sake of being idiomatic.

Specific Example

We have a large number perl scripts in our code base. We typically only use perl for very simple operations and the vast majority of the code is written by java developers, so it's styled much like java. We have a set of perl scripts and a framework that was written by a 'perl guru' that has since left our firm. This code contains many of the more obscure perl idioms and none of our developers, including myself, can read this perl code without extended effort. We often curse him for it. :)

Title: If my team has low skill, should I lower the skill of my code?

Body:
For example, there is a common snippet in JS to get a default value:

```<code>function f(x) {
    x = x || 'default_value';
}
</code>```

This kind of snippet is not easily understood by all the members of my team, their JS level being low.

Should I not use this trick then? It makes the code less readable by peers, but more readable than the following according to any JS dev:

```<code>function f(x) {
    if (!x) {
        x = 'default_value';
    }
}
</code>```

Sure, if I use this trick and a colleague sees it, then they can learn something. But the case is often that they see this as "trying to be clever".

So, should I lower the level of my code if my teammates have a lower level than me?


问:
How do you name your private variables in C#?
What is the best practice, most commonly accepted naming conventions for private variables in C#?

private int myInteger;

private int MyInteger;

private int mMyInteger;

private int _myInteger;

private int _MyInteger;

Mysterious other option

Which do you use and why?  (My company is fairly new to C# and I would like to pick the most "industry accepted" method to try and get into our coding standard.)

答:
I use the following naming scheme:

1st (myInteger) for local scoped variables

2nd (MyInteger) for public properties

4th (_myInteger) for private variables

ContentLicense: CC BY-SA 2.5


问:
Where can I find statistics on worldwide developers and software companies?
I try to find an answer of a very difficult question. The question is:

How many developers and how many software companies are there in the world?

For example if I check the Statistic Austria page I can see that in Austria there are 8383 companies with 35522 employees defined as "Computer programming, consultancy and related activities" and another 4102 companies with 15171 employees defined as "Information service activities".

This statistic is good, but it is only for Austria. Is there a similar for Europe, USA, Worldwide?

答:
answer: In 2005, there were about 680,000
enterprises in the EU27 whose main activity was
in ICT manufacturing and service industries, with
5.9 million people employed...
http://ftp.jrc.es/EURdoc/JRC49951.pdf</p>


答:
This is an interesting question, because it's all about the system's specification.

imel96's response has convinced me a 404 wouldn't be a proper response, since the 4xx family of codes is mainly for user/client errors, and this isn't one. The URL is well-formed and the tree must be there; if it's not, the system is in an inconsistent state!

Therefore this is a server error, i.e. something in the 5xx family. Possibly a generic 500 Internal Server Error or a 503 Service Unavailable (the service being "fetch me the tree that must be there").


问:
Why do most programming languages only support returning a single value from a function?
Is there a reason why functions in most(?) programming languages are designed to support any number of input parameters but only one return value?

In most languages, it is possible to "work around" that limitation, e.g. by using out-parameters, returning pointers or by defining/returning structs/classes. But it seems strange that programming languages were not designed to support multiple return values in a more "natural" way.

Is there an explanation for this?

答:
In most languages where functions are supported you can use a function call anywhere where a variable of that type can be used:-

```<code>x = n + sqrt(y);
</code>```

If the function returns more than one value this will not work. Dynamically typed languages such as python will allow you to do this, but, in most cases it will throw up a run time error  unless it can work out something sensible to do with a tuple in the middle of an equation.

Body:
In most languages where functions are supported you can use a function call anywhere where a variable of that type can be used:-

x = n + sqrt(y);

If the function returns more than one value this will not work. Dynamically typed languages such as python will allow you to do this, but, in most cases it will throw up a run time error  unless it can work out something sensible to do with a tuple in the middle of an equation.


问:
How can I find a good open source project to join?
I just started working a year ago, and I want to join an open source project for the same reasons as anyone else: help create something useful and develop my skills further.

My problem is, I don't know how to find a project where I'll fit in.

How can I find a beginner-friendly project?  What attributes should I be searching for?  What are warning signs that a project might not be the right fit?  Are there any tools out there to help match people with open source projects?

There's a similar question here, but that question has to do with employment and is limited to PHP/Drupal.

答:
OpenHatch was created specifically for this.

To quote:

OpenHatch is a non-profit dedicated to matching prospective free software
  contributors with communities, tools, and education.

You can browse projects by type, technology, skill level required etc. and find what matches your level.


问:
Name for this antipattern? Fields as local variables
In some code I'm reviewing, I'm seeing stuff that's the moral equivalent of the following:

```<code>public class Foo
{
    private Bar bar;

    public MethodA()
    {
        bar = new Bar();
        bar.A();
        bar = null;
    }

    public MethodB()
    {
        bar = new Bar();
        bar.B();
        bar = null;
    }
}
</code>```

The field bar here is logically a local variable, as its value is never intended to persist across method calls. However, since many of the methods in Foo need an object of type Bar, the original code author has just made a field of type Bar.

This is obviously bad, right?

Is there a name for this antipattern?

答:
This code smell is referred to as Temporary Field in Refactoring by Beck/Fowler.

http://sourcemaking.com/refactoring/temporary-field

Edited to add more explanation by request of moderators:
You can read more about the code smell in the referenced URL above, or in the hard copy of the book.  Since the OP was looking for the name for this particular antipattern/code smell, I thought that citing a heretofore unmentioned reference to it from an established source that's over 10 years old would be helpful, though I fully realize that I'm late to the game on this question, so it's unlikely the answer will get voted up or accepted.

If it's not too personally promotional, I also reference and explain this particular code smell in my forthcoming Pluralsight course, Refactoring Fundamentals, which I expect will be published in August 2013.

By way of adding more value, let's talk about how to fix this particular issue.  There are several options.  If the field is truly only used by one method, then it can be demoted to a local variable.  However, if multiple methods are using the field to communicate (in lieu of parameters), then this is the classic case described in Refactoring, and can be corrected by replacing the field with parameters, or if the methods that work with this code are closely related, Extract Class may be used to pull the methods and the field(s) out into their own class, in which the field is always in a valid state (perhaps set during construction) and represents the state of this new class.  If going the parameter route, but there are too many values to pass around, another option is to introduce a new Parameter Object, which can be passed instead of all the individual variables.


问:
What's so useful about closures (in JS)?
In my quest to understand closures in the context of JS, I find myself asking why do you even need to use closures? What's so great about having an inner function be able to access the parent function's variables even after the parent function returns? I'm not even sure I asked that question correctly because I don't understand how to use them.

Can someone give a real world example in JS where a closure is more beneficial vs. the alternative, whatever that may be?

Edit: the question Why is closure important for JavaScript? did not answer clearly enough what I want to understand. So, I don't consider this a duplicate.

I'll take a look at all of the answers/resources, and I'll mark an accepted one. Thanks to everyone!

答:
The really useful thing about closures is that they let you stick arbitrary data in a callback, independent of the function signature.

A good real-world example of where it comes in handy is animation.  JS isn't my strongest language, so I won't even try to write code for this, but here's the general idea:

Let's say you've got a function called Timer that takes two parameters, an interval and a callback.  (I know that the DOM has something like this, that's used for implementing animations in JavaScript.)  And after the interval is up, it calls your callback like so: CallbackFunction();

See the obvious problem?  It doesn't give you back data that might be needed inside your callback function.  Some callback systems let you pass an arbitrary object in when you set it up, and then when the callback is called, it passes that object back as context.  But then things get hairy if you need two pieces of data inside the callback, and so on...

The solution is to pass in a closure, and have it close around all the data you need.  Then it can be called as a callback at a later time (after the timer has run, for example,) and it can keep all of the data (enclosed variables) that it needs in order to perform its work.


答: How about a 204 No Content? It would suggest that your request was processed successfully but is returning nothing. It's still a "success" but allows you to see if you have results based on status code alone.</p>


答:
Javascript is asynchronous by nature. Your code can't wait. Instead, you say, "when this happens, call this function". This means that Javascript code is full of functions. Functions that are passed to other functions, called by them, and sometimes even returned by them to be called later. These functions often want to use some data that their defining scope has available, but their caller (the browser) does not.

```<code>function getSize(src, callback){
  var img = new Image();
  img.onload = function(event){
     console.log(event);
     callback(img.width, img.height);
  }
  img.src = src
}
</code>```

Now, this looks like a normal code. Except it uses the closure scope! img and callback are both closed over by img.onload. Now, imagine you didn't have closures. What are the other options? You might find img in the event object, but definitely not the callback. You need a function that takes two kinds of arguments: those that are set when you define a function, and those that are set when you call it. Or, you can tell the system everything you need. Or, you need a native currying mechanism*. You don't want to tell foreign code everything you know just because you need to react to its events, so let's assume that such mechanism exists. ES5 introduces bind:

* currying is a technique where a new function is created by binding arguments to an existing function in advance, and sending the arguments as the remaining arguments to the original function. The original function's return value is then returned

```<code>function getSize(src, callback){
  var img = new Image();
  img.onload = function(callback, img, event){
     callback(img.width, img.height);
  }.bind(null, callback, img); //not needed if you have closures
  img.src = src
}
</code>```

What are the arguments to bind? null sets the this context. Our hypothetical curry method would not. Then, callback and img. These must be in the same order as the arguments to img.onload. This is acceptable every now and then, but not if you have to curry uphill in both directions. More importantly, it is acceptable if you have three arguments, but not if you have thirty.

Now, for the funny part: The global scope is technically a closure scope too. But, even if it wasn't, you still don't want to define your module's utility functions in the global scope (namespacing issues). Functions are stored in variables!

```<code>getSize = function(Image, src, callback){
  var img = new Image();
  img.onload = function(callback, img, event){
     callback(img.width, img.height);
  }.bind(null, callback, img); //not needed if you have closures
  img.src = src
}.bind(null, Image) //not needed if you have closures
</code>```

Now, assume you want to transform the image coordinates for some reason, and that transformation is dependent on the source. Where do we need to add transform and src?

```<code>getSize = function(Image, transform, src, callback){ //here
  var img = new Image();
  img.onload = function(transform, src, callback, img, event){ //here
     var coord = transform(img.width, img.height, src); //used here
     callback(coord.x, coord.y);
  }.bind(null, transform, src, callback, img); //here
  img.src = src;
}.bind(null, transform, Image); //here
</code>```

Can you spot the bug? Yep, the outer bind arguments are in the wrong order.

You can circumvent this by holding all parameters in a global object. Of course, you don't want to modify the caller's scope, so you define your own scope whenever you want to pass a few extra arguments. With a few good conventions, this may be reasonably bug-free:

```<code>var scope = {Image: Image, ...}

getSize = function(scope, src, callback){
  var img = new scope.Image();
  var scope = {scope: scope, src: src, callback: callback, img:img};
  img.onload = function(scope, event){
     var coord = scope.transform(scope.img.width, scope.img.height, scope.src);
     callback(coord.x, coord.y);
  }.bind(null, scope);
  img.src = src;
}.bind(null, scope)
</code>```

Can you spot the bug now? scope.transform is undefined. We need scope.scope.transformThere's another one. Can you spot it too? Now this is getting ridiculous, even if we used one-letter variable for scope here. Maybe we could utilise the prototype chain:

```<code>var scope = {Image: Image, ...}

getSize = function(scope, src, callback){
  var img = new scope.Image();
  var scope = scope.Object.create(scope)
  scope.src = src;
  scope.callback = callback;
  scope.img = img;
  img.onload = function(scope, event){
     var coord = scope.transform(scope.img.width, scope.img.height, scope.src);
     callback(coord.x, coord.y);
  }.bind(null, scope);
  img.src = src;
}.bind(null, scope)
</code>```

of course, we could define our local variables directly in the scope so that we don't have to declare them twice if some inner function might use it. Unfortunately, there's no such trick for the arguments. There is the arguments variable, but using it for our purpose is kinda messy (scope.getSizeArgs[0]; quick - which one is it?). However, so far, to circumvent the lack of closures we have:

for each scope, created a special scope variable, with the parent's scope as its prototype.

added all arguments to it

used it for all local variables that might be needed in an inner function.

Of course, this is getting ridiculous. Maybe if the language somehow knew that if we use an undeclared variable, it should search for it in the defining scope, and even create such scope object for us when needed so that the variables can outlive their defining functions? Well, it does.

```<code>function getSize(src, callback){
  var img = new Image();
  img.onload = function(event);
     console.log(event);
     var coords = transform(img.width, img.height);
     callback(coords.x, coords.y);
  }
  img.src = src;
}
</code>```

Also, this explicit passing has another disadvantage: whenever you write to the scope, you always write to a local variable. You cannot modify a variable from an inner function. Sure, you could use one-element arrays or a special Reference<T> type, but this smells of a non-awesome language. With closures, you can do this directly. Do you actually need this?

```<code>var width = window.clientWidth;
window.addEventListener('resize', function(){width = window.clientWidth});
setInterval(function(){
  ...
</code>```

You might say that sometimes you want the caller's scope as the alternative would be to have 30 arguments. But, the caller does not want you to see their local scope, and they don't want to have to avoid variable names you might one day consider significant. You can still pass objects around, but you don't call them scopes. Some may say "data transfer object"; I prefer the term "named arguments"

```<code>$.ajax({
  url: "http://www.example.com/cors-api/echo.json",
  dataType: "json",
  success: function(response){
    ..
</code>```

Now, for the classic example of closure scoping, complete with an immediately invoked function expression to limit the scope of the static variable nextId:

```<code>var getId = (function(){
  var nextId = 0;
  return function getId(){ //named for clarity
    return nextId++;
  }
})()

getId() //0
getId() //1
getId() //2
</code>```

Title: What's so useful about closures (in JS)?

Body:
In my quest to understand closures in the context of JS, I find myself asking why do you even need to use closures? What's so great about having an inner function be able to access the parent function's variables even after the parent function returns? I'm not even sure I asked that question correctly because I don't understand how to use them.

Can someone give a real world example in JS where a closure is more beneficial vs. the alternative, whatever that may be?

Edit: the question Why is closure important for JavaScript? did not answer clearly enough what I want to understand. So, I don't consider this a duplicate.

I'll take a look at all of the answers/resources, and I'll mark an accepted one. Thanks to everyone!

Body:
Javascript is asynchronous by nature. Your code can't wait. Instead, you say, "when this happens, call this function". This means that Javascript code is full of functions. Functions that are passed to other functions, called by them, and sometimes even returned by them to be called later. These functions often want to use some data that their defining scope has available, but their caller (the browser) does not.

function getSize(src, callback){
  var img = new Image();
  img.onload = function(event){
     console.log(event);
     callback(img.width, img.height);
  }
  img.src = src
}

Now, this looks like a normal code. Except it uses the closure scope! img and callback are both closed over by img.onload. Now, imagine you didn't have closures. What are the other options? You might find img in the event object, but definitely not the callback. You need a function that takes two kinds of arguments: those that are set when you define a function, and those that are set when you call it. Or, you can tell the system everything you need. Or, you need a native currying mechanism*. You don't want to tell foreign code everything you know just because you need to react to its events, so let's assume that such mechanism exists. ES5 introduces bind:

* currying is a technique where a new function is created by binding arguments to an existing function in advance, and sending the arguments as the remaining arguments to the original function. The original function's return value is then returned

function getSize(src, callback){
  var img = new Image();
  img.onload = function(callback, img, event){
     callback(img.width, img.height);
  }.bind(null, callback, img); //not needed if you have closures
  img.src = src
}

What are the arguments to bind? null sets the this context. Our hypothetical curry method would not. Then, callback and img. These must be in the same order as the arguments to img.onload. This is acceptable every now and then, but not if you have to curry uphill in both directions. More importantly, it is acceptable if you have three arguments, but not if you have thirty.

Now, for the funny part: The global scope is technically a closure scope too. But, even if it wasn't, you still don't want to define your module's utility functions in the global scope (namespacing issues). Functions are stored in variables!

getSize = function(Image, src, callback){
  var img = new Image();
  img.onload = function(callback, img, event){
     callback(img.width, img.height);
  }.bind(null, callback, img); //not needed if you have closures
  img.src = src
}.bind(null, Image) //not needed if you have closures

Now, assume you want to transform the image coordinates for some reason, and that transformation is dependent on the source. Where do we need to add transform and src?

getSize = function(Image, transform, src, callback){ //here
  var img = new Image();
  img.onload = function(transform, src, callback, img, event){ //here
     var coord = transform(img.width, img.height, src); //used here
     callback(coord.x, coord.y);
  }.bind(null, transform, src, callback, img); //here
  img.src = src;
}.bind(null, transform, Image); //here

Can you spot the bug? Yep, the outer bind arguments are in the wrong order.

You can circumvent this by holding all parameters in a global object. Of course, you don't want to modify the caller's scope, so you define your own scope whenever you want to pass a few extra arguments. With a few good conventions, this may be reasonably bug-free:

var scope = {Image: Image, ...}

getSize = function(scope, src, callback){
  var img = new scope.Image();
  var scope = {scope: scope, src: src, callback: callback, img:img};
  img.onload = function(scope, event){
     var coord = scope.transform(scope.img.width, scope.img.height, scope.src);
     callback(coord.x, coord.y);
  }.bind(null, scope);
  img.src = src;
}.bind(null, scope)

Can you spot the bug now? scope.transform is undefined. We need scope.scope.transformThere's another one. Can you spot it too? Now this is getting ridiculous, even if we used one-letter variable for scope here. Maybe we could utilise the prototype chain:

var scope = {Image: Image, ...}

getSize = function(scope, src, callback){
  var img = new scope.Image();
  var scope = scope.Object.create(scope)
  scope.src = src;
  scope.callback = callback;
  scope.img = img;
  img.onload = function(scope, event){
     var coord = scope.transform(scope.img.width, scope.img.height, scope.src);
     callback(coord.x, coord.y);
  }.bind(null, scope);
  img.src = src;
}.bind(null, scope)

of course, we could define our local variables directly in the scope so that we don't have to declare them twice if some inner function might use it. Unfortunately, there's no such trick for the arguments. There is the arguments variable, but using it for our purpose is kinda messy (scope.getSizeArgs[0]; quick - which one is it?). However, so far, to circumvent the lack of closures we have:

for each scope, created a special scope variable, with the parent's scope as its prototype.

added all arguments to it

used it for all local variables that might be needed in an inner function.

Of course, this is getting ridiculous. Maybe if the language somehow knew that if we use an undeclared variable, it should search for it in the defining scope, and even create such scope object for us when needed so that the variables can outlive their defining functions? Well, it does.

function getSize(src, callback){
  var img = new Image();
  img.onload = function(event);
     console.log(event);
     var coords = transform(img.width, img.height);
     callback(coords.x, coords.y);
  }
  img.src = src;
}

Also, this explicit passing has another disadvantage: whenever you write to the scope, you always write to a local variable. You cannot modify a variable from an inner function. Sure, you could use one-element arrays or a special Reference<T> type, but this smells of a non-awesome language. With closures, you can do this directly. Do you actually need this?

var width = window.clientWidth;
window.addEventListener('resize', function(){width = window.clientWidth});
setInterval(function(){
  ...

You might say that sometimes you want the caller's scope as the alternative would be to have 30 arguments. But, the caller does not want you to see their local scope, and they don't want to have to avoid variable names you might one day consider significant. You can still pass objects around, but you don't call them scopes. Some may say "data transfer object"; I prefer the term "named arguments"

$.ajax({
  url: "http://www.example.com/cors-api/echo.json",
  dataType: "json",
  success: function(response){
    ..

Now, for the classic example of closure scoping, complete with an immediately invoked function expression to limit the scope of the static variable nextId:

var getId = (function(){
  var nextId = 0;
  return function getId(){ //named for clarity
    return nextId++;
  }
})()

getId() //0
getId() //1
getId() //2


问:
How do you name sprints in your projects?
Some Scrum software management tools give you this option to explicitly name your sprints.

Do you have a preferred way of naming your sprints or do you just use a simple scheme like 1, 2, 3, ...?

答:
After a while thinking about this, I came with the following convention:

```<code><year> CW <starting calendar week> - <ending calendar week>: <goal> (<version>)
</code>```

Version is optional.

So you end up with something like:

```<code>2013 CW 27-28: Improved reporting and dashboards (v1.5.1)
2013 CW 29-30: Redesigned gadgets (v1.5.2)
...
</code>```

This syntax answers the questions:

When was it done?

Why was it done?

Under what version was it released?

And also:

It is sortable

It is predictable

Allows for flexibility without sacrificing information

Body:
After a while thinking about this, I came with the following convention:

<year> CW <starting calendar week> - <ending calendar week>: <goal> (<version>)

Version is optional.

So you end up with something like:

2013 CW 27-28: Improved reporting and dashboards (v1.5.1)
2013 CW 29-30: Redesigned gadgets (v1.5.2)
...

This syntax answers the questions:

When was it done?

Why was it done?

Under what version was it released?

And also:

It is sortable

It is predictable

Allows for flexibility without sacrificing information


答:
I'd say that either a 200 or a 404 response code can be valid, depending on how you look at the situation.

The thing is that HTTP response codes are defined in the context of an server, which can deliver various resources based on their URL.  In this context, the meanings of 200 OK and 404 Not Found are perfectly unambiguous: the former says "here's the resource you asked for", while the latter says "sorry, I don't have any resource like that".

However, in your situation, you have an additional application layer between the HTTP server and the actual resources (trees) that are being requested.  The application occupies a sort of an intermediate space that is not well addressed in the HTTP spec.

From the webserver's viewpoint, the application looks kind of like a resource: it's typically a file on the server, identified by (a part of) the URL, just like other resources (e.g. static files) the server might serve.  On the other hand, it's a weird kind of resource, since it consists of executable code that dynamically determines the content, and indeed potentially even the status code, of the response, making it behave in some ways more like a mini-server.

In particular, in your example case, the webserver can locate the application just fine, but the application then fails to locate the subresource (tree) that has been requested.  Now, if you consider the application to be just an extension of the server, and the subitem (tree) to be the actual resource, then a 404 response is appropriate: the server has merely delegated the task of finding the actual resource to the application, which it turn has failed to do so.

On the other hand, if your viewpoint is that the application is the resource being requested, then obviously the webserver should return a 200 response; after all, the application was found and executed correctly.  Obviously, in this case, the application should actually return a valid response body in the expected format, indicating (using whatever higher-level protocol that format encodes) that no actual data matching the query was found.

Both of these viewpoints can make sense.  In most cases, at least for applications intended to be directly accessed over HTTP with an ordinary web browser, I would favor the former view: the user generally doesn't care about internal details like the difference between the server and the application, they just care about whether the data they wanted is there or not.

However, in the specific case of an application designed to communicate with other computer programs using a custom high-level API protocol, using HTTP only as a low-level transport layer, there's an argument to be made in favor of the latter view: for clients interfacing with such an application, all they really care about, at the HTTP level, is whether they managed to successfully contact the application or not.  Everything else is, in such cases, often more naturally communicated using the higher-level protocol.

In any case, regardless of which of the above views you prefer, there are a few details you should keep in mind.  One is that, in many cases, there may be a meaningful distinction between an (essentially) empty resource and a nonexistent one.

On the HTTP level, an empty resource would simply be indicated by a 200 response code and an empty response body, while a nonexistent resource would be indicated by a 404 response and a resource body explaining the absence of the resource.  In a higher-level API protocol, one would typically indicate a nonexistent resource by an error response, containing a suitable protocol-specific error code/message, while an empty response would simply be a normal response structure with no data items.

(Note that a resource need not be literally zero bytes long to be "empty" in the sense I mean above.  For example, a search result with no matching items would count as empty in the broad sense, as would an SQL query result with no rows or an XML document containing no actual data.)

Also, of course, if the application really does believe that the requested subresource should be there, but can't find it, then a third possible response code exists: 500 Internal Server Error.  Such a response makes sense if the existence of the resource is an assumed precondition for the application, such that its absence necessarily indicates an internal malfunction.

Finally, you should always keep in mind Postel's law:

"Be conservative in what you send, and liberal in what you receive."

Whether the server should respond in a particular situation with a 200 or a 404 response, that doesn't excuse you as the client implementor from handling either response appropriately and in the manner that maximizes robust interoperability.  Of course, what "appropriate" handling means in different situations can be argued, but it certainly shouldn't normally include crashing or otherwise "falling apart".


答:
The problem is that you want good readability of the source, but readability is in the eyes of the beholder.

I would suggest that we need better tools to solve this problem.  Nothing complex, mind you, we have had the technology to do it for more than 50 years.   Include a parser in the editor, and have the editor save the source in form of sexps (yes, just like lisp). Then the source is read, the editor unparses it into the syntactical and typographical (you know, spaces, tabs, commas), form the user prefers.

This way, you can type and read x = x || 10 and other programmers will read it as

```<code>if (0 == x) { x = 10;}
</code>```

emacs has all the pieces to do that easily.

Body:
The problem is that you want good readability of the source, but readability is in the eyes of the beholder.

I would suggest that we need better tools to solve this problem.  Nothing complex, mind you, we have had the technology to do it for more than 50 years.   Include a parser in the editor, and have the editor save the source in form of sexps (yes, just like lisp). Then the source is read, the editor unparses it into the syntactical and typographical (you know, spaces, tabs, commas), form the user prefers.

This way, you can type and read x = x || 10 and other programmers will read it as

if (0 == x) { x = 10;}

emacs has all the pieces to do that easily.


答:
From the sound of it, this is an API for internal use. This gives the edge of using whichever schema that gives the most benefit, regardless of whether it is by-the-book (specification) or not. This doesn't mean completely invent your own status codes, but it's OK to 'bend' the rules a little bit if it is beneficial.

I agree with your stand that you should get a status code that shows something went wrong. This is after all what status codes are for. Also you get the benefit of libraries that throw exceptions/etc. on non-200 status code so you do not have to check explicitly (Or you can write your own wrapper that does this).

I also agree with Andres F.'s point of view that 500 is appropriate since the tree should exist. In practice though, I like to split server errors into two categories.
Something unexpected went wrong and something that I can practically check for went wrong. This results in the following status codes,

200 - Everything is good

404 - Wrong url

409 - Something went wrong

500 - An unexpected error occurred on the server

In your particular case, you can check whether the tree exists or not on the server side and if it is not there then return a 409. It is an expected error (you know it can happen, you can check for it, etc.). 409 conflict is just my personal preference, a 5xx may also be appropriate as long as you can sit down and decide this with your team.

Categorizing codes like this helps you quicker identify the type of error, but it can have benefits beyond organization. Often with website errors you do not want the client to get unexpected errors as this can be a security concern and reveal vulnerabilities so you return a generic 500 "An error occurred." and log the full error on the server. But if an expected error occurs as a 409 you know that it would be safe to show the error to the client and you don't have to leave them in the dark as to what happened. This is just one practical use I can recount, but there are lots of possibilities.

This is a bit of a catch-22 because you are posting this due to not being able to agree with your co-workers, but it sounds like you guys are arguing more about semantics and who is politically correct. It really doesn't matter who is more proper, as long as you can come up with a system which most benefits the company.

On the other hand if this is a public API following the specifications as close as possible would be more important as to avoid confusion among the community.


答:
I would like to give one scene for closures：

```<code> function f1() {
      var n=999;

      setter=function() { n += 1 }
      function getter() {
           alert(n);
      }

      return f2;
 }
</code>```

In this function, the variable n becomes private and it has getter and setter methods (like Java).

Body:
I would like to give one scene for closures：

 function f1() {
      var n=999;

      setter=function() { n += 1 }
      function getter() {
           alert(n);
      }

      return f2;
 }

In this function, the variable n becomes private and it has getter and setter methods (like Java).


问:
Assessing Relative Maintainability
We (a contractor, actually) are implementing an off the shelf system to replace a legacy homegrown system for the core domain of the company (designing widgets). Unfortunately both systems will have to run concurrently for some time, as the product just isn't ready yet. Also, the decision was made to only migrate some of the widgets from the legacy system, based on date of last sale activity.

Later on a new requirement came down: certain people in the company, most of them outside of the widget development context, want to search all widgets. The search results screen has 3 pieces of data: a GUID, a human readable id that is searchable, and a brief description (may need to be searchable in the future). In the widget details, there will be multiple screens. These screens align very well along SOA / bounded context lines - a screen for marketing data, a screen for sales history, etc.

UML ahead! I am probably using the wrong kind of arrows here so please forgive me. The current solution - which is not in production yet - is something like the following:

Both systems will be queried and the controller will merge the results.

The new system has its own proprietary query language (we've alleviated this a bit with a LINQ provider). It also puts a lot of data on the wire. 15 search results typically run about 60k of unintelligible SOAP-wrapped xml. So I would prefer to avoid querying this system directly.

These two systems publish events to help us integrate with other systems, mainly an ERP system. One of these events contains all the data necessary for the search screen. I proposed the following alternative:

However I am being told that 'adding another database' will create more maintenance down the road. However, I believe this to be false, as I had to add a relatively simple feature that took several hours longer than anticipated because of this merging code.

I want to get a feel for which system is more maintainable in the long run. I personally have not had the burden of maintaining any large system. I want something more than my gut. Specifically I'd like to know if having more, specialized physical databases is more or less maintainable than having less larger physical databases.

答:
The 'search database' introduces an additional point of failure in the total system, and the failures introduced there might go unnoticed for a very long time.

The problem that I see is that the 'search database' might miss or otherwise fail to process a widget_event and get out of sync with the two sub-systems that it provides a front-end for. Such an inconsistency  will happen in the long run and won't be noticed until someone notices a particular widget being missing from the search results, while it is known to be present.

The 'search database' could work if you design it such that it periodically performs a full synchronization with the back-end systems, but then the added value diminishes to nearly zero, because you haven't skipped out on the queries to the back-end systems, while you still need to maintain an additional system.

Title: Assessing Relative Maintainability


问:
How to convert a Bazaar repository to GIT repository?
We have a large bazaar repository and we want to convert it to a git repository. The bazaar repository contains the folders of each of the interns. Any documentation/code prepared by interns is committed in their directory so there are a huge number of commits.

What steps should be performed to securely convert the bazaar repository to a git repository so that we do not lose any commit information.

We firstly need to create a backup of the existing bazaar repository and then convert it.

Edit: I followed this link: http://librelist.com/browser//cville/2010/2/9/migrate-repository-bzr-to-git/

It's working fine on my system with Ubuntu. But when I try to run it on the actual server it gives me EOF error and crashes

```<code>Starting export of 1036 revisions ...
fatal: EOF in data (1825 bytes remaining)
fast-import: dumping crash report to .git/fast_import_crash_11804
</code>```

Edit 2: I also tried it on a new CentOS system and received the following error

```<code>fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions
</code>```

答: Look at https://github.com/termie/git-bzr-ng. It's a little old but worked fine for me to fork a launchpad project in github. Simply import all bzr branches and push on your remote git server. I recommend using bzr2.2, it was buggy when I tried with newer verion of bzr.</p>


问:
Backend devs put down by user stories
I planned to slice in backend development into to the user stories vertically.
But a backend guy on our team started to complain that this makes their work invisible.

My answer was that

at the sprint planning and review meetings we discuss backend tasks
in front of stakeholders so it makes it visible, and

maintaining a high quality during the project will result a slower
startin pace than other teams, but we will have a stable velocity
during the project. And velocity is highly visible to stakeholders.

He still insist having stories like:
"As a developer
I need to have a domain layer
so I can encapsulate business logic."

How can I solve the issue before it pollutes the team?

The root of the issue is that our management systematically consider backend work as invisible and call backed devs miners, or other pejorative terms.

答:
The root of the issue is that our management systematically consider backend work as invisible and call backed devs miners, or other pejorative terms.

Indeed this is the problem. It's obvious you won't solve it with stories!

In general, one of the feature of agile development is transparency. This also means that it makes your organizational problems more manifest.

The standard agile solution to this problem is to adopt a more "vertical" or "full-stack" approach to development, where your backend devs take stories from top to bottom instead of simply working in their comfort zone  of the back end tier, and frontend devs likewise stretch towards the backend(*).

In other words: make everybody produce value for your end users.

(*) Note: not all stories need to have a front-end component or a back-end component. UI elements can be reshuffled without additional back-end work, and performance is a feature.

Title: Backend devs put down by user stories


答:
This seems to be a social problem, so it will need a social solution.

If (as I understand you) backend developers feel ignored and slighted, and feel that their work is not valued enough, then there is little that the development process can do to change this.

If I understand correctly, I looks like the devs feel that they should at least have their "own" user stories, so they can point to them and say "This is what we did, just us backend guys/gals". However, having stories sliced "horizontally" like this is a bad idea, and I agree with you to slice them vertically.

The best solution is probably to have a quiet talk with the developer(s) in question (individually or as a group), and address the underlying problem, which seems to be one of respect. At some point, this will probably need to escalate to management.

Title: Backend devs put down by user stories

Body:
I planned to slice in backend development into to the user stories vertically.
But a backend guy on our team started to complain that this makes their work invisible.

My answer was that

at the sprint planning and review meetings we discuss backend tasks
in front of stakeholders so it makes it visible, and

maintaining a high quality during the project will result a slower
startin pace than other teams, but we will have a stable velocity
during the project. And velocity is highly visible to stakeholders.

He still insist having stories like:
"As a developer
I need to have a domain layer
so I can encapsulate business logic."

How can I solve the issue before it pollutes the team?

The root of the issue is that our management systematically consider backend work as invisible and call backed devs miners, or other pejorative terms.


答:
The functional languages I know of can return multiple values easily through the use of tuples (in dynamically typed languages, you can even use lists). Tuples are also supported in other languages:

```<code>f :: Int -> (Int, Int)
f x = (x - 1, x + 1)

// Even C++ have tuples - see Boost.Graph for use
std::pair<int, int> f(int x) {
  return std::make_pair(x - 1, x + 1);
}
</code>```

In the example above, f is a function returning 2 ints.

Similarly, ML, Haskell, F#, etc., can also return data structures (pointers are too low-level for most languages). I have not heard of a modern GP language with such a restriction:

```<code>data MyValue = MyValue Int Int

g :: Int -> MyValue
g x = MyValue (x - 1, x + 1)
</code>```

Finally, out parameters can be emulated even in functional languages by IORef. There are several reasons why there is no native support for out variables in most languages:

Unclear semantics: Does the following function print 0, or 1? I know of languages that would print 0, and ones that would print 1. There are benefits to both of them (both in terms of performance, as well as matching the programmer's mental model):

```<code>int x;

int f(out int y) {
  x = 0;
  y = 1;
  printf("%d\n", x);
}
f(out x);
</code>```

Non-localized effects: As in the example above, you can find that you can have a long chain and the innermost function affects the global state. In general, it makes it harder to reason about what the requirements of the function are, and if the change is legal. Given that most modern paradigms try to either localize the effects (encapsulation in OOP) or eliminate the side-effections (functional programming), it conflicts with those paradigms.

Being redundant: If you have tuples, you have 99% of the functionality of out parameters and 100% of idiomatic use. If you add pointers to the mix you cover the remaining 1%.

I have trouble naming one language which could not return multiple values by using a tuple, class or out parameter (and in most cases 2 or more of those methods are allowed).

Title: Why do most programming languages only support returning a single value from a function?

Body:
Is there a reason why functions in most(?) programming languages are designed to support any number of input parameters but only one return value?

In most languages, it is possible to "work around" that limitation, e.g. by using out-parameters, returning pointers or by defining/returning structs/classes. But it seems strange that programming languages were not designed to support multiple return values in a more "natural" way.

Is there an explanation for this?

Body:
The functional languages I know of can return multiple values easily through the use of tuples (in dynamically typed languages, you can even use lists). Tuples are also supported in other languages:

f :: Int -> (Int, Int)
f x = (x - 1, x + 1)

// Even C++ have tuples - see Boost.Graph for use
std::pair<int, int> f(int x) {
  return std::make_pair(x - 1, x + 1);
}

In the example above, f is a function returning 2 ints.

Similarly, ML, Haskell, F#, etc., can also return data structures (pointers are too low-level for most languages). I have not heard of a modern GP language with such a restriction:

data MyValue = MyValue Int Int

g :: Int -> MyValue
g x = MyValue (x - 1, x + 1)

Finally, out parameters can be emulated even in functional languages by IORef. There are several reasons why there is no native support for out variables in most languages:

Unclear semantics: Does the following function print 0, or 1? I know of languages that would print 0, and ones that would print 1. There are benefits to both of them (both in terms of performance, as well as matching the programmer's mental model):

int x;

int f(out int y) {
  x = 0;
  y = 1;
  printf("%d\n", x);
}
f(out x);

Non-localized effects: As in the example above, you can find that you can have a long chain and the innermost function affects the global state. In general, it makes it harder to reason about what the requirements of the function are, and if the change is legal. Given that most modern paradigms try to either localize the effects (encapsulation in OOP) or eliminate the side-effections (functional programming), it conflicts with those paradigms.

Being redundant: If you have tuples, you have 99% of the functionality of out parameters and 100% of idiomatic use. If you add pointers to the mix you cover the remaining 1%.

I have trouble naming one language which could not return multiple values by using a tuple, class or out parameter (and in most cases 2 or more of those methods are allowed).


答:
A lot of the use cases where you would have used multiple return values in the past simply aren't necessary anymore with modern language features. Want to return an error code? Throw an exception or return an Either<T, Throwable>. Want to return an optional result? Return an Option<T>. Want to return one of several types? Return an Either<T1, T2> or a tagged union.

And even in the cases where you genuinely need to return multiple values, modern languages usually support tuples or some kind of data structure (list, array, dictionary) or objects as well as some form of destructuring bind or pattern matching, which makes packaging up your multiple values into a single value and then destructuring it again into multiple values trivial.

Here are a few examples of languages that do not support returning multiple values. I don't really see how adding support for multiple return values would make them significantly more expressive to offset the cost of a new language feature.

Ruby

def foo; return 1, 2, 3 end

one, two, three = foo

one
# => 1

three
# => 3
```

<h1>Python</h1>

<pre class="lang-py prettyprint-override"><code>def foo(): return 1, 2, 3

one, two, three = foo()

one
# >>> 1

three
# >>> 3
</code>```

Scala

def foo = (1, 2, 3)

val (one, two, three) = foo
// => one:   Int = 1
// => two:   Int = 2
// => three: Int = 3
```

<h1>Haskell</h1>

```let foo = (1, 2, 3)

let (one, two, three) = foo

one
-- > 1

three
-- > 3
```

<h1>Perl6</h1>

```sub foo { 1, 2, 3 }

my ($one, $two, $three) = foo

$one
# > 1

$three
# > 3
```

Body:
A lot of the use cases where you would have used multiple return values in the past simply aren't necessary anymore with modern language features. Want to return an error code? Throw an exception or return an Either<T, Throwable>. Want to return an optional result? Return an Option<T>. Want to return one of several types? Return an Either<T1, T2> or a tagged union.

And even in the cases where you genuinely need to return multiple values, modern languages usually support tuples or some kind of data structure (list, array, dictionary) or objects as well as some form of destructuring bind or pattern matching, which makes packaging up your multiple values into a single value and then destructuring it again into multiple values trivial.

Here are a few examples of languages that do not support returning multiple values. I don't really see how adding support for multiple return values would make them significantly more expressive to offset the cost of a new language feature.

Ruby

def foo; return 1, 2, 3 end

one, two, three = foo

one
# => 1

three
# => 3

Python

def foo(): return 1, 2, 3

one, two, three = foo()

one
# >>> 1

three
# >>> 3

Scala

def foo = (1, 2, 3)

val (one, two, three) = foo
// => one:   Int = 1
// => two:   Int = 2
// => three: Int = 3

Haskell

let foo = (1, 2, 3)

let (one, two, three) = foo

one
-- > 1

three
-- > 3

Perl6

sub foo { 1, 2, 3 }

my ($one, $two, $three) = foo

$one
# > 1

$three
# > 3


问:
Why is TDD not working here?
I want to write a class A that has a method calculate(<params>). That method should calculate a value using database data. So I wrote a class Test_A for unit testing (TDD). The database access is done using another class which I have mocked with a class, let's call it Accessor_Mockup.

Now, the TDD cycle requires me to add a test that fails and make the simplest changes to A so that the test passes. So I add data to Accessor_Mockup and call A.calculate with appropriate parameters.

But why should A use the accessor class at all? It would be simpler (!) if the class just "knows" the values it could retrieve from the database. For every test I write I could introduce such a new value (or an if-branch or whatever).

But wait ... TDD is more. There is the refactoring part. I could refactor class A using the DB accessor. But I could refactor it in any other way as well (e.g. introducing new classes that encapsulate the data). So, again: How do I write tests that force A to use the database (and nothing else)?

答:
But why should A use the accessor class at all?

Well, why should you use the database at all? Because the database can change.

Test that calculate(A) returns the expected value, then change the accessor and verify that calculate(A) returns the new expected value.

It's test driven design. You know what you want (a database), then you add tests that drives your coding in the direction of that ideal.

And for the other part, where you just add more and more if-statements to cover all parameters you test. Yes, that is what you should do: until you think that adding another if-statement is more complicated than actually doing the (least amount of) work you actually need to.

I'd say typical programmer should hit that limit before writing four if-statements.

The basic idea with "simplest" is to never get stuck on any single unit-test: if you know the end result you want, return that; think of another result you want and add that test. Repeat. Sooner or later you'll figure out a more efficient/simple way to do it.

Edit: How do I write tests that force A to use the database (and nothing else)?

The flippant answer is, you can't. From the perspective of the test, the method is a black box: you give it input and verify the output; whether it gets that output by querying the database or scrying is not something the test is concerned with.

In practice though: the database, or mock-database is just another input. Vary the input and verify the output; repeat until you can think of no more failing tests. It should not be long before the simplest thing you can do is actually query the (mock-)database.

Title: Why is TDD not working here?


问:
Best way for an external (remote) graphics designer to style ASP.NET MVC 4 app?
My customer has his own graphics designer he wants to use to style his web application we're building in ASP.NET MVC 4.

Our solution is in Bitbucket, but if he can't run it what choices do we have? I doubt he uses Visual Studio 2012.

One idea is for us to publish to our solution to a file system, send it to him, have him create a local IIS website on his machine (assuming he isn't using a Mac). Mocking data or pointing to a test SQL in Azure isn't a problem.  Then he can make changes to .css and .cshtml files. Will this even work?

The point is that he needs to be able to test his changes. I know he can modify the views and just check-in. But he needs to deliver a working design. So it seems inefficient.

The graphics designer will have access to our test site so he can see how it works,  what data we have and fields. Another idea is for him to build a static mock site using just HTML/CSS. Later I'd integrate his styles into customer's solution, split his html into partial views which we use and add Razor syntax. Again, we'd like to leverage graphics designer for all of this.

Is there a best practice documented around this subject? How do other teams deal with this situation?

答:
The way we have done it in the past is have the designer just create static HTML pages and separate CSS files with their own mocked data. We then took the HTML/CSS and added it to the real project our selves.

Once we added to the main project and tested the designs with the real data, we would then go back to the designer with any tweaks that needed doing. We would then work much more closely with them to implement the tweaks and add the finishing polish. Would would have the odd day here and there where a dev would just work with the designer to implement the final tweaks straight away to get instant feedback and a fast turn around.

We did this because the designer had no experience with visual studio or razor, we were also using javascript templating in some areas too.


问:
What syntax element do you hate most in a programming language you use frequently?
No matter how much you love a programming language, there are always a few details in it that aren’t quite as nice as they could be.

In this question, I would like to specifically focus on syntax elements. In a programming language that you use frequently (perhaps your favourite programming language, or perhaps the one you are forced to use at work), which syntax element do you find most unreadable, unclear, inconvenient or unpleasant?

答: Verbosity in Java anonymous classes. Will hopefully be fixed soon.</p>


答:
Rather than dumb down the code, why not improve the quality of the team? Training, coaching, education, and improved hiring practices can do a lot towards ensuring continuous improvement.

Statism, code rot, refusing to improve and innovate because someone doesn't want to work on self-improvement only cause trouble down the line, and sooner rather than later.

Of course in the specific case you show, you're just trying to be clever and deliberately writing obfuscated code, which is never a good idea. Code should first and foremost be readable, readily understandable, not written to show how clever you are at creating something in the least statements possible (special cases excepted, like where more statements would lead to unacceptably poor performance, in which case copious comments are called for).


问:
Multiple Object Instantiation
I am trying to get my head around object oriented programming as it pertains to web development (more specifically PHP).

I understand inheritance and abstraction etc, and know all the "buzz-words" like encapsulation and single purpose and why I should be doing all this.

But my knowledge is falling short with actually creating objects that relate to the data I have in my database, creating a single object that a representative of a single entity makes sense, but what are the best practises when creating 100, 1,000 or 10,000 objects of the same type.

for instance, when trying to display a list of the items, ideally I would like to be consistent with the objects I use, but where exactly should I run the query/get the data to populate the object(s) as running 10,000 queries seems wasteful.

As an example, say I have a database of cats, and I want a list of all black cats, do I need to set up a FactoryObject which grabs the data needed for each cat from my database, then passes that data into each individual CatObject and returns the results in a array/object - or should I pass each CatObject it's identifier and let it populate itself in a separate query.

答:
Creating 100, 1 000 or 10 000 similar objects is not itself an issue (unless the object itself is huge). If you find yourself creating thousands and thousands of objects, ask yourself if you really need to.

If you're loading Cat objects, one per cat stored in the database, do you need to load all the 500 000 cats, for example? Why? You can't display them on the screen: it wouldn't be particularly useful. If you need to process them, is preloading everything the best way to do?

When you need a list of black cats, you don't load every cat available. What you do is to limit, at database level (for example with a where [color] = @color), the results you get, and you build objects corresponding to black cats only.

Indeed, this can be done in a factory which will contain a method which takes a specific color and returns the cats of this color.

Doing a query per cat, on the other hand, is a terrible approach. The fewer queries you do, the better. That's why your suggestion to use a factory was a good idea.

Title: Multiple Object Instantiation


问:
If you had to go back and re-learn your skill set, how would you do it?
My younger brother is looking to start programming. He's 14, and technically-inclined, but no real experience programming. He's looking to me for guidance, and I don't feel as if my experience is enough, so I figured I'd ask here.

He's more interested in web programming, but also has an interest in desktop/mobile/server applications.

What would be a good learning path for him to take? I'm going to buy him a bunch of books for Christmas to get him started; the question is, what should he learn, and in which order?

The way I see it, he needs to learn theory and code. I'd like to start him off with Python or Ruby or PHP. If he wants to get in to web, he's also going to need to learn HTML, CSS, Javascript, etc.

Out of those three domains (Languages, Theory, Markup/Etc.), what is the best order do you think to learn in? Also, am I missing anything?

Thanks!

答:
c

c++

python upto basic programming

then HTML

css

javascript

do hard with css its very important and javascript upto minimum validation level

 then srart python for html and getting url

then framework if all stage are ok

levels are are follow

basic level with command prompt to understand basic anatomy

application level

mouse graphic level

web level

designning level

database level

dont forget to modularise things when you teach , undesrtand he will not understand javascript untill he know c/c++ or python etc

once he know basic programming he can do HTML easily

once he know html he llike css to

 but stop and try more with css so new ideas will generate and he feel he need help to get started with project then he will try to learn javascript and python with database for completion of project .

Added on 04/07/2013

at the age of 14 when you want to try u r hands on programming first you need to understand what resource i needed to get completed the task or project or basic guidelines ,
well as i mensioned in my post learn basic programming first ,
it will help you to understand how the programs or software works with looping and condition , when next you think i understand all things but i dont klnow how to access mouse or do something when i click somewhere , you will try some libraries like graphics and mouse , so you understand how this works , next question will come to ur mind how to place my buttons and add events so they can interact with my code , so you will like to learn event programming then when you complete this stage , next question will arise i make very big code and i dont know how to call function its bit complicated , then you will try modularization , object and classes for application ,

after that you will think i know how to build basic application but i want to make application for database, then Database comes to mind , you like to learn but problem is that you feel its hard to get connected with code so you will work on database command prompt ,

its a programmic approach believe , i do and learn from same way and my basics arevery clear so i can understand how routines or program is work,

once you understand and much confident about you can make application for desktop try same skills for HTML

when you try for html , you will feel its much more easy than what you learn prevoiusly , just because you spent lot of time on basics .

in html , understand structure and how code works , once you know this things , you loike to give validation and database connectivity for application ,
give try and you get succed in a day , you can easily builkd form place buttons and validate with the halp of javascript,
then you will ask a question to yourself i made everything but what about look it dosnt match with what i see on internet , so try hard with css,
i am very sure if you dedicately try for css with best IDE or dreamweaver you will be in love wit hTML/css .

its enough for you to make a simple application or web with HTML,

at certain point you will ask another question to yourself how to make it dynamic when you know hyperlinks work well , then what does dynamic , lets think about database , that you learn prevoiusly ,

yes thats my point , show records , insert record , delete record and play with database locally with javascript and server side programming,
then other concept will come to your mind automatically , to create user , validation , session , user history, internationalization   etc

and you will go ahead without guidance because your base is clear and you know what to do and what resource you needed to complete the task

thats all the stages .
basics are very important and right steps also .
once you know basics you can easily learn another language or migrate from one language to another language

thanks for reading

Added on 04/07/2013

progarme is nothing but a set of instruction and routines ,
eg our daily routine ,
we wake up , take bath , lunch , work , dinner, go to sleep .

but if we mis any one of the task we feel unconfortable thats is if day is sunday when you have no work or on vacation the condition is change and daily routines also , so you get match with other things , thats what like programming approach , learn from practical not from what books tell you , books are good for reference but understand natural way how we react , work with the help of if-else statement , eg: suppose we have two work and both are very important , but we can do only one at a time , you pick 1st one and complete then you can go to home , if you pick second then you need to work next 5 hours , else if you complete both work , you get 1 day leave ,thats about programming approach


问:
Is it good practice to require a trailing forward slash in directory names?
I want to ask the user of my bash script to pass a directory path as argument. Which one of the following is a good programming practice?

Require that the user enter a trailing / (forward slash)

Require that a user doesn't enter a trailing / (forward slash)

答:
Requiring that the directory must not have a trailing slash would be extremely annoying for interactive use on the console: auto-completion with TAB automatically adds a trailing slash for directories.

So you certainly need to allow that directories are specified with trailing slash.


问:
If my team has low skill, should I lower the skill of my code?
For example, there is a common snippet in JS to get a default value:

```<code>function f(x) {
    x = x || 'default_value';
}
</code>```

This kind of snippet is not easily understood by all the members of my team, their JS level being low.

Should I not use this trick then? It makes the code less readable by peers, but more readable than the following according to any JS dev:

```<code>function f(x) {
    if (!x) {
        x = 'default_value';
    }
}
</code>```

Sure, if I use this trick and a colleague sees it, then they can learn something. But the case is often that they see this as "trying to be clever".

So, should I lower the level of my code if my teammates have a lower level than me?

答:
There seems to be a huge aversion to creating a function in JS. This aversion
causes people try to be clever and use ridiculous tricks just to keep
stuff in one line like a function call would have been. Of course the function
name in a call acts as extra documentation too. We cannot attach a comment
to a tricky expression because then it would defeat the point of doing it
so we just call it "js idiom" and suddenly it is understandable.

Javascript is extremely accessible, most people don't eat specifications for breakfast like
we do. So they will never understand what the hidden assumptions and edge cases
of an idiom is.

```<code>x = x || 'default_value';
</code>```

The average joe will either not understand this or has memorized that it is the idiom for default value. Both are harmful, in fact the latter is even more harmful. He
will not understand the assumptions and edge cases here. He will not care to read the specification
and understand it ever.

When I look at that code I see "if it's null or undefined, then set it to this default value. Although
it will also implicitly treat +0, -0, NaN, false, and "" as not suitable values. I will have to
remember that 3 months from now when that needs to change. I will probably forget it.".

The implicit assumption is extremely likely to cause a bug in the future and when your codebase is full of tricks like
this then there is no chance you are keeping them all in your head whenever you are thinking about what
a modification will affect. And this is for the "JS pro", the average joe would have written
the bug even if the requirements were to accept a falsy value to begin with.

Your new snippet has more familiar syntax but still has the above problem.

You can go with:

```<code>function f(x) {
    x = valueOrDefault(x, "default_value");
}
</code>```

Now you can have very complex logic to handle the edge cases and the client code still looks beautiful and readable.

Now, how do you differentiate between advanced language feature like passing a function as argument or a clever trick
like || "default"?

Clever tricks are always operating under some hidden assumptions that could be ignored when the code was initially created. I will
never have to modify an IIFE to something else because a requirement changed, it will always be there. Maybe in 2020 when I can use
actual modules but yeah.

| 0 or the cargo cult version ~~num used for flooring assumes positive and 32-bit signed integer bounds.

|| "default" assumes all falsy values are same as not passing an argument at all.

And so on.

Body:
There seems to be a huge aversion to creating a function in JS. This aversion
causes people try to be clever and use ridiculous tricks just to keep
stuff in one line like a function call would have been. Of course the function
name in a call acts as extra documentation too. We cannot attach a comment
to a tricky expression because then it would defeat the point of doing it
so we just call it "js idiom" and suddenly it is understandable.

Javascript is extremely accessible, most people don't eat specifications for breakfast like
we do. So they will never understand what the hidden assumptions and edge cases
of an idiom is.

x = x || 'default_value';

The average joe will either not understand this or has memorized that it is the idiom for default value. Both are harmful, in fact the latter is even more harmful. He
will not understand the assumptions and edge cases here. He will not care to read the specification
and understand it ever.

When I look at that code I see "if it's null or undefined, then set it to this default value. Although
it will also implicitly treat +0, -0, NaN, false, and "" as not suitable values. I will have to
remember that 3 months from now when that needs to change. I will probably forget it.".

The implicit assumption is extremely likely to cause a bug in the future and when your codebase is full of tricks like
this then there is no chance you are keeping them all in your head whenever you are thinking about what
a modification will affect. And this is for the "JS pro", the average joe would have written
the bug even if the requirements were to accept a falsy value to begin with.

Your new snippet has more familiar syntax but still has the above problem.

You can go with:

function f(x) {
    x = valueOrDefault(x, "default_value");
}

Now you can have very complex logic to handle the edge cases and the client code still looks beautiful and readable.

Now, how do you differentiate between advanced language feature like passing a function as argument or a clever trick
like || "default"?

Clever tricks are always operating under some hidden assumptions that could be ignored when the code was initially created. I will
never have to modify an IIFE to something else because a requirement changed, it will always be there. Maybe in 2020 when I can use
actual modules but yeah.

| 0 or the cargo cult version ~~num used for flooring assumes positive and 32-bit signed integer bounds.

|| "default" assumes all falsy values are same as not passing an argument at all.

And so on.


问:
How is a "Software Developer" different from a "Software Consultant"? What makes a consultant?
I have seen a lot of people claiming themselves to be a "software consultant". These consultants do what a normal software developer does, write code, estimate tasks, fix bugs and attend meetings etc. The only difference being the financials, consultants end up earning more. Then how is a software developer different from a "consultant"?

In addition to the main question, I would like to know how can a software developer become a consultant? Are there any specific guidelines for a consultant? Do they need to amass certifications and write up research papers? Please do not confuse the software consultant with a management consultant. Software consultants I have seen are not managers.

答:
I guess, you'd have to be a kickass software developer or atleast a good one, to give other people advice on how to develop software.

Simply put, a S/W Consultant is  a S/W Developer with proven experience.

Just look back in time in your own life - when you started driving, or reached the age to get a driver's license, did you ask stuff about driving and license application  from someone younger than you or someone older who had a license and knew driving ?

Also, consultants often do the job for you - the developing part, besides other stuff that is around the creation of a software product, from start to finish.
Atleast the big organizations do, they handle every aspect of the product creation for you. You just need to tell them what you want, how you want it done, what the critical stuff is, deadlines, documentation, etc etc.

TCS comes to mind. Tata Consultancy Services. Don't be misled, they're one of India's very bright IT services companies, a fork of the Tata group of industries, under Ratan Tata.

TCS' notable works - digitazation of the passport application system, UID, and other major govt works.


问:
When to decide to introduce interfaces (pure abstract base classes) in C++?
Assume that you are developing a functionality and are 90% sure that the implementation class will stay alone. If I was in this position in Java I would probably not use the interface right now to keep the things simple. In Java it is easy to refactor the code and extract the interface later.

In C++ the refactoring is not always so easy. It may require replacing values with smart pointers (because of the introduction of polymorphism) and other non-trivial tasks.

On the other hand I don't much like the idea of introducing virtual calls when I am 90% sure they won't be needed. After all speed is one of the reasons to prefer C++ over simpler languages.

答:
Interfaces are a design decision, so they are much more important to get right than implementation or convenience. Your design should drive the other concerns, not the other way around. Get the design right, decide whether to introduce interfaces, then worry about what that means in your language, C++ or otherwise.

[refactoring] may require replacing values with smart pointers

Smart pointers should be a drop-in replacement; even if this is not possible and you have to use raw pointers, you should be using idiomatic C++ where your object lifetimes are well-managed, i.e. it's obvious where you need to put deletes.

On the other hand I don't much like the idea of introducing virtual calls when I am 90% sure they won't be needed.

Are you sure you need to worry about virtual call overhead? Have you profiled your code? Is the virtual call on your hot path? Are you sure you've exhausted other options for improving speed (that are much more effective), such as algorithms, data structures, cache-friendliness, fitting things into L1?


答:
This example is pretty similar to gravityplusplus'. Asynchronous code is the most common case, as Mason and Jan pointed out; but it's also useful for localized modules (module meaning "a block of code that does its own individual task). Here's some code all in the same scope (meaning, this is how NOT to do it).

```<code>counter = 0;

function incrementCounter() {
    counter += 1;
    return counter;
}

// Define Ryu's attack functions here
function lightPunch() {
    //TODO
}
function counter() {
    //TODO
}

function getCounterValue() {
    return counter;
}
</code>```

What is getCounterValue() going to return? I'm not even sure; I think it's going to be the function that I declared, not the number. If these were seperated into closures in some way (and there are several ways to do so; gravity listed one good example) then there's no chance of variable names getting mixed up. And in a large, corporate project with pages consisting of 50+ JS files, there are going to be LOTS of variable names.

Body:
This example is pretty similar to gravityplusplus'. Asynchronous code is the most common case, as Mason and Jan pointed out; but it's also useful for localized modules (module meaning "a block of code that does its own individual task). Here's some code all in the same scope (meaning, this is how NOT to do it).

counter = 0;

function incrementCounter() {
    counter += 1;
    return counter;
}

// Define Ryu's attack functions here
function lightPunch() {
    //TODO
}
function counter() {
    //TODO
}

function getCounterValue() {
    return counter;
}

What is getCounterValue() going to return? I'm not even sure; I think it's going to be the function that I declared, not the number. If these were seperated into closures in some way (and there are several ways to do so; gravity listed one good example) then there's no chance of variable names getting mixed up. And in a large, corporate project with pages consisting of 50+ JS files, there are going to be LOTS of variable names.


问:
How can I quickly weed out "copy & paste" coders?
I need a way to filter out resumes of folks who just copy-and-paste code then hope it works, and check it in if it does.  All this happens without having an understanding (or care) to understand the rest of the code in the system.

Sure I know that copying and pasting code is part of learning a new object, control, etc... but how can one tell if that accounts for 70% (or more) of their development career?

I've come across some senior level guys perhaps whose skills are so outdated or irrelevant for the project, that all they do is google, copy-then-paste some code without thinking about the solution as a whole.  As a result we have a mismash of JSON, AJAX, callbacks, ASMX, WCF and postbacks in the same project.  It is clear there is no consistency or logic behind where each technology is being used.

In the worst case, this type of developer creates security issues and vectors for attack.

Question

How would you recommend I filter out people who have a poor programming background?  Can I do it at the resume level?  If not, how do I do this during the interview.

答:
Simple

(1) Lock them inside a room + Free Oxygen.

(2) Give them a PC with Internet connection + IDE of choice + access to Food.

(3) Have wireshark or similar method of logging all inbound and outbound traffic.

(4) Give him a medium assignment.

(5) Examine all HTTP traffic, post assignment completion.

(6) If subject has copied large chunks of source code, terminate Subject.....

Edit:

As makerofthings7 as pointed out, in practical terms one could do a video capture (screen capture).