答:
I caution you against applying too rigid a hierarchy to these terms.  We tried to do that in my previous job twice.  Both attempts were different and both times we found we had unnecessarily limited ourselves.  The only constant was the definition of a User Story (archived).

From a planning perspective, a story is the basic building block of a project.  The larger terms (epic, feature, etc.) are effectively just tags.  Tags are an easy way to allow a story to exist as part of multiple Epics and multiple Features at the same time.  It's not worth the mental effort to be more strict than that.

Tags work for Stack Exchange and they can work for you too.

Title: Relationship between user story, feature, and epic?

Body:
As someone who's still new to agile, I'm not sure I completely understand the relationship or difference between user story, feature, and epic.

According to this question, a feature is a collection of stories.  One of the answers suggests that a feature is actually an epic. So are features and epics considered the same thing, that is basically a collection of related user stories?

Our project manager insists that there's a hierarchical structure:

Epic -> Features -> User stories

And that basically all user stories must fall within this structure.  Therefore all user stories must fall under an umbrella feature and all features must fall under an epic.

To me, that sounds awkward.  Can someone please clarify how user stories, features, and epics are related?  Or is there an article that clearly outlines the differences?


问:
How to avoid huge functions with made up of enums and if-else or switch case when dealing with server response in iOS?
in my application,
I have a request type associated with variety of API calls I make to the REST server.
when the response from server comes in the same delegate method for web engine's response,

I have to check the API type in the request object passed as  a parameter to the delegate method and then take the corresponding action.
The problem is there are around 10-12 different API request types.
So the switch case that checks the different enums associated with API Types, takes action based on it.

How to get rid of this switch 'tower' ?

答:
In Objective-C you can build selectors at runtime. This lets you "stringly-type" method dispatch, which removes a lot of conditional code (though replaces it with something that has its own problems). An example that shows how this might work:

```<code>- (void)sendHTTPRequest: (NSString *)request
{
    NSString *requestMethod = [NSString stringWithFormat: "send%@Request", [request upperCaseString]];
    SEL requestSelector = NSSelectorFromString(requestMethod);
    if ([self respondsToSelector: requestSelector])
      [self performSelector: requestSelector];
    else
      [self reportUnknownRequest: request];
}

- (void)sendGETRequest { ... }
- (void)sendPOSTRequest { ... }
- (void)sendDELETERequest { ...}
- (void)reportUnknownRequest: (NSString *)request { ... }
</code>```

I use this approach for building parsers, for avoiding large switch statements, and for behaviour that depends on the class of a parameter in cases where putting the behaviour on the parameter classes would not be appropriate.

ContentLicense: CC BY-SA 3.0

Body:
In Objective-C you can build selectors at runtime. This lets you "stringly-type" method dispatch, which removes a lot of conditional code (though replaces it with something that has its own problems). An example that shows how this might work:

- (void)sendHTTPRequest: (NSString *)request
{
    NSString *requestMethod = [NSString stringWithFormat: "send%@Request", [request upperCaseString]];
    SEL requestSelector = NSSelectorFromString(requestMethod);
    if ([self respondsToSelector: requestSelector])
      [self performSelector: requestSelector];
    else
      [self reportUnknownRequest: request];
}

- (void)sendGETRequest { ... }
- (void)sendPOSTRequest { ... }
- (void)sendDELETERequest { ...}
- (void)reportUnknownRequest: (NSString *)request { ... }

I use this approach for building parsers, for avoiding large switch statements, and for behaviour that depends on the class of a parameter in cases where putting the behaviour on the parameter classes would not be appropriate.


问:
What are the Advantages of a "Combined" Getter/Setter VS Individual Methods?
This is what I call a "combined" getter/setter method (from jQuery):

```<code>var foo = $("<div>This is my HTML</div>"),
    myText;

myText = foo.text(); // myHTML now equals "This is my HTML" (Getter)
foo.text("This is a new value"); // The text now equals "This is a new value")
</code>```

This is the same logic with separate (theoretical) methods:

```<code>var foo = $("<div>This is my HTML</div>"),
    myText;

myText = foo.getText(); // myHTML now equals "This is my HTML" (Getter)
foo.setText("This is a new value"); // The text now equals "This is a new value")
</code>```

My Question:

When designing a library like jQuery, why would you decide to go the first route and not the second? Isn't the second approach clearer and easier to understand at a glance?

答:
Purely speculating here, but I would be inclined to believe the jQuery developers who used a lot of the functional styling in structuring jQuery clearly have a leaning towards the functional paradigm.

Given that, in the functional paradigm there is a strong culture of reducing redundancy, and it could be argued that the second approach has unnecessary redundancy. The first approach may not be clear to someone used to all the common imperative languages, but it is unarguably doing more with less by having only one method instead of two. This may be dangerous, but it is a common tool in the functional paradigm and something one quickly gets used to.

Practice in the functional paradigm and you quickly get over that desire towards ceremony and learn to appreciate the ability to do more with less. Though this is recognizably a subjective choice based on preference in the same way many people have preferences regarding whitespace management. In this way I'm not saying one way is better, rather that they are things people get used to, which is likely why jQuery has the approach it does.

This would be why I believe the jQuery developers did this and is in the general why someone might take this approach.


答:
The form

```<code>foo.text("This is a new value");
</code>```

can imply a number of things.  Most commonly, it suggests a foo object, with a method called text accepting a string, that does something.  There's no implication that this is a property at all.

In many languages, this can be consider an abbreviated form of

```<code>var result = foo.text("This is a new value");
</code>```

where the result is discarded.  So this approach is just too ambiguous to be an effective way to set a property (from a code readability point of view).

Title: What are the Advantages of a "Combined" Getter/Setter VS Individual Methods?

Body:
This is what I call a "combined" getter/setter method (from jQuery):

```<code>var foo = $("<div>This is my HTML</div>"),
    myText;

myText = foo.text(); // myHTML now equals "This is my HTML" (Getter)
foo.text("This is a new value"); // The text now equals "This is a new value")
</code>```

This is the same logic with separate (theoretical) methods:

```<code>var foo = $("<div>This is my HTML</div>"),
    myText;

myText = foo.getText(); // myHTML now equals "This is my HTML" (Getter)
foo.setText("This is a new value"); // The text now equals "This is a new value")
</code>```

My Question:

When designing a library like jQuery, why would you decide to go the first route and not the second? Isn't the second approach clearer and easier to understand at a glance?

Body:
The form

foo.text("This is a new value");

can imply a number of things.  Most commonly, it suggests a foo object, with a method called text accepting a string, that does something.  There's no implication that this is a property at all.

In many languages, this can be consider an abbreviated form of

var result = foo.text("This is a new value");

where the result is discarded.  So this approach is just too ambiguous to be an effective way to set a property (from a code readability point of view).


问:
Effectiveness of FizzBuzz and Beyond
As part of the interview process we initially ask the candidates to do 'FizzBuzz' nowadays the percentage of candidates that can correctly answer FizzBuzz has increased dramatically - this may be due to it's popularity on the web.

About a year ago, as a second question we began asking a question very similar to the original FizzBuzz. The question was designed to be as simple as the original FizzBuzz, and to also assess a particular ability of the candidate, specifically the ability to order and prioritize in a meaningful and logical manner a set of "business rules" that have been provided in some arbitrary order. The wording of the question initially seems slightly ambiguous, which may make it difficult for non-native English speakers, but if thought through can be correctly resolved - Also it gives the candidate the opportunity to ask questions for clarification, which is always a good thing.

We find this a very important skill to have as a developer, as software development is typically based on functional requirements that are derived in no particular order over time, that may place constraints and conditions upon other areas of the software without explicitly indicating and it is the job of the astute developer to at the very least investigate potential issues and conflicts with regards to the implementation.

What we found was that a little over 65% of the candidates (sample size of 38) that passed FizzBuzz completely failed FizzBuzz v2.0 Normally these candidates would be detected later on in the process, but it seems to be a nice way to detect them early on.

My question is not about whether or not FizzBuzz is outdated, but rather what factors could be contributing to such a high number of candidates failing the FizzBuzz v2 question.

Is the question too ambiguous?

Does the stress of an interview environment decrease ones ability to think critically to the point of not being able to complete such a trivial task?

Question:

Write a routine in your favourite programming language that will take a list of strings as input, and for each string in the list will do one of the following:

Print only Fizz if the string contains the letter A

Print only Buzz if the string contains the letter B

Print only BuzzBuzz if the string contains both A and B

Print only FizzFizz if the string does not contain both A and B

Print only FizzBuzz if the string contains only one A and only one B

Some typical questions asked by candidates are:

Should it be case sensitive?

Does "contains A and B" mean A should come before B

What should be printed if none of the points are met?

What should happen if more than one condition can be met?

We found that the overwhelming majority of candidates that successfully completed the question, didn't ask anything at all they just did it like they did FizzBuzz.

答:
We found that the overwhelming majority of candidates that successfully completed the question, didn't ask anything at all they just did it like they did FizzBuzz.

I've seen interview processes that encourage programmers to think out loud and ask questions to see their thinking process. I like this process better.

I read through this fizzbuzz v2.0 and I would asked about #3 and #5 requirement there. I don't know about other people but I find in engineering I don't want any ambiguity so I ask question. Because later down the line (coded and all), I don't want to find out I had to make an assumption and it was wrong.

Title: Effectiveness of FizzBuzz and Beyond


答:
It's a bit speculative, but here is my shot at it.

jQuery embrace fully the functional nature of javascript. That is what make it so awesome, but it can leave a lot of developer scratching their head when they come from of more purely OO language such as java. It seem to break all convention and good practice.

Functional langage tend to put the emphasis on a declarative syntax. It tend to read like statement of a fact rather than like commands. Example

```<code>var eligible = customers.where(c => c.age > 30);
</code>```

which can be read as "the eligible customer are the customers whose age are over 30". By constrast, the imperative language read like a sequence of command

```<code>for (customer in customers)
    if (customer.age > 30)
        eligible.add(customer)
</code>```

That can be read as "Check each customer, and if their age is over 30, add them to the eligible collection"

Adding a a set and a get operation would make jQuery feel like an imperative library. You can constrast the way to read the following statements

```<code>// The element tag have an html of <p>hello</p>
$("#element").html("<p>hello</p>");

// content represent the html of the element tag
var content = $("#element").html();

//Imperative style

// Set the element tag to an inner html of <p>hello</p>
$("#element").setHtml("<p>hello</p>");

//Get the html of #element, and put it in the content variable
var content = $("#element").getHtml();
</code>```

By keeping actions verb out of the jQuery api, they made it feel like a declarative API. It give a consistent, functional feel to the library. That is why I think they overloaded the keywords.

Body:
It's a bit speculative, but here is my shot at it.

jQuery embrace fully the functional nature of javascript. That is what make it so awesome, but it can leave a lot of developer scratching their head when they come from of more purely OO language such as java. It seem to break all convention and good practice.

Functional langage tend to put the emphasis on a declarative syntax. It tend to read like statement of a fact rather than like commands. Example

var eligible = customers.where(c => c.age > 30);

which can be read as "the eligible customer are the customers whose age are over 30". By constrast, the imperative language read like a sequence of command

for (customer in customers)
    if (customer.age > 30)
        eligible.add(customer)

That can be read as "Check each customer, and if their age is over 30, add them to the eligible collection"

Adding a a set and a get operation would make jQuery feel like an imperative library. You can constrast the way to read the following statements

// The element tag have an html of <p>hello</p>
$("#element").html("<p>hello</p>");

// content represent the html of the element tag
var content = $("#element").html();

//Imperative style

// Set the element tag to an inner html of <p>hello</p>
$("#element").setHtml("<p>hello</p>");

//Get the html of #element, and put it in the content variable
var content = $("#element").getHtml();

By keeping actions verb out of the jQuery api, they made it feel like a declarative API. It give a consistent, functional feel to the library. That is why I think they overloaded the keywords.


答:
It makes it behave somewhat more like properties, which were only recently introduced to JavaScript, and therefore aren't widely used yet, especially in libraries like jQuery that are meant to help abstract away browser incompatibilities.

If you have ever looked at a class definition full of such properties, the "set" and "get" prefixes look superfluous, because the addition of the value parameter already tells you it's a setter.  Martin Fowler makes a good point about getters that require a parameter, but even then, within that context the additional value parameter clearly denotes a setter, as well as the fact that a setter rarely appears on the right hand side of an assignment.  And when you're writing code, you have to look at the documentation for the library anyway.

Since you only asked for advantages, I won't cover the disadvantages.


问:
Name for sanitizing at the right time?
Recently we had an issue on our site where someone attempted SQL injection via a cookie (we'll call it lastID).  NOC was in a frenzy and angry about how the cookie as an attack vector could be ignored.  They had a developer create a class for managing cookies that will sanitize lastID (and eventually other cookies) to check that it is numeric.

However, I think that this is wrong.  The problem wasn't that lastID wasn't numeric, it was that the query that uses it was vulnerable to injection.  I'm in charge of the review of the code changes, and I want to bring up the fact that forcing lastID to be numeric is not particularly useful and perhaps even undesirable.

Is there a term or concept that describes sanitizing at the right time (i.e. sanitizing at query time rather than at cookie retrieval time), or "over-sanitizing" (e.g. forcing lastID to be numeric) that I can use to describe what's happening/should happen in my review?  The second part of Postel's Law seems to apply here in my mind:

Be ... liberal in what you accept

答:
Your are right.  Correct all your queries to injection-proof prepared statements, and stop worrying about the supplied data.  Trying to sanitize inputs to be directly interpolated into SQL statements leads to web applications that reject last names containing apostrophes, or passwords containing certain special characters.

By the way, just because you are right doesn't mean you will be able to convince NOC.  Good luck with that.

Title: Name for sanitizing at the right time?


问:
Recursion or while loops
I was reading about some development interview practices, specifically about the technical questions and tests asked at interviews and I've stumbled quite a few times over sayings of the genre "Ok you solved the problem with a while loop, now can you do it with recursion", or "everyone can solve this with a 100 lines while loop, but can they do it in a 5 lines recursive function?" etc.

My question is, is recursion generally better than if/while/for constructs?

I've honestly always thought that recursion is not to be preferred, because it's limited to the stack memory which is a lot smaller than the heap, also doing a great number of function/method calls is suboptimal from a performance standpoint, but I may be wrong...

答:
Recursion is about repeating call to function, loop is about repeating jump to place in memory.

Should be mentioned also about stack overflow - http://en.wikipedia.org/wiki/Stack_overflow

Title: Recursion or while loops


问:
Using xml datatype to store a "shopping cart"
For my final project in school we have to develop an online shop. This shop should have a cart where items can be placed whether or not you are logged in. If you log out the cart shouldn't empty and should still be shown.

So my question is would it make sense to store the cart as xml in the database(ms sql server)? There is potentially a (relatively)fair amount of data that should be kept, is it possible that this could deliver any performance benefits or am I way off base?

答:
Whether to use a server-side database or a cookie depends on whether you want a user to have the same items in their shopping cart when logged on from another (device/browser).  Unless the user goes insane and orders thousands of items, the amount of data isn't likely to be a major factor.

Whether you store the data in XML, JSON, or some other format depends on your preferences and your environment (e.g., are the tools you're using better at dealing with XML than with JSON?).

The data you store itself should be pretty minimal--you don't want to replicate pricing, product details, etc., in your shopping cart data.


答:
Is the question too ambiguous?

Yes, the question is too ambiguous to be answered without clarifications. However, an additional rule saying that in cases when multiple rules apply, your program should pick the most specific thing, should remove the ambiguity.

Does the stress of an interview environment decrease ones ability to think critically to the point of not being able to complete such a trivial task?

It's more likely an indication of the candidate "cramming" the FizzBuzz: stress or not, the program is very simple.

I think the modified FizzBuzz is not comparable to the original one, because its ideal solution is different: although a chain of if-then-else remains acceptable, I think that a table-based solution is more appropriate for this problem:

```<code>static string[,] FB = new string[3,3] {
    {"FizzFizz", "Buzz", "Buzz"}
,   {"Fizz", "FizzBuzz", "BuzzBuzz"}
,   {"Fizz", "BuzzBuzz", "BuzzBuzz"}
};
static string FizzBuzz(string str) {
    return FB[
        Math.Min(str.Count(c => c == 'a'), 2)
    ,   Math.Min(str.Count(c => c == 'b'), 2)
    ];
}
</code>```

The size of the problem space is 3x3, not 2x2, so it maps to a table much more readily than the original FizzBuzz. In fact, I find a table-based solution to the original FizzBuzz problem harder to understand.

```<code>private static string[] FB = new[] {"{0}", "Fizz", "Buzz", "BizzBuzz"};
public static void Main() {
    for (var i = 1 ; i <= 100 ; i++) {
        Console.WriteLine(FB[(i%5==0?2:0)+(i%3==0?1:0)], i);
    }
}
</code>```

Title: Effectiveness of FizzBuzz and Beyond

Body:
As part of the interview process we initially ask the candidates to do 'FizzBuzz' nowadays the percentage of candidates that can correctly answer FizzBuzz has increased dramatically - this may be due to it's popularity on the web.

About a year ago, as a second question we began asking a question very similar to the original FizzBuzz. The question was designed to be as simple as the original FizzBuzz, and to also assess a particular ability of the candidate, specifically the ability to order and prioritize in a meaningful and logical manner a set of "business rules" that have been provided in some arbitrary order. The wording of the question initially seems slightly ambiguous, which may make it difficult for non-native English speakers, but if thought through can be correctly resolved - Also it gives the candidate the opportunity to ask questions for clarification, which is always a good thing.

We find this a very important skill to have as a developer, as software development is typically based on functional requirements that are derived in no particular order over time, that may place constraints and conditions upon other areas of the software without explicitly indicating and it is the job of the astute developer to at the very least investigate potential issues and conflicts with regards to the implementation.

What we found was that a little over 65% of the candidates (sample size of 38) that passed FizzBuzz completely failed FizzBuzz v2.0 Normally these candidates would be detected later on in the process, but it seems to be a nice way to detect them early on.

My question is not about whether or not FizzBuzz is outdated, but rather what factors could be contributing to such a high number of candidates failing the FizzBuzz v2 question.

Is the question too ambiguous?

Does the stress of an interview environment decrease ones ability to think critically to the point of not being able to complete such a trivial task?

Question:

Write a routine in your favourite programming language that will take a list of strings as input, and for each string in the list will do one of the following:

Print only Fizz if the string contains the letter A

Print only Buzz if the string contains the letter B

Print only BuzzBuzz if the string contains both A and B

Print only FizzFizz if the string does not contain both A and B

Print only FizzBuzz if the string contains only one A and only one B

Some typical questions asked by candidates are:

Should it be case sensitive?

Does "contains A and B" mean A should come before B

What should be printed if none of the points are met?

What should happen if more than one condition can be met?

We found that the overwhelming majority of candidates that successfully completed the question, didn't ask anything at all they just did it like they did FizzBuzz.

Body:
Is the question too ambiguous?

Yes, the question is too ambiguous to be answered without clarifications. However, an additional rule saying that in cases when multiple rules apply, your program should pick the most specific thing, should remove the ambiguity.

Does the stress of an interview environment decrease ones ability to think critically to the point of not being able to complete such a trivial task?

It's more likely an indication of the candidate "cramming" the FizzBuzz: stress or not, the program is very simple.

I think the modified FizzBuzz is not comparable to the original one, because its ideal solution is different: although a chain of if-then-else remains acceptable, I think that a table-based solution is more appropriate for this problem:

static string[,] FB = new string[3,3] {
    {"FizzFizz", "Buzz", "Buzz"}
,   {"Fizz", "FizzBuzz", "BuzzBuzz"}
,   {"Fizz", "BuzzBuzz", "BuzzBuzz"}
};
static string FizzBuzz(string str) {
    return FB[
        Math.Min(str.Count(c => c == 'a'), 2)
    ,   Math.Min(str.Count(c => c == 'b'), 2)
    ];
}

The size of the problem space is 3x3, not 2x2, so it maps to a table much more readily than the original FizzBuzz. In fact, I find a table-based solution to the original FizzBuzz problem harder to understand.

private static string[] FB = new[] {"{0}", "Fizz", "Buzz", "BizzBuzz"};
public static void Main() {
    for (var i = 1 ; i <= 100 ; i++) {
        Console.WriteLine(FB[(i%5==0?2:0)+(i%3==0?1:0)], i);
    }
}


答:
You're definitely right.  I think you're actually hitting on two concepts.

KISS. (Keep It Simple) The basic tenet is that you use the simplest solution that actually solves the problem. (Making lastID numeric doesn't really solve the problem, just that particular case)

DRY.  (Don't Repeat Yourself) If there was ever another place where this query was executed with some other input than lastID, you'd have to solve the problem of SQL injection there too.  Just fix the query and it's solved for all execution paths.

Moreover, the solution of enforcing lastID to be numeric is using the wrong level of abstraction.

Title: Name for sanitizing at the right time?

Body:
Recently we had an issue on our site where someone attempted SQL injection via a cookie (we'll call it lastID).  NOC was in a frenzy and angry about how the cookie as an attack vector could be ignored.  They had a developer create a class for managing cookies that will sanitize lastID (and eventually other cookies) to check that it is numeric.

However, I think that this is wrong.  The problem wasn't that lastID wasn't numeric, it was that the query that uses it was vulnerable to injection.  I'm in charge of the review of the code changes, and I want to bring up the fact that forcing lastID to be numeric is not particularly useful and perhaps even undesirable.

Is there a term or concept that describes sanitizing at the right time (i.e. sanitizing at query time rather than at cookie retrieval time), or "over-sanitizing" (e.g. forcing lastID to be numeric) that I can use to describe what's happening/should happen in my review?  The second part of Postel's Law seems to apply here in my mind:

Be ... liberal in what you accept


答:
I would simply point out that the vulnerability lies with the database procedure that can be exploited by SQL Injection. The cookie is merely an attack vector.

While it is important to take care of known attack vectors, the more comprehensive solution is to fix the vulnerability at the source. This will both solve the immediate issue of the cookie attack vector and other unknown (possibly future) attack vectors.

Title: Name for sanitizing at the right time?


问:
Is Neo4j graph database sufficient to itself for all query types?
Neo4j eases relationship traversals => especially useful for a social network for instance.

But are there any scenarios when it's advised to associate an additional relational database (or other NoSQL database that isn't specifically oriented graph) for specific query types.

In short, can Neo4j be sufficient to itself for all query tasks?

答:
I tend to think of it this way.  SQL relational databases are tuned to run SQL queries as fast as possible, whether or not that is the best way to represent your data.

Each of the NoSQL products have generally arisen because SQL databases are not a good match for representing a particular type of data, and are tuned for that use.  If you are using a well respected product for the problem its designed to solve, then you are probably in good shape.

Go outside this, and it tends to bite you.


答:
This shop should have a cart where items can be placed whether or not you are logged in. If you log out the cart shouldn't empty and should still be shown.

Those requirements seem to ask for client side storage, that is either cookies or localStorage. But of course you could set a simple cookie, separate from the session cookie, that reference a shopping cart stored in the database.

I don't see much need for XML in this job, while at times there may be a performance benefit from collecting a lot of data in a single string (that could be in XML form) and storing that in the database, rather than storing the same data as a lot of entries, I do not think that applies in this case since you update a lot, you don't read a lot, and when you do read you need the data split for further handling immediately.

Title: Using xml datatype to store a "shopping cart"

Body:
For my final project in school we have to develop an online shop. This shop should have a cart where items can be placed whether or not you are logged in. If you log out the cart shouldn't empty and should still be shown.

So my question is would it make sense to store the cart as xml in the database(ms sql server)? There is potentially a (relatively)fair amount of data that should be kept, is it possible that this could deliver any performance benefits or am I way off base?


问:
project layout using webapi
I have the following project structure I would like to implement. I would like to know if there are any pitfalls to structuring my code this way. It is going to be using Microsoft's WebAPI, an MVC 4 project, and Plain Old C# Objects (POCO). The explanation follows.

First off there is going to be a class library project that contains only interfaces and objects like so:

```<code>public interface IBookService {
   IEnumerable<Book> GetBooks();
}

public class Book {
   public int Id { get; set; }
   public string Name { get; set; }
}
</code>```

This interface and class will be shared by the other projects. The first being the implementation project which contains:

```<code>public class BookService : IBookService {
  // implementation that pulls books from somewhere
}
</code>```

The third project is going to be a WebAPI project that exposes IBookService as a  uri, such as http://mysite/books. UPDATE: This WebAPI site will be sitting on a different machine than the MVC site.

Now here is where I'm concerned about my implementation choice. The fourth and final project is an MVC 4 application. It will reference only the interfaces and the web api (via HttpContent and friends). I would like to implement the IBookService interface in this project as well. Except in this implementation it would call the WebAPI like so.

```<code>public class MvcBookService : IBookService {
   public IEnumerable<Book> GetBooks() {
      var client = new HttpClient();
      client.BaseAddress = new Uri("http://mySite"); // would be pulled from config
      client.DefaultRequestHeaders.Accept.Add(
         new MediaTypeWithQualityHeaderValue("application/json"));

      HttpResponseMessage response = client.GetAsync("books").Result; // blocking call
      if (response.IsSuccessStatusCode) {
          // blocking call
          return response.Content.ReadAsAsync<IEnumerable<Book>>().Result;
      } else {
         // handle response code
         return null;
      }
   }
}
</code>```

I plan on enforcing this project structure for all WebAPI interaction within the company.

I don't for see any maintenance problems with this project layout. However many eyes always helps.

答:
This is similar to a recent PSE question, and I'll answer yours with the same advice:

Don't bother creating a dependency between your MVC project and the WebAPI project. Put as much of your logic as is possible under the Service project/layer, and have both the WebAPI and MVC projects depend directly on it, independently.

Forcing your MVC project to depend on the WebAPI just adds another layer to the architecture you have to support, but without any clear benefit (that I can see).

Title: project layout using webapi


答:
I have worked on a system which implemented a shopping cart in precisely this fashion: "in-progress" shopping carts were serialized to XML and stored into a single field in a single table in the database.

The reason to do this isn't so much performance as ease of development. I suspect that once upon a time, shopping carts were only stored in session state, so if you browsed away from the site and returned an hour later, they would be gone. I suspect that when a request came in to make them persist against a user, the quickest way to do it was just to decorate the various classes involved with XML serialization attributes, serialize, store.

The pitfall to watch for is that this will make it difficult to do much with the data other than storing and retrieving individual users' carts. For example, if a particular product is removed from the catalogue, you might want to remove it from any shopping carts. If you had your temporary carts stored as a bunch of tables you'd simply find them with something like SELECT * FROM ShoppingCartItems WHERE ProductID=@productIdToDelete. If it's all in XML blobs, that won't be straightforward, and you may find a better approach to just re-validate all carts when they are retrieved from the DB and deserialized.


问:
What is best pratice for user stories containing two roles
I have a number of user stories where the same feature needs to be shared by multiple roles. I have started writing these stories like this:

As a Role-A or a Role-B
 When I perform Action-X
 Event-Y should occure.

Is this the correct way to represent that concept in user stories, or should I break it up into one story for each role?

答:
You need to identify and abstract out roles

The example you provided...

```<code>As a Role-A or a Role-B
When I perform Action-X
Event-Y should occure.
</code>```

doesn't scale because there are an exponential number of combinations that the program could take.

To extract individual roles, you need to imagine the steps from a first-hand perspective while ignoring the global state.

I highly suggest you take a look at 'How to get a cup of coffee'. It demonstrates how a REST API for a coffee shop can be modeled using state diagrams.

The point is, you won't be able to draw an accurate picture of how the system interacts globally until you can see it working at a local level.

Body:
You need to identify and abstract out roles

The example you provided...

As a Role-A or a Role-B
When I perform Action-X
Event-Y should occure.

doesn't scale because there are an exponential number of combinations that the program could take.

To extract individual roles, you need to imagine the steps from a first-hand perspective while ignoring the global state.

I highly suggest you take a look at 'How to get a cup of coffee'. It demonstrates how a REST API for a coffee shop can be modeled using state diagrams.

The point is, you won't be able to draw an accurate picture of how the system interacts globally until you can see it working at a local level.


问:
Unit of work/repository pattern with dependency injection advice
I'm developing a series of repository classes and a UnitOfWork class (plus its IUnitOfWork interface of course). I'm using Castle Windsor, which injects dependencies via constructors.

My business tier has classes such as "CustomerBusinessLogic", with methods like RetrieveCustomer, SaveCustomer, etc. These in turn use the UOW to perform the database operations.

I'm struggling to find how/where the BLL class should get an instance of the UOW. It doesn't feel right injecting it into the ctr, as a unit of work is exactly that - a unit of work! I think an individual method (LoadCustomer, SaveCustomer) should be responsible for instantiating the UOW for the lifetime of its operation. However doing this means resorting to a service locator, which is an anti-pattern.

Suggestions welcome!

答:
What you're describing is a really common pattern where instead of injecting the object of interest you want to inject an object that can create instances of the object of interest. You might call it a factory. If you are using Autofac it is baked in by simply injecting Func<T> (to create instances of T). I'm pretty sure Castle Windsor has this same feature.

You may need to consider the boundaries of your unit of work further. Your question implies that a unit of work falls within the boundaries of, say, SaveCustomer but ask yourself what if I reuse that method within a larger unit of work. What are the boundaries of your unit of work then, and does your injection strategy and unit of work implementation handle that correctly.


答:
I just finished an article today about the repository pattern (with sample implementations).

The thing with most .NET ioc containers is that they support scoping. That is, they can create objects with a limited lifetime. That works very well with HTTP applications since the scope is the same as the lifetime of a HTTP request.

If you use ASP.NET MVC you can combine that with built in features of MVC to trigger the UoW if no errors where detected: http://blog.gauffin.org/2012/06/how-to-handle-transactions-in-asp-net-mvc3/

If you use any other kind of application I usually create a scope by myself (for instance to wrap a command):

```<code>using (var scope = MyContainer.CreateChildCointainer())
{
    using (var uow = scope.Resolve<IUnitOfWork>())
    {
        // do something here

        uow.SaveChanges();
    }
}
</code>```

The thing is that the repositories etc do not have to be aware of the unit of work (if you use databases in .NET). The UoW implementation can make sure that all OR/M or UoW implementation enlists all db commands in the transaction.

Title: Unit of work/repository pattern with dependency injection advice

Body:
I'm developing a series of repository classes and a UnitOfWork class (plus its IUnitOfWork interface of course). I'm using Castle Windsor, which injects dependencies via constructors.

My business tier has classes such as "CustomerBusinessLogic", with methods like RetrieveCustomer, SaveCustomer, etc. These in turn use the UOW to perform the database operations.

I'm struggling to find how/where the BLL class should get an instance of the UOW. It doesn't feel right injecting it into the ctr, as a unit of work is exactly that - a unit of work! I think an individual method (LoadCustomer, SaveCustomer) should be responsible for instantiating the UOW for the lifetime of its operation. However doing this means resorting to a service locator, which is an anti-pattern.

Suggestions welcome!

Body:
I just finished an article today about the repository pattern (with sample implementations).

The thing with most .NET ioc containers is that they support scoping. That is, they can create objects with a limited lifetime. That works very well with HTTP applications since the scope is the same as the lifetime of a HTTP request.

If you use ASP.NET MVC you can combine that with built in features of MVC to trigger the UoW if no errors where detected: http://blog.gauffin.org/2012/06/how-to-handle-transactions-in-asp-net-mvc3/

If you use any other kind of application I usually create a scope by myself (for instance to wrap a command):

using (var scope = MyContainer.CreateChildCointainer())
{
    using (var uow = scope.Resolve<IUnitOfWork>())
    {
        // do something here

        uow.SaveChanges();
    }
}

The thing is that the repositories etc do not have to be aware of the unit of work (if you use databases in .NET). The UoW implementation can make sure that all OR/M or UoW implementation enlists all db commands in the transaction.


问:
How do you handle increasingly long compile times when working with templates?
I use Visual Studio 2012 and he have cases where we added templates parameters to a class "just" in order to introduce a "seam point" so that in unit-test we can replace those parts with mock objects.

How do you usually introduce seam points in C++: using interfaces and/or mixing based on some criteria with implicit interfaces by using templates parameters also ? One reason to ask this is also because when compiling sometimes a single C++ file (that includes templates files, that could also include other templates) results in an object file being generated that takes in the order of around 5-10 seconds on a developer machine.

VS compiler is also not particularly fast on compiling templates as far as I understand, and because of the templates inclusion model (you practically include the definition of the template in every file that uses it indirectly and possibly re-instantiate that template every time you modify something that has nothing to do with that template) you could have problems with compile times (when doing incremental compiling).

What are your ways of handling incremental(and not only) compile time when working with templates (besides a better/faster compiler :-)).

答: We used to fire off a big task to build our precompiled headers and precompiled templates overnight, and just build against those the following day.</p>


答:
Once I used a strange solution for a similar problem: Including the STL lead to compile times like several seconds per source file - no matter how tiny it was. So I included all my source files into one master file and the compilation time per file hardly changed... which meant a speed up of factor 20+ as I had only a single file to compile.

In order to keep the design clean I continued to maintain a makefile, but never actually used it (except for verifying it still works).

Title: How do you handle increasingly long compile times when working with templates?

Body:
I use Visual Studio 2012 and he have cases where we added templates parameters to a class "just" in order to introduce a "seam point" so that in unit-test we can replace those parts with mock objects.

How do you usually introduce seam points in C++: using interfaces and/or mixing based on some criteria with implicit interfaces by using templates parameters also ? One reason to ask this is also because when compiling sometimes a single C++ file (that includes templates files, that could also include other templates) results in an object file being generated that takes in the order of around 5-10 seconds on a developer machine.

VS compiler is also not particularly fast on compiling templates as far as I understand, and because of the templates inclusion model (you practically include the definition of the template in every file that uses it indirectly and possibly re-instantiate that template every time you modify something that has nothing to do with that template) you could have problems with compile times (when doing incremental compiling).

What are your ways of handling incremental(and not only) compile time when working with templates (besides a better/faster compiler :-)).


问:
What are the drawbacks of elastic tabstops?
Look here: a typical holy war on tabs vs spaces.

Now look here: elastic tabstops. All problems solved, and a bunch of very useful new behaviours added.

Are elastic tabstops even mentioned in that tabs vs spaces discussion? Why not? Are there drawbacks to the elastic tabstop idea so serious that nobody has ever implemented them in a popular editor?

EDIT: I apologise for putting too much emphasis on "why aren't they mentioned". That wasn't really what I intended; that question is possibly even off topic. What I really mean is, what are the biggest drawbacks of this that prevent wider adoption of an obviously beneficial idea? (in an ideal world where everything supports it already)

(Turns out there's already a request on the Microsoft Connect for a Visual Studio implementation of elastic tabstops, and a request in Eclipse too. Plus there's a question asking about other editors that implement elastic tabstops)

答:
Why don't we just make the vertical tab character (VT, ASCII 11) serve to indicate the use of elastic tabstops?  It serves no purpose in any mainstream programming language, yet is parsed as valid whitespace in all of them, AFAIK.

This would mean that the use of elastic tabstops is no longer an externalized convention (e.g. "this file was formatted with elastic tabstops, please turn them on") but something you opt in to on a case by case basis.

Existing text editors usually display a glyph or a single space in place of a vertical tab.  This is not ideal, but a small price to pay, IMO.


问:
Thoughts on a custom data structure for a node/chain implementation
I am designing a simple GUI that will allow a user to create a GPX route by clicking repeatedly on a map panel.  I am faced with a design dilemma for how to represent the nodes and route.  This construct can be abstracted as follows:

the user clicks n times on the screen in sequence to create a chain of n nodes

after a chain has been completed, a user can add more nodes to it, either by selecting nodes in the middle (inserting between existing nodes) or by simply automatically appending to the end with his next click

At first I was determined to use a Java Collections class to represent the chain, but there are unexpected difficulties with that.  On the surface, this would appear to be a perfect example of a LinkedList, but consider as follows.  If the user wishes to insert a node in the middle of the chain, he first chooses some node on screen that he wishes to insert a new node before.  If the node belongs to a linked list, it will need to maintain a reference to its encompassing list (a somewhat unusual practice, I'd think), and even then we will still have to locate the node in the list before we can insert.  So we have to:

find the node (linear time)

insert the new node (constant time)

Or if I try the same thing with an ArrayList, it also performs at best in linear time.

find the node (linear time)

insert the new node (linear time)

But neither case really seems desirable.  I briefly flirted with the idea of using a LinkedHashSet, but it does not allow insertion into the middle of the linked list, nor does it seem fundamentally correct to use a set implementation for something like this.

So here is what I came up with:

```<code>class Node {
    Node previous;
    Node next;
    Chain chain;
}
</code>```

A Node maintains only a reference to its previous and next nodes, as well as the chain it belongs to (again, this latter part seems unconventional and possibly even wasteful to me, but I'm convinced it may be necessary here).

```<code>class Chain {
    Node first;
    Node last;
}
</code>```

The chain knows only what its first and last nodes are.

Now, if a user wants to insert a node in the middle of the chain?  He selects the node, which simply updates the first/last references of itself and its neighbors.  If he wants to add nodes to the end of a chain?  He simply selects any node on screen (which is aware of what chain it belongs to, and therefore what the last node in that chain is), and the chain immediately begins updating link references for the last node and each node added after it, as well as keeping its own "last" reference up to date.

I really wanted to use a Collections class, but this approach seems better to me.  But I'd love to here thoughts/criticisms from more experienced programmers.  Thanks.

答:
Mutable circular references are nasty. Just use an ArrayList and don't worry about it.

You can see all of the elements on screen: it's not going to be so long that linear time takes any time.

re dude demanding an explanation why mutable circular references are nasty: like, as in bad code. It's an inefficient use of programmer-thinky-time, not unavoidably problematic.


问:
What should every programmer know about programming?
Please, stay on technical issues, avoid behavior, cultural, career or political issues.

答: Short-circuit evaluation, althought it's one of the first thing they teach you about boolean operators.</p>

ContentLicense: CC BY-SA 2.5


问:
Functional testing before code checkin
I am working on a project with legacy code where it does not have much code coverage. One of the idea to improve that is to enforce a rule that each code check-in must have test, not only test but functional test as well, so that we can verify that the existing code did not break.

I would like to get some ideas, both pros and cons on this approach. Sometimes it sounds like it's a huge undertaking as it will need a really good infrastructure so that developers can have their code fully tested before it is committed.  How would one go about running automated unit tests as well as functional tests when code is checked in?  Is this even a feasible idea?

答:
You should start by evaluating the problem that you are really wanting to solve.  You have a nasty confusing code base that is brittle and filled with technical debt.  Often those working on it are required to know the software completely to truly know what other features they could be affecting, however this is unrealistic because the legacy code has gotten so bad over the years that your group has had a revolving door.

There is hope to fix this, but I feel that perhaps commit enforcement of functional tests is like learning to run before you have even started crawling.

1. Refactoring slowly

Learn to get in the good habit of refactoring code as you work on various areas.  Perhaps you are fixing a bug in one module, however the code is confusing, scattered, duplicated and doesn't conform to any patterns or designs.  This is a good opportunity to take a few extra days to refactor that portion.

Some things to keep in mind when you refactor are to keep an eye on the ideal yet realistic design that you hope to achieve someday.  Document your efforts well as you go.

2. Write unit tests for your REFACTORED code

How can you verify that the module or code you have refactored hasn't changed functional behavior?  Write unit tests that can verify the newly refactored code.  I put emphasis on only writing unit tests for refactored code as unit tests on poor legacy code almost always end up being poor unit tests.

On this note, enforcing each check in to have a unit test will be counter productive as you are wasting time writing unit tests on code that should be refactored anyway, and also it encourages a rushed developer that is close to a deadline to check in incomplete or deficient unit tests.

3. Code review

Get your team in the habit of reviewing each others code and designs.  Enforce this procedure for any major code checkin or feature to make sure that code is following proper design, that modules are slowly being refactored, and that unit tests are being added to cover new and refactored code.

4. Automated builds and test suites

Establish and configure automated builds after checkin to verify that code compiles, and also configure that all existing unit tests will run and report any test failures to the team after a checkin.  This is a superior means of enforcing code commit quality.

After addressing the following issues, you should begin to start seeing the benefits of Functional Testing in general, however a few of the negatives aspects that I mentioned about commits enforcing the existence of a unit test I feel paint a pretty strong picture that it is not a worthwhile endeavor when you have so much room for improvement of code and feature quality elsewhere in the application.

Title: Functional testing before code checkin


问:
Is fixing bugs made by other people a good approach?
Let's assume the situation where a team of four developers is building an application. During the testing phase, bugs are reported by users. Who should fix them? The person who committed the erroneous code, or anyone who is free?

What is preferred approach in agile development (scrum)?

答:
There are only three reasons to care about who fixes a bug: cost, speed and professional development.

And there are pros and cons for all three.   For instance professional development, on one hand it's an opportunity to learn more about the code on the other it's an opprtunity to recognize the kinds of mistakes you make and avoid some in the future. Or take cost, presumably the one that made the mistake would be able to fix it faster, and probably cheaper, on the other hand there's a cost for the time spent identifying who made the mistake, and assigning it to the appropriate person -- time which in a lot of cases exceeds that of fixing the bug.

The agile approach is to let the developers self assign the problem, I would override that only for a good reason.


答:
TL;DR: Do the analysis for your case. Weigh the cost against the benefit and do it if the benefits win.

A lot depends on the cost of breaking the system versus the cost of writing a full functional test for every change.  This can be further complicated by the developers familiarity with test driven development.  It can be difficult, expensive or both to create a test that captures all of the functional behavior and asserts on that state.

We do ATDD (Acceptance Test Driven Development) at my work.  The developers (yes the developers) are responsible for writing a test (we build up just like you do with a unit test) before coding.  The test doesn't stop at a unit, but continues on until it covers the acceptance criteria.  We use a standard xUnit framework and wire the test call directly to the top of the stack instead of starting up a server.  Essentially we treat our system as the unit rather than a function or object.  Keeping the stack processing within the same process space as the test call eliminates timing issues with regard to server startup and gives us more control over what we can change or even call in the stack.  This allows us to create tests with mocks if we need a more more controlled test, or even write straight unit tests if we feel we need coverage specifically for the a function.

Cons

False positive broken tests do to unmanaged resources (ie. database, network, network service, etc).  This can be mitigated in many ways.  In practice I have found failures from unmanaged resources to be both obvious and, with a little work, rare.

Functional test (and most ATDD tests) only tell you the system isn't working properly, it doesn't necessarily tell you with function, module or object is defective.  In practice, most errors I get come with a stack trace so I know at least where the exception is thrown.  While the origin of the exception is not always the same as the source of the error, it's usually not that hard to backtrack and find what the source is.  There is also nothing preventing you from writing more granular tests (more classic unit tests) for more/better coverage.

Additional time upfront.  Although this is true for all test driven development in general. It costs more time upfront to develop the tests and the code.  It can also cost more time specifically for ATDD because you have to understand how to reset the system after a test so that your always executing from a known state.

Pros

Coverage of integration points (other function, objects, databases, SOAP services, etc).  I started doing only unit testing (any automated tests are better than none) and while that did prevent many kinds of defects I found it didn't prevent the worst ones which came from integration incompatibilities.  A function or object returning information in a slightly different way than was expected.  Sure you can mitigate with strong requirements, but the point is that you have no coverage of the actual integration points.

Coverage of the acceptance criteria aka. a working system.  The near confidence that your code will work you develop from having a suite of automated acceptance tests is great.  The fact you can run the suite to verify everything works after a massive refactor/rewrite, upgrading dependent systems, deploying to alternative platforms, etc is a huge benefit.

Forces the developer to understand what the system behavior needs to be.  Obviously this only works if the developer is the one writing the tests.  I find this to be very valuable, so much so I don't think I will ever consider changing this practice.  I have found very valuable benefits such as driving understanding/comprehension and eliminating ambiguities earlier in the process.

Your Case, and The Differences

In your case you have to weigh the cost to doing this style of development with the benefit.  I would do a trial and see how it works for 5 changes.  Then review and take a look at the cost and the benefits.

UPDATE:

I've simulated HTTP calls two different ways.

Limited Monkey patch all network calls to be direct calls to the network call's endpoint which keeps everything in the same process space.  We limit the monkey patch because we may still need to make network calls out to communicate with DB, SOAP, etc.

Create our own HTTP GET and POST which takes data exactly how a user would send it.  Transform and pass the data the same way it would occur in a server to our code's entry point (top of our stack).

Obviously this works better with RESTful services because it eliminates having to test the UI component.  However, you can automate, to some degree, the testing of the UI.  What I have done in the past is use HTML parsing to assert the data is showing in the page under the correct element as identified by class, element or context.  This allows you to still make calls and assert the data the user is requesting is returned.  This still leaves the rendering of the page as a gap.

The classification of what kind of test it is depends on your definition of functional/integration/acceptance tests are.  They are integrative tests in that they do cover integration points.  They are functional tests in that they test a particular function of the system.  They are acceptance tests in that the tests encode the success criteria by which we can say the feature has been implemented.  They are always, always, ALWAYS automated tests.

Title: Functional testing before code checkin

Body:
I am working on a project with legacy code where it does not have much code coverage. One of the idea to improve that is to enforce a rule that each code check-in must have test, not only test but functional test as well, so that we can verify that the existing code did not break.

I would like to get some ideas, both pros and cons on this approach. Sometimes it sounds like it's a huge undertaking as it will need a really good infrastructure so that developers can have their code fully tested before it is committed.  How would one go about running automated unit tests as well as functional tests when code is checked in?  Is this even a feasible idea?


答:
You really want to leverage Java-provided "list maintenance" functionality. Go with ease of use first and worry about performance later. "pre-optimization" is a dog chasing its tail.

```<code>Class Waypoint {
    string name;
    double lat;  // I'm not saying double is necessarily the ideal type here.
    double long;
    // other stuff as needed for GPX

   RouteCollection myRoutes; // all the routes containing this waypoint
}

Class Route {
    LinkedList<Waypoint> myRoute;
    string name;
    Waypoint start { return myRoute[0]; }
    Waypoint end { return myRoute[myRoute.Length-1] };
}

Class RouteCollection {
    ArrayList<Route> myRoutes;
    // maybe a dictionary/hash instead, the key being the Route.name perhaps
    // order is not important in this collection, I suspect.
}

Class WaypointJanitor {
    // keeps cross references in the various classes in sync
    // for example updates the Waypoint.myRoutes when a Route object is edited

    // I can see the main add/delete/insert functionality in this class,
    // passing routes & waypoint parameters. And all the complexity is contained, keeping your data structure classes clean and simple.
}
</code>```

The UI Provides Context for Inserting

If the node belongs to a linked list, it will need to maintain a reference to its encompassing list

"if the node belongs.." This is confusing. Seems to me that in the UI I create routes/chains/tracks explicitly, giving each a name probably. Thus there is no question about. When I want to insert a waypoint I designate through the UI what route I'm manipulating. Further, any given waypoint (arbitrary lat/long coordinate) could be part of any number of routes; by explicitly selecting the route to edit there is no ambiguity.

Title: Thoughts on a custom data structure for a node/chain implementation

Body:
I am designing a simple GUI that will allow a user to create a GPX route by clicking repeatedly on a map panel.  I am faced with a design dilemma for how to represent the nodes and route.  This construct can be abstracted as follows:

the user clicks n times on the screen in sequence to create a chain of n nodes

after a chain has been completed, a user can add more nodes to it, either by selecting nodes in the middle (inserting between existing nodes) or by simply automatically appending to the end with his next click

At first I was determined to use a Java Collections class to represent the chain, but there are unexpected difficulties with that.  On the surface, this would appear to be a perfect example of a LinkedList, but consider as follows.  If the user wishes to insert a node in the middle of the chain, he first chooses some node on screen that he wishes to insert a new node before.  If the node belongs to a linked list, it will need to maintain a reference to its encompassing list (a somewhat unusual practice, I'd think), and even then we will still have to locate the node in the list before we can insert.  So we have to:

find the node (linear time)

insert the new node (constant time)

Or if I try the same thing with an ArrayList, it also performs at best in linear time.

find the node (linear time)

insert the new node (linear time)

But neither case really seems desirable.  I briefly flirted with the idea of using a LinkedHashSet, but it does not allow insertion into the middle of the linked list, nor does it seem fundamentally correct to use a set implementation for something like this.

So here is what I came up with:

```<code>class Node {
    Node previous;
    Node next;
    Chain chain;
}
</code>```

A Node maintains only a reference to its previous and next nodes, as well as the chain it belongs to (again, this latter part seems unconventional and possibly even wasteful to me, but I'm convinced it may be necessary here).

```<code>class Chain {
    Node first;
    Node last;
}
</code>```

The chain knows only what its first and last nodes are.

Now, if a user wants to insert a node in the middle of the chain?  He selects the node, which simply updates the first/last references of itself and its neighbors.  If he wants to add nodes to the end of a chain?  He simply selects any node on screen (which is aware of what chain it belongs to, and therefore what the last node in that chain is), and the chain immediately begins updating link references for the last node and each node added after it, as well as keeping its own "last" reference up to date.

I really wanted to use a Collections class, but this approach seems better to me.  But I'd love to here thoughts/criticisms from more experienced programmers.  Thanks.

Body:
You really want to leverage Java-provided "list maintenance" functionality. Go with ease of use first and worry about performance later. "pre-optimization" is a dog chasing its tail.

Class Waypoint {
    string name;
    double lat;  // I'm not saying double is necessarily the ideal type here.
    double long;
    // other stuff as needed for GPX

   RouteCollection myRoutes; // all the routes containing this waypoint
}

Class Route {
    LinkedList<Waypoint> myRoute;
    string name;
    Waypoint start { return myRoute[0]; }
    Waypoint end { return myRoute[myRoute.Length-1] };
}

Class RouteCollection {
    ArrayList<Route> myRoutes;
    // maybe a dictionary/hash instead, the key being the Route.name perhaps
    // order is not important in this collection, I suspect.
}

Class WaypointJanitor {
    // keeps cross references in the various classes in sync
    // for example updates the Waypoint.myRoutes when a Route object is edited

    // I can see the main add/delete/insert functionality in this class,
    // passing routes & waypoint parameters. And all the complexity is contained, keeping your data structure classes clean and simple.
}

The UI Provides Context for Inserting

If the node belongs to a linked list, it will need to maintain a reference to its encompassing list

"if the node belongs.." This is confusing. Seems to me that in the UI I create routes/chains/tracks explicitly, giving each a name probably. Thus there is no question about. When I want to insert a waypoint I designate through the UI what route I'm manipulating. Further, any given waypoint (arbitrary lat/long coordinate) could be part of any number of routes; by explicitly selecting the route to edit there is no ambiguity.


问:
What are the pros and cons of Inter process communication done via sockets vs shared memory?
I understand that two of the many more options for inter process communication can be :

Shared memory

Sockets

Actually I saw these two options being exposed by Intellij Idea for debugging a Java application . I want to know what are the pros and cons of each approach .

答:
A few advantages for each off the top of my head. Note that some of these items may not apply in all cases; these are just general observations.

Sockets

Simple and controlled. Can be extended to network sockets as necessary with little or no modification. Programming model requires serialization, which in turn requires you to think about what data actually gets transferred from A to B. Synchronization is necessarily built-in to the communication mechanism; no other synchronization necessary.

Shared Memory

Does not necessarily require a syscall (therefore potentially faster). Sharing does not explicitly require data to be transferred -- data can be made available that the recipient does not retrieve (bandwidth does not have to be wasted transferring data that the recipient won't use). No serialization/deserialization step means no time spent on communication overhead.


问:
Top down or bottom up approach?
I'm an interface designer and now I'm working with a team of programmers to develop a new CMS for a heavy media site.

As I've started developing a specification list for a prototype it turned out a very big one. I do realize now that the client-side will be JS heavy, with lots of DnD and other "cool designer stuff". The CMS will even include a small project management system for its users, nothing big like Basecamp, but with a live feed of comments etc.

The problem is the the team has now separated. Someone is proposing the existing backend solution used in other CMS, someone is proposing to rewrite everything from scratch. The point to keep the code is that it is faster, the point to rewrite is to make it better for the proposed design (include Node.js and other stuff I don't actually get).

The question is — can the UI specs influence back-end? The guys that propose to use the existing solution did everything with the Yii framework (as far as I know), and they say that everything on server is not affected by this "interface coolness". Others say that it does, that even autosave can't work without server load.

答:
The ideal design would be one where frontend and backend are so completely structurally independent that each team can focus on its own strengths without necessarily bending to appease the other. That's the goal, but it typically isn't realistic.

For the rest of us in the real world, here's your rule-of-thumb to help you prioritize appropriately: start with what matters most. If performance is your key driving feature, start with performance. If UI effectiveness is the most important feature, start with the UI.

The decisions that matter most should be made with all possible options open to you. All other decisions will then be made in the context of these "important" decisions.

Title: Top down or bottom up approach?


答:
If your templates parameters can only assume a finite (and small) set of values, you could move their definition in a source file, and use explicit instantiation.

For instance, in aaa.h you only declare the template functions f and g:

```<code>template <int n>
int f();

template <class T>
void g(int a);
</code>```

Assume n template parameter can only be 1, 3, 6, and T template parameter can only be int, long and void *.

Then you define them in aaa.cpp like this:

```<code>template <int n>
int f()
{
    ...
}

template <class T>
void g(int a)
{
    ...
}

template int f<1>();
template int f<3>();
template int f<6>();

template void g<int>(int a);
template void g<long>(int a);
template void g<void *>(int a);
</code>```

In this way the compiler instantiates the template for the given parameters when compiling aaa.cpp. When compiling client code, it assumes that the definitions exist somewhere, and the linker will take care of that.

```<code>#include "aaa.h"

int main()
{
    f<1>();
    f<3>();
    f<6>();

    g<int>(5);
    g<long>(5);
    g<void *>(5);
}
</code>```

You can explicitly instantiate template classes too. The drawback is that you can not use f or g with other template parameters.

```<code>#include "aaa.h"

int main()
{
    f<5>();
}
</code>```

results in

```<code>undefined reference to `int f<5>()'
</code>```

I used this technique in a project where few complex classes depended on a small (< 10) set of integer template parameters, and it significantly reduced compilation time (since the compiler did not have to parse the complex template definitions when compiling the client code). Of course you may get lesser improvements, depending on the actual code.

Body:
If your templates parameters can only assume a finite (and small) set of values, you could move their definition in a source file, and use explicit instantiation.

For instance, in aaa.h you only declare the template functions f and g:

template <int n>
int f();

template <class T>
void g(int a);

Assume n template parameter can only be 1, 3, 6, and T template parameter can only be int, long and void *.

Then you define them in aaa.cpp like this:

template <int n>
int f()
{
    ...
}

template <class T>
void g(int a)
{
    ...
}

template int f<1>();
template int f<3>();
template int f<6>();

template void g<int>(int a);
template void g<long>(int a);
template void g<void *>(int a);

In this way the compiler instantiates the template for the given parameters when compiling aaa.cpp. When compiling client code, it assumes that the definitions exist somewhere, and the linker will take care of that.

#include "aaa.h"

int main()
{
    f<1>();
    f<3>();
    f<6>();

    g<int>(5);
    g<long>(5);
    g<void *>(5);
}

You can explicitly instantiate template classes too. The drawback is that you can not use f or g with other template parameters.

#include "aaa.h"

int main()
{
    f<5>();
}

results in

undefined reference to `int f<5>()'

I used this technique in a project where few complex classes depended on a small (< 10) set of integer template parameters, and it significantly reduced compilation time (since the compiler did not have to parse the complex template definitions when compiling the client code). Of course you may get lesser improvements, depending on the actual code.


问:
would like help understanding javascript throttle function
A user on Stack Overflow posted a question related to overriding a native JS function. The question is here and this is the code:

```<code>function throttle(fn, time) {
  var handle;

  var execute = function() {
    handle = null;
    fn.apply(this, arguments);
  };

  var throttled = function() {
    if(!handle) {
      handle = setTimeout(execute.bind(this), time);
    }
  };

  throttled.toString = function() {
    return fn.toString() + "\n// throttled to " + time + "ms";
  };

  return throttled;
}

var makeAjax = throttle(function(callback) {
  $.getJSON("/path", callback);
}, 500);
</code>```

I have a pretty good handle (I think) on JavaScript, but there are some areas that remain very grey to me. I would like to know what is happening in this code?

I don't really understand what bind and apply are doing, or what the end result of this all would be. I've looked up bind and apply on Mozilla's JS documentation, but the "official" definition has done little to help me understand what they are doing in this context.

I appreciate your help!

答:
It's quite simple really - the handle of a setTimeout call is used as a guard against multiple execution.

The throttled variable contains a function that is also the return value - makeAjax will contain that function. When it is executed, it will either

Cause the execute function to be called after a delay, if handle has been cleared / not already set

Return immediately otherwise.

This makes the name of the function apparent - it throttles the execution of the input function to after a certain time, and no more than once concurrently.

It uses bind to set the this context of the function stored in the execute variable.

The execute variable is a function wrapping the calling of the input function with the clearing of the handle, so that whenever the function stored in execute is called it allows further executions of the function. The function uses apply to execute the function with a specific context and arguments.

I hope that clears something up - I found it hard to put into words at all, and I'm not sure I managed it in a clear and concise way.


问:
Developing on a production server
Today I got yelled at for developing an application on a production server. Quote, "developing on a production server is not acceptable - ever!"

Here is the situation.

I set up a development instance: http://example.com:3000

The production instance is: http://example.com

I complete all my development work on http://example.com:3000 and when the client is pleased with the changes, I move them over to http://example.com.

The application I am working with is an old Ruby on Rails application, and I have to say that initially, I did try to set up an development environment locally, but I could never get it running. After trying for a while, I gave up and decided to develop on the production server.

Again, am I an idiot? Probably so, but I've been doing web development for a couple of years now, and I have never encountered a situation like this. Who is right and why?

答:
I'm quite astonished no one mentioned the most important reason yet, why it's absolutely forbidden to develop on production servers:

Don't mess with production data, which can happen oh so easily!

A tiny error in one place leads to gigantic troubles in other calculations and then, on the next day, all the data is garbage and the customer is pissed. This is much, much worse than a bug in the UI or a little crash here and there.

For most applications, the value lies in the data and not in the routines.

Title: Developing on a production server


问:
How do you organize your MVC framework while supporting modules/plugins?
There are a two main codebase structures that I have seen when it comes to MVC frameworks. The problem is that they both seem to have an organisational bug that goes with them.

Standard MVC

```<code>/controller
/model
/view
</code>```

Problem: No separation of related components (forum, blog, user, etc..)

Modular MVC

```<code>/blog
    /controller
    /model
    /view
/user
    /controller
    /model
    /view
/forum
    /controller
    /model
    /view
</code>```

Picking the module-based system leaves you with a problem.

Long names (Forum_Model_Forum = forum/model/forum.php) (Like Zend)

File system searches using is_file() to find which folder has the forum model? (Like Kohana)

Are their any other MVC structures that work well when trying to separate different modules? Are there benefits from these structures that I'm missing?

答:
Mathiases solution makes great sense
And using his folder structure does not prevent having pluggable content, for example adding an independent /gallery/ could look like this

```<code>WebClient
    /blog
        /controller
        /view
    /user (uses /model/User/)
       /controller
        /view
    /forum
        /controller
        /view
    /gallery
        /controller
        /view
        /model
CommandLineClient
    delete_spam_posts_script
RestApiClient

/model
    User
    BlogPost
    Comment
</code>```

Now we have a shared "model" and independent ones if necessary

Body:
Mathiases solution makes great sense
And using his folder structure does not prevent having pluggable content, for example adding an independent /gallery/ could look like this

WebClient
    /blog
        /controller
        /view
    /user (uses /model/User/)
       /controller
        /view
    /forum
        /controller
        /view
    /gallery
        /controller
        /view
        /model
CommandLineClient
    delete_spam_posts_script
RestApiClient

/model
    User
    BlogPost
    Comment

Now we have a shared "model" and independent ones if necessary


答:
It really bugs me how often developers falsely assume they should (and could) do the work of professional testers. This could probably only be compared to another notoriously bad intuition programmers have about performance. Every time I see developers breaking their heads on SQA matters, it feels as if restaurant guys worried about quality of products they use, decide to establish their own farm instead of looking for the right supplier.

Checkin to VCS is by design supposed to be reversible. Thus, it is only natural to checkin first, then do func-testing, then revert it if needed. That way VCS could have a documented trail of what was done and why, that can be greatly leveraged, helping future maintainers avoid repeating the same mistake again.

If there is an issue that multiple programmers can make it complicated by checking in concurrently, solution for that is, again,

not to avoid checkins but perform and test these in independent branches, then merge.

Given above, the question would be better phrased as, whether to do functional testing after each and every checkin. Taking into account that this is as a rule more time and effort-consuming than build checks and running unit tests, one would better think twice whether it is worth it.

I can easily imagine this making sense in mission critical software, but in 99.99% regular applications this is most likely an overkill.

Main consideration when deciding on what approach to take in functional testing is I believe to clearly understand that these matters are supposed to be of professional testing, not development.

Because of that, I think the most realistic solution would be to get to your testers (or hire them if you don't have QA at all 1, 2, 3) and check with them.

Quite sad that while it is widely understood that the right answer to legal questions is typically ask a lawyer, when it comes to matters clearly belonging to professional SQA, it is so rare to see an answer ask a tester. And it is particularly painful to think of consequences when developers waste their efforts doing wrong job. It comes at price, and the price is they have less time and focus to perform their primary duties, which in turn leads to worse design, code and unit tests and eventually to more bugs.

Title: Functional testing before code checkin


问:
GitHub OS project how to have a good version and a work in progress version
I have started my own OS application, I am hosting it on GitHub. My problem is that I push changes to the repository from more than one location so sometimes I want to work on it and sometimes I can't always finish something in time but I would still like to push it anyway so I can fetch it later from my other location. I'd like to be able to somehow have a stable version and have the master branch be a 'work in progress'.

How do I do this?

Is there some button I can push that will take the code from my master branch and make it into a zip file in my downloads tab and call it a version or should I do this by hand?

Would it be better to have the master branch be nice and neat and have a separate branch to play with and then merge the two when the time is right? Would this not cause more problems in the merging phase?

答:
You should (almost) always have a working master branch in git repositories.

That doesn't mean you can push to master only when you make a new release,
but it does mean you should use another branch when you are in the middle of implementing a new feature.

You merge new_feature to master after the feature is complete and tested.

Patches and new (feature) branches are normally based on master.

You could use a branch named stable,
since you can change which branch is the default branch shown in github.
However, stable is also frequently used as a branch that only receives changes for security fixes or similar of the currently stable release.

Either way, you should not rebase or push -f to "well-known" branches like master and stable, since that is often unexpected.
You can rebase in feature branches as much as you like and breaking things in feature branches is no big deal either.

Using feature branches is especially important when you want to open pull_requests on github.
After you opened a pull-request to merge one branch into some other branch,
you can't use that branch without your changes appearing in that pull-request.
This means you should only use the master branch if your repository is the main repository.
When you only have a fork and don't plan on making this a standalone project,
you should not use the master branch in your fork at all, only feature branches.


问:
Fundamental Difference between fn() and new fn() in javascript
In what all aspects, calling a function with and without new keyword differ in javascript?
I mean what all things are differing between?

testFn() vs new testFn()

答: new creates a new (empty) object and sets this to it, then calls the function, which acts as the constructor for the object (by manipulating this.something). Calling the same function without the new keyword would let it act on whatever this currently means.


问:
Why is it often said that the test cases need to be made before we start coding?
Why is it often said that the test cases need to be made before we start coding?

What are its pros and what the cons if we don't listen to this advice?

Moreover, does that advice refer to black box testing or White Box testing or both?

答:
Why is it often said that the test cases need to be made before we start coding?

There are a couple reasons why this is said.

Some people approach tests (blackbox) as contracts.  This forces the person writing the test and the person implementing the code to have a clear set of criteria for success. This means you write code to meet the contract and that's how you know when the functionality required is met.

TDD (Test Driven Development) is a practice where you drive all development through tests.  Classically this is done with unit tests, but more recently with tests at whatever level are appropriate to your product and process.

What are its pros and what the cons if we don't listen to this advice?

Pros

Drives out ambiguity earlier in the process because you must understand what the success criteria is before writing the test.

Some proponents suggest there are design benefits specifically to unit TDD because it enforces loose coupling and more modular design.

Confidence that your code is working (at least for the portions that are tested).

Cons

Understand how to write maintainable tests.

Understand how to write good tests.

Understand when to make the trade off between a very expensive good test and a low cost less good test.

More code to maintain

Moreover, does that advice refer to black box testing or White Box testing or both?

It depends.  Most unit tests tend to be more blackbox in that they will examine input and output of the method or function.  However, there are times when mocks or stubs are needed making it more of a whitebox test as it now requires information about the implementation.  It may be a moot point for the purposes of TDD because the developer is typically the one writing the tests.


答:
Sockets are one-to-one. You need multiple sockets if you want to send the same thing to multiple processes. With shared memory, you can have multiple readers, and also multiple writers.

Sockets are resource intensive. Each and every message goes through the OS. With shared memory, you map the shared memory but once into your application's memory and from then on it's your's to use. However, you still need to go through the OS when you used shared memory; see below.

Sockets are synchronized (so long as you don't use UDP). With shared memory, you almost inevitably need some additional mechanism to tell other processes that it is OK / not OK to read or write to the shared memory. Don't do this and you will run into problems with corrupted memory. Example: Suppose process A starts reading a chunk shared memory, but gets swapped out partway through the read. Process B writes to that same chunk of shared memory. When process A restarts and continues reading shared memory, what it has read in is a mishmash of old and new data. To prevent this, you still go through the OS when you are using shared memory.

It's fairly easy to convert a socket-based set of applications to one that uses network sockets. You can spread the processing to all the machines in your lab, or even further afield. just can't do this with shared memory. You are locked to one machine with a shared memory-based solution.

Sockets are intended for low volumes of data, shared memory for large volumes of data. The different mechanisms exist to solve different problems.

Title: What are the pros and cons of Inter process communication done via sockets vs shared memory?

Body:
I understand that two of the many more options for inter process communication can be :

Shared memory

Sockets

Actually I saw these two options being exposed by Intellij Idea for debugging a Java application . I want to know what are the pros and cons of each approach .


问:
OO Design related questions in technical interviews
I've been attending quite a few interviews recently and have been asked by companies to answer "design a [insert model]" questions more than a few times.

Is this normal in the industry nowadays? I've been in the software world for more than two  decades and have attended my share of interviews, but I am seeing this pattern in interviews emerge only recently.

I feel the question is very open ended. For example: I was asked to draw a class diagram to "Design a parking lot". I am not sure what level of detail the interviewer is expecting. This was in an online test where I was expected to attach a visio diagram, so I couldn't ask them what their expectations were.

Do you use these kind of questions in your interview process? Are they related to only class diagrams or do you also ask sequence, flowcharts and ERDs (ofcourse based on the nature of the position) Have they been effective in your hiring process?

* Edit for Kevin's response *

For example: A complete question could be "Design a parking lot management system that can be used to find vacant slots"

I can be done with 2 classes, ParkingLot and Slot or I could go on to add IVehicle and Vehicle and Car and Motorcycle classes. Where do I draw the line?

```<code>public class ParkingLot
{
   IVehicle Vehicle {set; get;}

   List<Slot> GetEmptySlots() { };
}

public class Vehicle : IVehicle
{
  Slot SlotNum {set; get;}
}

public class Slot
{
  int Row {set; get;}
  int Column {set; get; }
}
</code>```

答:
To some degree, yes. Anyone can recite syntax or copy/paste their way through a solution. We want to hire people who can solve problems.

They expect you to document the design sufficiently that they can understand it (and no more than that).

I ask people how they would solve XYZ problem, yes. Usually they just describe it verbally. I want to see if they ask questions to clarify requirements. I want to see how they communicate with other programmers. I want to see if they can think on their feet.

It has been helpful for me. I don't want code monkeys, I want software engineers.


问:
Javascript and proprietary algorithms
I'll be quite to the point, is there any way to make Javascript a bit more concealed than it usually is or is Javascript always out and open if you look in the source code ?

This is about hiding proprietary algorithms that would dispense a service that does not exist yet (to my knowledge) on the market and is not really straightforward. I know that patenting is possible but let's leave this out of the question.

答:
Well you can "obfuscate" the code by removing all recognizable names that are not essential to the working of the code.  (And minification is a good approximation to obfuscation.)

However, the fact remains that Javascript must be delivered (to the user's browser) as source code that is ultimately compilable and executable by the browser.  That means that someone who controls the browser will always be able to reverse engineer any "secrets" embedded in the code ... and that includes secret algorithms.

(Incidentally, this applies to ALL methods of delivering algorithms.  If you don't control the execution platform, any mechanism for protecting or hiding a secret algorithm can be broken ... given sufficient time and motivation.)

The solution is to not embed the algorithms.  Keep them server side and have the browser make a call to the server to run them.

Alternatively, use a legal solution: require all users to sign a legally enforceable agreement that has "teeth" ... and enforce it vigorously!  (WARNING: this won't make you popular with your users ...)

Title: Javascript and proprietary algorithms


答:
I used to ask these - back when we created class diagrams for code generation.  I still do on occasion, but not routinely.  I like the question because it lets me see the person think.

It is intended to be open ended.  That's ok.  There isn't one right answer.  I don't have an answer in my mind; I want to see where it leads.  I think it's a better question to ask in person, not "email in answer."  It's about communication, assumptions and interaction; not just an answer!

Title: OO Design related questions in technical interviews

Body:
I've been attending quite a few interviews recently and have been asked by companies to answer "design a [insert model]" questions more than a few times.

Is this normal in the industry nowadays? I've been in the software world for more than two  decades and have attended my share of interviews, but I am seeing this pattern in interviews emerge only recently.

I feel the question is very open ended. For example: I was asked to draw a class diagram to "Design a parking lot". I am not sure what level of detail the interviewer is expecting. This was in an online test where I was expected to attach a visio diagram, so I couldn't ask them what their expectations were.

Do you use these kind of questions in your interview process? Are they related to only class diagrams or do you also ask sequence, flowcharts and ERDs (ofcourse based on the nature of the position) Have they been effective in your hiring process?

* Edit for Kevin's response *

For example: A complete question could be "Design a parking lot management system that can be used to find vacant slots"

I can be done with 2 classes, ParkingLot and Slot or I could go on to add IVehicle and Vehicle and Car and Motorcycle classes. Where do I draw the line?

```<code>public class ParkingLot
{
   IVehicle Vehicle {set; get;}

   List<Slot> GetEmptySlots() { };
}

public class Vehicle : IVehicle
{
  Slot SlotNum {set; get;}
}

public class Slot
{
  int Row {set; get;}
  int Column {set; get; }
}
</code>```


问:
Restrict access to backend
This might be one of those "not answerable" or "just opinions"-questions but I thought I'd give it a shot.

I'm developing an app with health care information with a friend who's a doctor. The basics of app are done and the information in the database is shaping up so now I've come to the question of wether, and if so how, I should restrict access to that information to just my app. The question of if is one I can answer, but any opinions are welcome. The question of how is where I need your help.

The app is written in Java on Android and the backend in Django, what ways do you see for restricting access to the backend so that other scripts/apps can't access it? One idea I had was for the phone to request an api key on first start and bind it to the IMIE number which I think is unique for each phone, then keep track of those tuples on the server.
We(as in I) will likely port this to iOS at some stage, so it needs to be fairly cross-platform, I thought about binding to google accounts instead of IMIE number before.

答:
While you may be ways how to make it harder the general answer is no (what you are describing is similar in idea to DRM). You must assume that whoever have the application on their phone is able to reverse engineer it and (by definition) have all the necessary keys/passwords.

What you may do is restrict access to certain account by using authentication in similar way stackexchange is restricting access to your account only to you (but cannot restrict you to single application - I can fake the IE request by using telnet). Hence try to check in backend for user and be prepared for (potentially) malicious input from user who tried another application.

As last notes:

you want to connect by https of course.

check the regulations regarding handling medical data. While IANAL and I've never been in medical-related industry I do know that in some jurisdictions there are laws regarding handling such data and if procedures are not followed you (or your friend) might be in troubles even if nothing will happen.

while spoofing IMIE numbers is not legal in many places it is likely to be trivial to spoof it by using Android VM. Also IIRC IMIE is broadcasted through GSM network which crypto is broken for the last 20 years or so (so it can be assumed to be transmitted as plaintext).

Title: Restrict access to backend


问:
Great Lunch and Learn Topics
We recently revived the lunch in learns for the programming department in the company I work for. We were all asked if we had any ideas for a session, and if we would be interested in doing a presentation. I've had a few ideas ranging from various topics such as:

How to think like a user when designing UI

or Differences in HTML5

A few coworkers I tossed these ideas around to seem to like them. However, I'd like some more ideas before I dig too far into creating a presentation.

What are some great lunch and learn topics?

答: Inversion of Control and Dependency Injection are powerful ideas that need to be much more widespread than they currently are.</p>

Title: Great Lunch and Learn Topics


问:
Which past version of Netbeans IDE that has lightness almost equal or better than Eclipse Indigo?
Currently, I'm a long Eclipse user because my past and current companies always deal with eclipse. Recently I met some example java codes created using netbeans. I downloaded and tried Netbeans 7.x and 6.9.x, but they're more heavier and eating memory resources than Eclipse Indigo.

So anyone know which past version of Netbeans IDE that has lightness almost equal to or better than Eclipse Indigo (3.7) but can support Java SDK v1.6?

答:
Whether one IDE is more lightweight than another is pretty subjective.  Do you have the identical features running etc?  Even then it's not a like for like comparison.  Couple of workarounds:

The two IDEs both feature importers that will allow you to bounce projects back an forth - most of my projects run in all three major IDEs.

You can performance tune your IDE, take a look at what Java heap settings they both start with and run a quick GC analysis on them when you do project work.  You've be amazed what a few command line parameter changes can do.

Good hardware is comparatively cheap.  SSD Drive + 8 GB of RAM should see almost any IDE happy.


问:
Why are cryptic short identifiers still so common in low-level programming?
There used to be very good reasons for keeping instruction / register names short. Those reasons no longer apply, but short cryptic names are still very common in low-level programming.

Why is this? Is it just because old habits are hard to break, or are there better reasons?

For example:

Atmel ATMEGA32U2 (2010?): TIFR1 (instead of TimerCounter1InterruptFlag), ICR1H (instead of InputCapture1High), DDRB (instead of DataDirectionPortB), etc.

.NET CLR instruction set (2002): bge.s (instead of branch-if-greater-or-equal.short), etc.

Aren't the longer, non-cryptic names easier to work with?

When answering and voting, please consider the following. Many of the possible explanations suggested here apply equally to high-level programming, and yet the consensus, by and large, is to use non-cryptic names consisting of a word or two (commonly understood acronyms excluded).

Also, if your main argument is about physical space on a paper diagram, please consider that this absolutely does not apply to assembly language or CIL, plus I would appreciate if you show me a diagram where terse names fit but readable ones make the diagram worse. From personal experience at a fabless semiconductor company, readable names fit just fine, and result in more readable diagrams.

What is the core thing that is different about low-level programming as opposed to high-level languages that makes the terse cryptic names desirable in low-level but not high-level programming?

答:
Humans read and write assembly only occasionally, and most of the time it's just a communication protocol. I.e., it is most often used as an intermediate serialised text-based representation between compiler and assembler. The more verbose this representation is, the more unnecessary overhead is in this protocol.

In the case of opcodes and register names, long names actually harm readability. Short mnemonics are better for a communication protocol (between compiler and assember), and assembly language is a communication protocol most of the time. Short mnemonics are better for programmers, since compiler code is easier to read.


答: These variants are syntactically different: with "new" variant supposes that the function is a constructor. The variant without "new" supposes, that it is not a constructor.

Title: Fundamental Difference between fn() and new fn() in javascript

Body:
In what all aspects, calling a function with and without new keyword differ in javascript?
I mean what all things are differing between?

testFn() vs new testFn()