问:
How do you identify bugfix commits on QA environment with Git repository?
I got used to the following approach on bugfixing phase of the project development. The developer should add SVN commit number as a comment to the JIRA issue when resolving it. Latest artifact from CI-server shows build number which include major version, branch name and commit number. This approach helps QA easily to identify whether the bugfix was included in the latest build or not. Even when same issue was reopened and fixed again.

After moving from SVN to Git we lost incremental commit number. It is possible to solve this problem with tagging the code but tags are tied to the sprint numbers. And in case of the issue reopening this approach moves this issue resolving on the next sprint. But client is dissatisfied with the fact of having certain issue unfixed for a several sprints.

So, how do you identify bugfix commits in for QA environment?
Thanks.

UPD: The question is NOT about linking issues to commits, but about ability of QAs figure out whether certain fix (ticket) is included in certain build just by looking on build number and ticket comments.

答:
How about using tags to mark the commits ?

See this post about another user moving from SVN to GIT and facing similar issues to you, e.g. "As the svn revisions are simple numbers we can use them to extend the version numbers of our plugins and SDK builds"

More info at How do you achieve a numeric versioning scheme with Git?


问:
Is it necessary to map integers to bits in a genetic algorithm?
From what I've read, genetic algorithms are usually (always?) applied to chromosomes of bits. So if a problem involves maximizing a function that takes integer values, the integers are first encoded as bits.

Is this mapping necessary? It seems that you could take chromosomes of integers and apply crossover and mutation directly. So, if I have a function that takes 35 integer inputs, I can just apply the genetic operators to those integers, rather than on the 35xB bits (where B is the number of bits needed to encode an integer). Is there a reason this isn't done?

Perhaps the algorithm would suffer because the problem is defined more coarsely (that is, a problem can be defined with shorter chromosomes if we're not using bits), but I'm curious if anyone has a better answer.

答:
The mapping is not necessary.

Differential evolution (DE) is a very successful "subset" of the broader space of genetic algorithms.

The first big change is that DE is using actual real/integer numbers instead of bit strings (usually real numbers for numerical optimization, integers in other fields).

Anyway it's nice to be able to represent things as actual numbers.

It's a way to use computer resources efficiently and also makes input and output transparent for the user: parameters can be input, manipulated and output as ordinary numbers without ever being reformatted as genes with a different binary representation.

For the problem of being "defined more coarsely", DE adopts modified mutation / crossover operators that make use of the difference between two or more integer/real vectors in the population to create a new vector (e.g. by adding some random proportion of the difference to one of the existing vectors, plus a small amount of random noise).

From Differential Evolution - A Practical Approach to Global Optimization

OwnerDisplayName: itzy

ContentLicense: CC BY-SA 3.0


问:
"Hub" which executes interface methods on all registered instances
Is it possible to have a generic class (let's name it Hub) which implements:

- interface T

- has method named Add (not a part or interface T)

And now calling Add allows me to store any instance of T in internal list.

And finally when I use a method XYZ from interface T on my Hub class, for example: Hub.XYZ(1), it will fire a method XYZ with parameter 1 on all instances registered in my internal list.

Example:

```<code>var hub = Hub<IDisposable>();
hub.Add (new SomeClassA());
hub.Add (new SomeClassB());
hub.Add (new SomeClassC());

hub.Dispose(); // it will call Dispose on all 3 registered instances
</code>```

答:
You can't do it using exactly this syntax, because generic parameters can't change what interfaces does your class implement (i.e. you can't write something like class Hub<T> : T).

I can see two alternative ways to do this (there are probably others):

A simple approach using lambdas

Your Hub class would have a method like void Execute(Action<T> action), which would execute the given action for all items in it.

With this, your code would become:

```<code>var hub = new Hub<IDisposable>();

hub.Add(new SomeClassA());
hub.Add(new SomeClassB());
hub.Add(new SomeClassC());

hub.Execute(x => x.Dispose());
</code>```

The implementation of Hub could look something like:

```<code>public class Hub<T>
{
    private readonly List<T> items = new List<T>();

    public void Add(T item)
    {
        items.Add(item);
    }

    public void Execute(Action<T> action)
    {
        foreach (var item in items)
        {
            action(item);
        }
    }
}
</code>```

A complicated approach using metaprogramming, that results in a slightly simpler syntax

Another way would be to have a property of the interface type on your Hub, which would actually return a type generated at runtime that executes the action for all items. To generate such type, you could use something like Castle DynamicProxy, or do it manually using Reflection.Emit.

With this, your code would look like this:

```<code>var hub = new Hub<IDisposable>();

hub.Add(new SomeClassA());
hub.Add(new SomeClassB());
hub.Add(new SomeClassC());

hub.Instance.Dispose();
</code>```

The code for Hub using DynamicProxy is actually simpler than I expected:

```<code>public class Hub<T>
    where T : class
{
    private readonly List<T> items;
    private readonly T instance;

    public Hub()
    {
        items = new List<T>();
        var interceptor = new HubInterceptor(items);
        instance = new ProxyGenerator().CreateInterfaceProxyWithoutTarget<T>(interceptor);
    }

    public T Instance { get { return instance; } }

    public void Add(T item)
    {
        items.Add(item);
    }

    private class HubInterceptor : IInterceptor
    {
        private readonly IEnumerable<T> targets;

        public HubInterceptor(IEnumerable<T> targets)
        {
            this.targets = targets;
        }

        public void Intercept(IInvocation invocation)
        {
            foreach (var target in targets)
            {
                invocation.Method.Invoke(target, invocation.Arguments);
            }
        }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can't do it using exactly this syntax, because generic parameters can't change what interfaces does your class implement (i.e. you can't write something like class Hub<T> : T).

I can see two alternative ways to do this (there are probably others):

A simple approach using lambdas

Your Hub class would have a method like void Execute(Action<T> action), which would execute the given action for all items in it.

With this, your code would become:

var hub = new Hub<IDisposable>();

hub.Add(new SomeClassA());
hub.Add(new SomeClassB());
hub.Add(new SomeClassC());

hub.Execute(x => x.Dispose());

The implementation of Hub could look something like:

public class Hub<T>
{
    private readonly List<T> items = new List<T>();

    public void Add(T item)
    {
        items.Add(item);
    }

    public void Execute(Action<T> action)
    {
        foreach (var item in items)
        {
            action(item);
        }
    }
}

A complicated approach using metaprogramming, that results in a slightly simpler syntax

Another way would be to have a property of the interface type on your Hub, which would actually return a type generated at runtime that executes the action for all items. To generate such type, you could use something like Castle DynamicProxy, or do it manually using Reflection.Emit.

With this, your code would look like this:

var hub = new Hub<IDisposable>();

hub.Add(new SomeClassA());
hub.Add(new SomeClassB());
hub.Add(new SomeClassC());

hub.Instance.Dispose();

The code for Hub using DynamicProxy is actually simpler than I expected:

public class Hub<T>
    where T : class
{
    private readonly List<T> items;
    private readonly T instance;

    public Hub()
    {
        items = new List<T>();
        var interceptor = new HubInterceptor(items);
        instance = new ProxyGenerator().CreateInterfaceProxyWithoutTarget<T>(interceptor);
    }

    public T Instance { get { return instance; } }

    public void Add(T item)
    {
        items.Add(item);
    }

    private class HubInterceptor : IInterceptor
    {
        private readonly IEnumerable<T> targets;

        public HubInterceptor(IEnumerable<T> targets)
        {
            this.targets = targets;
        }

        public void Intercept(IInvocation invocation)
        {
            foreach (var target in targets)
            {
                invocation.Method.Invoke(target, invocation.Arguments);
            }
        }
    }
}


问:
Unit Testing large controller actions
I've a web page that has many constituent parts.

On some user action, a POST operation is made, which then returns JSON to update the page.  The problem is that this JSON payload contains a lot of information built from many different operations and classes.  The JSON data is used then to update a number of partial views via the Ajax callback.

My question is, what is the best way of unit testing this?  Should this one action method even be responsible for collating all this information and returning in one chunk, or should it be done via a number of Html calls to different actions from the web page?  That would I think be easier to unit test.

Currently I may write 8 tests against a single action which I generally have to mock a number of operations which are not needed for some tests.

答:
In my opinion Actions should be relatively small and delegate work to other objects. Actions should (again, in my opinion) simply be responsible for the following:

Receiving the request

Delegate work to other objects

Return the result in the correct format

If you do this then unit testing becomes much easier through the use of mock objects and Dependency Injenction. Each object can then be unit tested independently.

I can write up a small code sample later if needed.

Title: Unit Testing large controller actions


答:
C# delegates already do this.

```<code>var hub = Action<int>();
hub += new SomeClassA().XYZ;
hub += new SomeClassB().XYZ;
hub += new SomeClassC().XYZ;
hub(1);
</code>```

Better yet, you don't actually need the different classes to have a common interface. As long as you specify some function that takes an int and returns void then Action<int> works.

The problem with this implementation is that the functions are executed in order. If an exception happens in one, the chain stops, and you don't know where. The alternative is to build a class that keeps the delegates(or an instance of your interface) in a list, calling them in turn.

Title: "Hub" which executes interface methods on all registered instances

Body:
Is it possible to have a generic class (let's name it Hub) which implements:

- interface T

- has method named Add (not a part or interface T)

And now calling Add allows me to store any instance of T in internal list.

And finally when I use a method XYZ from interface T on my Hub class, for example: Hub.XYZ(1), it will fire a method XYZ with parameter 1 on all instances registered in my internal list.

Example:

```<code>var hub = Hub<IDisposable>();
hub.Add (new SomeClassA());
hub.Add (new SomeClassB());
hub.Add (new SomeClassC());

hub.Dispose(); // it will call Dispose on all 3 registered instances
</code>```

Body:
C# delegates already do this.

var hub = Action<int>();
hub += new SomeClassA().XYZ;
hub += new SomeClassB().XYZ;
hub += new SomeClassC().XYZ;
hub(1);

Better yet, you don't actually need the different classes to have a common interface. As long as you specify some function that takes an int and returns void then Action<int> works.

The problem with this implementation is that the functions are executed in order. If an exception happens in one, the chain stops, and you don't know where. The alternative is to build a class that keeps the delegates(or an instance of your interface) in a list, calling them in turn.


问:
TCP Max SEQ number +1
I'm reading about TCP at the moment and there is a maximum sequence number 2 ^ 32, my question is what happens when the other host tries to send an acknowledgement for that sequence number 2 ^ 32 + 1?

Does TCP handle this by resetting or does it just crash out?

(Also bonus question, is the first sequence number generated at random?, I keep reading different things about it)

答:
The sequence numbers in TCP wrap around. This means that after 2^32-1 (4294967295), the sequence numbers continue with 0.

You might think that this could pose problems with distinguishing between old and new data with the same sequence number, but that doesn't happen, because TCP also has the concept of a window of acceptable sequence numbers and that window is at most 2^16 sequence numbers wide. This means that long before you need to re-use sequence numbers, they have fallen outside the window of acceptable sequence numbers.

The initial sequence number can be selected in multiple ways.

The original TCP specification leaves it fairly open, but does specify that the initial sequence number should not have been used in a preceding connection (on the same port) in the last few hours. One example given is that the initial sequence numbers are chosen based on a bit-clock with a period of 4.55 hours (after that time the sequence numbers start to repeat).

It is also possible to select the initial sequence numbers more randomly, as long as there is no chance that the packets of the new connection can't be confused with those from a previous connection.

Title: TCP Max SEQ number +1


答:
If a method is too large to effectively unit test- meaning it is most likely doing too many things for one method- then there are two approaches you can take:

Split the method into several methods to be called sequentially

Abstract parts of its functionality behind other methods

In your question you seem to focus on 1, but most of the time, 2 will be the better option, and in this case you're already aware of the problems that 1 causes- you'd have to make extra calls from the browser to the server, for example.

There's two ways you can extract methods, either to private methods on the same class, or public methods on another class. Private methods don't help with unit testing, so generally as long as you're able to make cohesive classes for the extracted methods which make sense and follows SOLID principles, then that's the best bet. This is very commonly done in MVC, which is why people talk about having thin controllers- the meaty work is done by service classes which the controllers call out to.

From there, you can use the usual unit testing technique of mocking to test your now much smaller methods in isolation from their dependencies.

Title: Unit Testing large controller actions

Body:
I've a web page that has many constituent parts.

On some user action, a POST operation is made, which then returns JSON to update the page.  The problem is that this JSON payload contains a lot of information built from many different operations and classes.  The JSON data is used then to update a number of partial views via the Ajax callback.

My question is, what is the best way of unit testing this?  Should this one action method even be responsible for collating all this information and returning in one chunk, or should it be done via a number of Html calls to different actions from the web page?  That would I think be easier to unit test.

Currently I may write 8 tests against a single action which I generally have to mock a number of operations which are not needed for some tests.


问:
Why do most programming languages have special keyword or syntax for declaring functions?
Most programming languages (both dynamically and statically typed languages) have special keyword and/or syntax that looks much different than declaring variables for declaring functions. I see functions as just as declaring another named entity:

For example in Python:

```<code>x = 2
y = addOne(x)
def addOne(number):
  return number + 1
</code>```

Why not:

```<code>x = 2
y = addOne(x)
addOne = (number) =>
  return number + 1
</code>```

Similarly, in a language like Java:

```<code>int x = 2;
int y = addOne(x);

int addOne(int x) {
  return x + 1;
}
</code>```

Why not:

```<code>int x = 2;
int y = addOne(x);
(int => int) addOne = (x) => {
  return x + 1;
}
</code>```

This syntax seems more natural way of declaring something (be it a function or a variable) and one less keyword like def or function in some languages. And, IMO, it is more consistent (I look in the same place to understand the type of a variable or function) and probably makes the parser/grammar a little bit simpler to write.

I know very few languages uses this idea (CoffeeScript, Haskell) but most common languages have special syntax for functions (Java, C++, Python, JavaScript, C#, PHP, Ruby).

Even in Scala, which supports both ways (and has type inference), it more common to write:

```<code>def addOne(x: Int) = x + 1
</code>```

Rather than:

```<code>val addOne = (x: Int) => x + 1
</code>```

IMO, atleast in Scala, this is probably the most easily understandable version but this idiom is seldom followed:

```<code>val x: Int = 1
val y: Int = addOne(x)
val addOne: (Int => Int) = x => x + 1
</code>```

I am working on my own toy language and I am wondering if there are any pitfalls if I design my language in such a way and if there are any historical or technical reasons this pattern is not widely followed?

答:
Well, the reason might be, that those languages are not functional enough, so to say. In other words, you rather seldomly define functions. Thus, the use of an extra key word is acceptable.

In languages of the ML or Miranda heritage, OTOH, you define functions most of the time. Look at some Haskell code, for instance. It's literally mostly a sequence of function definitions, many of those have local functions and local functions of those local functions. Hence, a fun keyword in Haskell would be a mistake as great as requiring an assingment statement in an imperative language to start with assign. Cause assignment is probably by far the single most frequent statement.


答:
The general command that immediately jumps out at me is git branch --contains. Obviously that needs to be checked explicitly rather than at a glance.

But as long as you have at least one tag in your entire history and keep your history largely free of rebases, git describe --tags will give you a linear version.

Title: How do you identify bugfix commits on QA environment with Git repository?

Body:
I got used to the following approach on bugfixing phase of the project development. The developer should add SVN commit number as a comment to the JIRA issue when resolving it. Latest artifact from CI-server shows build number which include major version, branch name and commit number. This approach helps QA easily to identify whether the bugfix was included in the latest build or not. Even when same issue was reopened and fixed again.

After moving from SVN to Git we lost incremental commit number. It is possible to solve this problem with tagging the code but tags are tied to the sprint numbers. And in case of the issue reopening this approach moves this issue resolving on the next sprint. But client is dissatisfied with the fact of having certain issue unfixed for a several sprints.

So, how do you identify bugfix commits in for QA environment?
Thanks.

UPD: The question is NOT about linking issues to commits, but about ability of QAs figure out whether certain fix (ticket) is included in certain build just by looking on build number and ticket comments.


问:
Best Git workflow suitable for our needs
I need help with the workflow that is best suitable for our needs. We are a 3-4 person team and are working on 4 different projects.

We have three main branches:

master - deployable production branch

staging - features under QA on live data

dev - features under QA on test data

Then for each feature, we create a feature branch

What we need:

Sometimes we would like to create a release (for many features that have something in common) and would be deployed in the end of the month.

Sometimes we would like to deploy a specific feature/change (without creating a release). This is what we do most of the time.

Now to the workflow:

I start working on some feature. I create a feature branch off from dev.

I finish my feature (with 30 commits).

I squash merge my feature into dev - so it becomes just one commit.

The feature is automatically deployed to a testing environment and QA tests out my feature on test data.

The feature tested OK, so I cherry-pick my feature commit hash to a staging branch. The feature is automatically deployed to a staging environment and QA tests out my feature on live data.

The feature passes QA (test and staging) and is either cherry-picked to master or to a release branch, which will be merged with master in the end of the month.

Here's a picture explaining what I have in mind:

Does this all make sense? Is there a better way to achieve this goal? Thanks for your time.

答:
Because we have to deploy specific features on testing and staging environments, I was thinking about something like:

Two main branches:

master

dev

Feature branches are branched from dev

When a feature is ready for testing, we add a tag testing/ISSUE-1234

TeamCity notices the tag and deployes to testing environment

When the feature passes testing, we add a tag staging/ISSUE-1234

TeamCity notices the tag and deployes to staging environment

When the feature passes staging, we make a pull request to dev branch and someone reviews code and logic.

If the code review went well, he merges the branch into dev.

On a monthly basis we merge the dev branch into master

How does this sound?


问:
When and how should I use exceptions?

The Setting

I often have trouble determining when and how to use exceptions. Let's consider a simple example: suppose I am scraping a webpage, say "http://www.abevigoda.com/", to determine if Abe Vigoda is still alive. To do this, all we need to do is download the page and look for times that the phrase "Abe Vigoda" appears. We return the first appearance, since that includes Abe's status. Conceptually, it will look like this:

```<code>def get_abe_status(url):
    # download the page
    page = download_page(url)

    # get all mentions of Abe Vigoda
    hits = page.find_all_mentions("Abe Vigoda")

    # parse the first hit for his status
    status = parse_abe_status(hits[0])

    # he's either alive or dead
    return status == "alive"
</code>```

Where parse_abe_status(s) takes a string of the form "Abe Vigoda is something" and returns the "something" part.

Before you argue that there are much better and more robust ways of scraping this page for Abe's status, remember that this is just a simple and contrived example used to highlight a common situation I'm in.

Now, where can this code encounter problems? Among other errors, some "expected" ones are:

download_page might not be able to download the page, and throws an IOError.

The URL might not point to the right page, or the page is downloaded incorrectly, and so there are no hits. hits is the empty list, then.

The web page has been altered, possibly making our assumptions about the page wrong. Maybe we expect 4 mentions of Abe Vigoda, but now we find 5.

For some reasons, hits[0] might not be a string of the form "Abe Vigoda is something", and so it cannot be correctly parsed.

The first case isn't really a problem for me: an IOError is thrown and can be handled by the caller of my function. So let's consider the other cases and how I might handle them. But first, let's assume that we implement parse_abe_status in the stupidest way possible:

```<code>def parse_abe_status(s):
    return s[13:]
</code>```

Namely, it doesn't do any error checking. Now, on to the options:

Option 1: Return None

I can tell the caller that something went wrong by returning None:

```<code>def get_abe_status(url):
    # download the page
    page = download_page(url)

    # get all mentions of Abe Vigoda
    hits = page.find_all_mentions("Abe Vigoda")

    if not hits:
        return None

    # parse the first hit for his status
    status = parse_abe_status(hits[0])

    # he's either alive or dead
    return status == "alive"
</code>```

If the caller receives None from my function, he should assume that there were no mentions of Abe Vigoda, and so something went wrong. But this is pretty vague, right? And it doesn't help the case where hits[0] isn't what we thought it was.

On the other hand, we can put in some exceptions:

Option 2: Using Exceptions

If hits is empty, an IndexError will be thrown when we attempt hits[0]. But the caller shouldn't be expected to handle an IndexError thrown by my function, since he has no idea where that IndexError came from; it could have been thrown by find_all_mentions, for all he knows. So we'll create a custom exception class to handle this:

```<code>class NotFoundError(Exception):
    """Throw this when something can't be found on a page."""

def get_abe_status(url):
    # download the page
    page = download_page(url)

    # get all mentions of Abe Vigoda
    hits = page.find_all_mentions("Abe Vigoda")

    try:
        hits[0]
    except IndexError:
        raise NotFoundError("No mentions found.")

    # parse the first hit for his status
    status = parse_abe_status(hits[0])

    # he's either alive or dead
    return status == "alive"
</code>```

Now what if the page has changed and there are an unexpected number of hits? This isn't catastrophic, as the code may still work, but a caller might want to be extra careful, or he might want to log a warning. So I'll throw a warning:

```<code>class NotFoundError(Exception):
    """Throw this when something can't be found on a page."""

def get_abe_status(url):
    # download the page
    page = download_page(url)

    # get all mentions of Abe Vigoda
    hits = page.find_all_mentions("Abe Vigoda")

    try:
        hits[0]
    except IndexError:
        raise NotFoundError("No mentions found.")

    # say we expect four hits...
    if len(hits) != 4:
        raise Warning("An unexpected number of hits.")
        logger.warning("An unexpected number of hits.")

    # parse the first hit for his status
    status = parse_abe_status(hits[0])

    # he's either alive or dead
    return status == "alive"
</code>```

Lastly, we might find that status isn't either alive or dead. Maybe, for some odd reason, today it turned out to be comatose. Then I don't want to return False, as that implies that Abe is dead. What should I do here? Throw an exception, probably. But what kind? Should I create a custom exception class?

```<code>class NotFoundError(Exception):
    """Throw this when something can't be found on a page."""

def get_abe_status(url):
    # download the page
    page = download_page(url)

    # get all mentions of Abe Vigoda
    hits = page.find_all_mentions("Abe Vigoda")

    try:
        hits[0]
    except IndexError:
        raise NotFoundError("No mentions found.")

    # say we expect four hits...
    if len(hits) != 4:
        raise Warning("An unexpected number of hits.")
        logger.warning("An unexpected number of hits.")

    # parse the first hit for his status
    status = parse_abe_status(hits[0])

    if status not in ['alive', 'dead']:
        raise SomeTypeOfError("Status is an unexpected value.")

    # he's either alive or dead
    return status == "alive"
</code>```

Option 3: Somewhere in between

I think that the second method, with exceptions, is preferable, but I'm not sure if I'm using exceptions correctly within it. I'm curious to see how more experienced programmers would handle this.

答:
The accepted answer deserves to be accepted and answers the question, I write this only to provide a bit of extra background.

One of Python's credos is: it's easier to ask forgiveness than permission. This means that typically you just do things, and if you expect exceptions, you handle them. As opposed to doing if checks before hand to make sure you won't get an exception.

I want to provide an example to show you how dramatic the difference is in mentality from C++/Java. A for loop in C++ typically looks something like:

```<code>for(int i = 0; i != myvector.size(); ++i) ...
</code>```

A way to think about this: accessing myvector[k] where k >= myvector.size() will cause an exception. So you could in principle write this (very awkwardly) as a try-catch.

```<code>    for(int i = 0; ; ++i)  {
        try {
           ...
        } catch (& std::out_of_range)
             break
</code>```

Or something similar. Now, consider what's happening in a python for loop:

```<code>for i in range(1):
    ...
</code>```

How is this working? The for loop takes the result of range(1) and calls iter() on it, grabbing an iterator to it.

```<code>b = range(1).__iter__()
</code>```

Then it calls next on it at each loop iteration, until...:

```<code>>>> next(b)
0
>>> next(b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
</code>```

In other words, a for loop in python is actually a try-except in disguise.

As far as the concrete question goes, remember that exceptions stop normal function execution and must be dealt with separately. In Python, you should freely throw them whenever there is no point executing the rest of the code in your function, and/or none of the returns correctly reflect what happened in the function. Note that returning early from a function is different: returning early means you already figured out the answer and don't need the rest of the code to figure out the answer. I am saying that exceptions should be thrown when the answer is not known, and the rest of the code to determine the answer cannot be reasonably run. Now, "correctly reflect" itself, like which exceptions you choose to throw, is all a matter of documentation.

In the case of your particular code, I would say any situation that causes hits to be an empty list should throw. Why? Well, the way your function is setup, there is no way to determine the answer without parsing hits. So if hits is not parseable, either because the URL is bad, or because hits is empty, then the function can't answer the question, and in fact can't even really try to.

In this particular case, I would argue that even if you manage to parse and don't get a reasonable answer (alive or dead), then you should still throw. Why? Because, the function returns a boolean. Returning None is very dangerous to your client. If they do an if check on None, there won't be failure, it will just silently be treated as False. So, your client will basically always have to do an if is None check anyhow if he doesn't want silent failures... so you should probably just throw.

Title: When and how should I use exceptions?

Body:
The accepted answer deserves to be accepted and answers the question, I write this only to provide a bit of extra background.

One of Python's credos is: it's easier to ask forgiveness than permission. This means that typically you just do things, and if you expect exceptions, you handle them. As opposed to doing if checks before hand to make sure you won't get an exception.

I want to provide an example to show you how dramatic the difference is in mentality from C++/Java. A for loop in C++ typically looks something like:

for(int i = 0; i != myvector.size(); ++i) ...

A way to think about this: accessing myvector[k] where k >= myvector.size() will cause an exception. So you could in principle write this (very awkwardly) as a try-catch.

    for(int i = 0; ; ++i)  {
        try {
           ...
        } catch (& std::out_of_range)
             break

Or something similar. Now, consider what's happening in a python for loop:

for i in range(1):
    ...

How is this working? The for loop takes the result of range(1) and calls iter() on it, grabbing an iterator to it.

b = range(1).__iter__()

Then it calls next on it at each loop iteration, until...:

>>> next(b)
0
>>> next(b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

In other words, a for loop in python is actually a try-except in disguise.

As far as the concrete question goes, remember that exceptions stop normal function execution and must be dealt with separately. In Python, you should freely throw them whenever there is no point executing the rest of the code in your function, and/or none of the returns correctly reflect what happened in the function. Note that returning early from a function is different: returning early means you already figured out the answer and don't need the rest of the code to figure out the answer. I am saying that exceptions should be thrown when the answer is not known, and the rest of the code to determine the answer cannot be reasonably run. Now, "correctly reflect" itself, like which exceptions you choose to throw, is all a matter of documentation.

In the case of your particular code, I would say any situation that causes hits to be an empty list should throw. Why? Well, the way your function is setup, there is no way to determine the answer without parsing hits. So if hits is not parseable, either because the URL is bad, or because hits is empty, then the function can't answer the question, and in fact can't even really try to.

In this particular case, I would argue that even if you manage to parse and don't get a reasonable answer (alive or dead), then you should still throw. Why? Because, the function returns a boolean. Returning None is very dangerous to your client. If they do an if check on None, there won't be failure, it will just silently be treated as False. So, your client will basically always have to do an if is None check anyhow if he doesn't want silent failures... so you should probably just throw.


答:
For some languages functions are not values. In such a language to say that

```<code>val f = << i : int  ... >> ;
</code>```

is a function definition, whereas

```<code>val a = 1 ;
</code>```

declares a constant, is confusing because you are using one syntax to mean two things.

Other languages, such as ML, Haskell, and Scheme treat functions as 1st class values, but provide the user with a special syntax for declaring function valued constants.*  They are applying the rule that "usage shortens form". I.e. if a construct is both common and verbose, you should give the user a shorthand.  It is inelegant to give the user two different syntaxes that mean exactly the same thing; sometimes elegance should be sacrificed to utility.

If, in your language, functions are 1st class, then why not try to find a syntax that is concise enough that you won't be tempted to find a syntactic sugar?

-- Edit --

Another issue no one has brought up (yet) is recursion.  If you allow

```<code>{
    val f = << i : int ... g(i-1) ... >> ;
    val g = << j : int ... f(i-1) ... >> ;
    f(x)
}
</code>```

and you allow

```<code>{
    val a = 42 ;
    val b = a + 1 ;
    a
} ,
</code>```

does it follow that you should allow

```<code>{
    val a = b + 1 ;
    val b = a - 1 ;
    a
} ?
</code>```

In a lazy language (like Haskell), there is no issue here. In an language with essentially no static checks (like LISP), there is no issue here. But in a statically-checked eager language, you have to be careful about how the rules of static checking are defined, if you want to allow the first two and forbid the last.

-- End of Edit --

*It might be argued that Haskell does not belong in this list. It provides two ways to declare a function, but both are, in a sense, generalizations of the syntax for declaring constants of other types

Title: Why do most programming languages have special keyword or syntax for declaring functions?

Body:
Most programming languages (both dynamically and statically typed languages) have special keyword and/or syntax that looks much different than declaring variables for declaring functions. I see functions as just as declaring another named entity:

For example in Python:

```<code>x = 2
y = addOne(x)
def addOne(number):
  return number + 1
</code>```

Why not:

```<code>x = 2
y = addOne(x)
addOne = (number) =>
  return number + 1
</code>```

Similarly, in a language like Java:

```<code>int x = 2;
int y = addOne(x);

int addOne(int x) {
  return x + 1;
}
</code>```

Why not:

```<code>int x = 2;
int y = addOne(x);
(int => int) addOne = (x) => {
  return x + 1;
}
</code>```

This syntax seems more natural way of declaring something (be it a function or a variable) and one less keyword like def or function in some languages. And, IMO, it is more consistent (I look in the same place to understand the type of a variable or function) and probably makes the parser/grammar a little bit simpler to write.

I know very few languages uses this idea (CoffeeScript, Haskell) but most common languages have special syntax for functions (Java, C++, Python, JavaScript, C#, PHP, Ruby).

Even in Scala, which supports both ways (and has type inference), it more common to write:

```<code>def addOne(x: Int) = x + 1
</code>```

Rather than:

```<code>val addOne = (x: Int) => x + 1
</code>```

IMO, atleast in Scala, this is probably the most easily understandable version but this idiom is seldom followed:

```<code>val x: Int = 1
val y: Int = addOne(x)
val addOne: (Int => Int) = x => x + 1
</code>```

I am working on my own toy language and I am wondering if there are any pitfalls if I design my language in such a way and if there are any historical or technical reasons this pattern is not widely followed?

Body:
For some languages functions are not values. In such a language to say that

val f = << i : int  ... >> ;

is a function definition, whereas

val a = 1 ;

declares a constant, is confusing because you are using one syntax to mean two things.

Other languages, such as ML, Haskell, and Scheme treat functions as 1st class values, but provide the user with a special syntax for declaring function valued constants.*  They are applying the rule that "usage shortens form". I.e. if a construct is both common and verbose, you should give the user a shorthand.  It is inelegant to give the user two different syntaxes that mean exactly the same thing; sometimes elegance should be sacrificed to utility.

If, in your language, functions are 1st class, then why not try to find a syntax that is concise enough that you won't be tempted to find a syntactic sugar?

-- Edit --

Another issue no one has brought up (yet) is recursion.  If you allow

{
    val f = << i : int ... g(i-1) ... >> ;
    val g = << j : int ... f(i-1) ... >> ;
    f(x)
}

and you allow

{
    val a = 42 ;
    val b = a + 1 ;
    a
} ,

does it follow that you should allow

{
    val a = b + 1 ;
    val b = a - 1 ;
    a
} ?

In a lazy language (like Haskell), there is no issue here. In an language with essentially no static checks (like LISP), there is no issue here. But in a statically-checked eager language, you have to be careful about how the rules of static checking are defined, if you want to allow the first two and forbid the last.

-- End of Edit --

*It might be argued that Haskell does not belong in this list. It provides two ways to declare a function, but both are, in a sense, generalizations of the syntax for declaring constants of other types


问:
The need for header file when including libraries?
When compiling an application that depends on a library we have to specify the include the library and also the header file.

Since the library binary contains the actual function names couldn't the function names be provided from just the binary?

答: Libraries are specified during linking, rather than compiling, and thus don't provide functions names during compilation. Also, the library object files may not have all the information necessary for the compilation stage (such as the number and types of arguments), depending on what features are available in the object format and which features the compiler made use of when producing the library file.</p>


问:
Is it necessary to collect zip codes if I'm already collecting address, city, and state?
I'm currently building a B2B web application. As a part of the signup process, I require users to enter their office's street address, state, and city, which I then geocode into latitude and longitude using the Bing Maps API. Since I'm primarily using their address for geocoding purposes, I haven't had any issues so far, but now I'm wondering if I should collect their zip code "just in case".

The only scenario I can think where a zip code would affect geolocation is if two places have the exact same address, city, and state but different zip codes. Is that scenario even possible?

Would it be a good idea to collect zip codes, even though I already have enough information to accurately and reliably geocode their coordinates?

答:
Yes, you should collect the zip code.  Mostly because there are cases where the post office and locals disagree on city names, and geocoders get confused.  Adding a zip code will massively improve your odds of success

But there is also a case I heard of in the Boston area with 2 addresses with the same city, street, and street number..but different zip codes.  It sucks having a website that can't handle your address.  And people in that position tend to get more frustrated over time, rather than less.


答: To add to btilly's answer, yes you should require a ZIP code. Not only can this help validate the address, you also assume a US style ZIP code. Other countries use  different postal code systems. The UK, for example, has a much finer grained postcode system, making it a much better validator and harder to infer from an address (although there are existing services that do both).

Title: Is it necessary to collect zip codes if I'm already collecting address, city, and state?

Body:
I'm currently building a B2B web application. As a part of the signup process, I require users to enter their office's street address, state, and city, which I then geocode into latitude and longitude using the Bing Maps API. Since I'm primarily using their address for geocoding purposes, I haven't had any issues so far, but now I'm wondering if I should collect their zip code "just in case".

The only scenario I can think where a zip code would affect geolocation is if two places have the exact same address, city, and state but different zip codes. Is that scenario even possible?

Would it be a good idea to collect zip codes, even though I already have enough information to accurately and reliably geocode their coordinates?


问:
Why does java collections not supply a function for the index of max value?
I have been using Collections.max(list) for many projects, but I occasionally want to find the index of that maximum element. I feel silly writing a function to do this for myself in every program I write.

Why does the Collections Interface not supply a Collections.maxIndex(list)?

答:
While there can be exactly one max value in a collection, there can be more than item representing that value. E.g {1, 9, 2, 9, 0} has max value of 9, represented by both elements [1] and [3].

Note that not all collections support index access; e.g. a Set<Integer> can have a meaningful maximum but accessing an element by index makes no sense in it.

Even if we limit the method to List, it would be a bit hard to come up with one method to find indices of the maximum value that is not clumsy. You could return a list of indices, but then you'd lose the value, and in some collections, e.g. linked lists, accessing an element by index is slow. Since Java does not have an easy syntax for tuples, you'd have to return a special type of object with .getValue() and .getIndices().

But I think that such an operation is just not common enough to be supported in the standard library. Finding a maximum is literally 3-4 lines of code, and tracking the index is another 1-2 lines, and there's no much room to do it wrong. If you do it a lot, you can easily put it in your own utility class.


答:
It is entirely possible to use libraries without using the headers. Here is an example using just the C library:

```<code>int puts(const char *);

int main()
{
    puts("Hello, World!");
}
</code>```

The advantage of header files is to provide the function signatures and structure bodies for you. In the case of the Standard C Library itself, the standard explicitly forbids declaring any function signature yourself if it involves any library-defined type (a real-world example is anything that uses 'off_t', which usually exists in a 32-bit version and a 64-bit version and uses some compiler-specific magic to rename the symbol)

Title: The need for header file when including libraries?

Body:
When compiling an application that depends on a library we have to specify the include the library and also the header file.

Since the library binary contains the actual function names couldn't the function names be provided from just the binary?

Body:
It is entirely possible to use libraries without using the headers. Here is an example using just the C library:

int puts(const char *);

int main()
{
    puts("Hello, World!");
}

The advantage of header files is to provide the function signatures and structure bodies for you. In the case of the Standard C Library itself, the standard explicitly forbids declaring any function signature yourself if it involves any library-defined type (a real-world example is anything that uses 'off_t', which usually exists in a 32-bit version and a 64-bit version and uses some compiler-specific magic to rename the symbol)


答:
Yes you would want to collect this if nothing more than for a sanity check.

Addresses are frequently entered incorrectly.  A geocoding engine often cannot necessarily tell you this.  Take 100 main street denver co and 100 main street denver pa for example.   A good thing to check is to ensure the address in fact does lie within that city and zip code.  If the zip code does not match the city and state, then likely one of the 3 fields are wrong and you could prompt the user at that time to check for address errors.

You might also want to have the zip code if you are planning on using something like a cass verification service to ensure the address is valid in the US.


问:
Should I rebuild my read only database every time I launch my server?
I'm getting into web development, and I'm trying to get a grip on databases.

In an app I want to make, there is a read only database that will be filled up with a large amount of data, which will be the heart of the application, and also a lot of work to put in.

I'm uncomfortable with putting all this data into the database, as the database is "separate" from my web app code. I feel like I should rather write my data in code somewhere, and then have my application put the data into the database for me.

This way I would have my entire project written in code, and not an integral part of my software hidden away in the database, which is a bit complicated to work with, and seems difficult to move from computer to computer.

But is this a sensible way to do this, however? Should I write my data in code, and every time I launch the server, make the application drop all the tables and read them in from my code again?

Is this the wrong way to go about it? Would it cause considerable overhead? How do people do this?

答:
In web development, the app code and database data are kept separate. Don't ever put the code in the database, it just doesn't make any sense. To answer your original question:

No, you shouldn't rebuild your read-only database every time. You would create the database once and add data to it over time.

One thing that didn't quite make sense to me is why would you be rebooting your server often? Servers are designed to remain constantly online so any reboots should be rare.


答:
If it's all read-only, why do you even need a database?

But there is a reason that CREATE TEMP TABLE exists, don't be afraid to use it (but reloading it every time your process starts is likely to be more expensive than just leaving it on disk).

Title: Should I rebuild my read only database every time I launch my server?

Body:
I'm getting into web development, and I'm trying to get a grip on databases.

In an app I want to make, there is a read only database that will be filled up with a large amount of data, which will be the heart of the application, and also a lot of work to put in.

I'm uncomfortable with putting all this data into the database, as the database is "separate" from my web app code. I feel like I should rather write my data in code somewhere, and then have my application put the data into the database for me.

This way I would have my entire project written in code, and not an integral part of my software hidden away in the database, which is a bit complicated to work with, and seems difficult to move from computer to computer.

But is this a sensible way to do this, however? Should I write my data in code, and every time I launch the server, make the application drop all the tables and read them in from my code again?

Is this the wrong way to go about it? Would it cause considerable overhead? How do people do this?


问:
Is a tree with nodes that have reference to parent still a tree?
If we make reference to the parent for each node in a tree, do we still have a tree (by definition) anymore?

Wikipedia definition is:

In computer science, a tree is a widely used abstract data type (ADT)
  or data structure implementing this ADT that simulates a hierarchical
  tree structure, with a root value and subtrees of children,
  represented as a set of linked nodes.

答:
Let's follow this definition. Will surely get the ans.

A connected graph G is called a tree if the removal of any of its edges makes
G disconnected.
So, as the graph given above, does not support this statement, so we can not say that the graph given is a tree.

For more info you can continue this link.

http://win.ua.ac.be/~vanhoudt/graph/trees.pdf


问:
Given a subset of numbers and subset of sums. Match the numbers to sums.(Harder than appears)
I'm not sure what the most efficent solution to this algorithm is. I'm not sure this fits exact cover, and approaching it via exhaustive backtracking seems somewhat inefficient. Any suggestions on how to approach this?

There are 210 Invoices and 1700 bills – these bills add up to these invoices

The association between bills and invoices is lost . The only way to match them is by adding them up to correct amounts that are equal to the invoices.

For example, consider the case where you have 2 invoices for 80, 210 and you have bills for values 50, 10, 10, 30, 20, 70, 100.

One of the possible solution is:

80 = 50 + 30

210 = 10 + 10 + 20 + 70 + 100

Other possible solution is

80 = 50 + 10 + 20

210 = 30 + 20 + 70 + 100

What is the best possible way to get all solutions? Remember you are dealing with big datasets.

答:
This problem is harder than solving it for 2 invoices (just group all invoices but one). If we try solving it for 2 invoices and 1700 bills we see that the sum of the 2 invoices is equal to the sum of the 1700 bills, so all we need to find is a subset of the 1700 bills whose sum is equal to one of the invoices. Thus we have a subset sum problem, which means that this is a NP-hard problem. So, unless we have some reasonable restriction on what values the invoices can take this problem is not solvable in a reasonable amount of time.

The answer is thus that this problem is not solvable with the given information. However, if we assume that the largest invoice is reasonably small we can use dynamic programming to solve this problem.


问:
Convincing my boss that touching the Database is integration testing
I am currently working on introducing continuous integration and switching to git, and as part of that, we must also better structure our tests.

We have agreed on splitting the tests in "integration" and "unit" - however he doesn't seem to agree that touching the database is also integration testing.

The code is horrible, everything is coupled to the database, it's hard to mock and stub, and I want to move it on the long term towards a better modularisation and testability.

Getting him to accept and use the proper naming is critical in future arguments.

So how to convince him that every test which touches the database is also integration testing?

At the moment he thinks that exec()-ing an external program or using an external interface (e.g. via SOAP) is an integration test.

He also thinks that everything which is slow belongs to integration testing, while he's in love with his "lightning fast database".

答:
I think that when you are dealing with people who think they know best, or you are just in a position where they don't think they should be listening to you, the best way is question their ways.

He is probably the type that believes that he should be the one making the decisions (independently of whether or not he is the most qualified). And just telling him your view is not really helpful. You have to plant a seed in him that can help him make a new, better decision.

Instead of telling your boss how you should be structuring your tests, you should question his ways - "why do you believe that tests hitting the database are unit tests when every well respected resource says that unit tests should not touch the database?", "Shouldn't unit tests be independent? How can they be when they touch a shared database? Shouldn't they be able to run in parallel?"

You say that he is quite inconsistent with himself, which I think you should focus on. "I don't understand, when you say that integration tests are ... but then you say that ... is not/also an integration test?"

If you just tell him, "unit tests should not touch the database", you are indirectly just saying to him, "you are wrong, I am right", and he will start being defensive. If you question his ways, you are forcing him to think.

It is important that you phrase your questions in a way where you really try to understand his point of view. If not, your questions will be just a slightly modified version of dictating your own point of view, and the debate quickly becomes tiring for both. And maybe he has a valid point somewhere that you should also understand.

Disclaimer: I have now tried to analyze your boss without ever actually having met him, which is of course impossible. But the scenario you describe is consistent with a pattern I have seen before.


问:
C++: Metaprogramming with a compiler API rather than with C++ features
This started out as a SO question but I realized that it is quite unconventional and based on the actual description on the websites, it might be better suited to programmers.se since the question has a lot of conceptual weight.

I have been learning clang LibTooling and it is a very powerful tool capable of exposing the entire "nitty gritty" of the code in a friendly way, that is, in a semantic way, and not by guessing either. If clang can compile your code, then clang is certain about the semantics of every single character inside that code.

Now allow me to step back for a moment.

There are many practical problems that arise when one engages in C++ template metaprogramming (and especially when venturing beyond templates into the territory of clever albeit terrifying macros). To be honest, to many programmers, myself included, many of the ordinary uses of templates are also somewhat terrifying.

I guess a good example would be compile-time strings. This is a question that is over a year old now, but it is clear that C++ as of right now does not make this easy for mere mortals. While looking at these options isn't quite enough to induce nausea for me, it nevertheless leaves me unconfident about being able to produce magical, maximally efficient machine code to suit whatever fancy application I have for my software.

I mean, let's face it, folks, strings are pretty simple and basic. Some of us just want a convenient way to emit machine code that has certain strings "baked in" significantly more than we do get when coding it the straightforward way. In our C++ code.

Enter clang and LibTooling, which exposes the abstract syntax tree (AST) of the source code and allows a simple custom C++ application to correctly and reliably manipulate raw source code (using Rewriter) alongside a rich semantic object-oriented model of everything in the AST. It handles a lot of things. It knows about the macro expansions, and lets you follow those chains. Yes, I am talking about source-to-source code transformation or translation.

My fundamental thesis here is that clang now enables us to create executables which themselves can function as the ideal custom preprocessor stages to our C++ software, and we can implement these metaprogramming stages with C++. We are simply constrained by the fact that this stage must take input which is valid C++ code and produce as output more valid C++ code. Plus whatever other constraints your build system applies.

The input has to be at least very close to valid C++ code because, after all, clang is the compiler front-end and we are just poking around and being creative with its API. I do not know if there is any provision for being able to define new syntax to use, but clearly we have to develop the ways to properly parse it and add it to the clang project in order to do this. To expect any more is to have something in the clang project that is out of scope.

Not a problem. I would imagine that some no-op macro functions can handle this task.

Another way to look at what I'm describing is to implement metaprogramming constructs using runtime C++ by manipulating the AST of our source code (thanks to clang and its API) instead of implementing them using the more limited tools available in the language itself. This has clear compilation performance benefits as well (template-heavy headers slow compilation proportionally to how often you use them. Lots of compiled stuff then gets carefully matched up and thrown away by the linker).

This does, however, come at the cost of introducing an additional step or two in the build process and also in the requirement of writing some (admittedly) somewhat more verbose software (but at least it is straightforward runtime C++) as part of our tool.

That isn't the whole picture. I am pretty certain that there is a much larger space of functionality that can be had from generating code that is extremely difficult or impossible with core language features. In C++ you can write a template or a macro or a crazy combination of both, but in a clang tool you can modify classes and functions in ANY way that you can achieve with C++, at runtime, while having full access to the semantic content, in addition to template and macros and everything else.

So, I'm wondering about why everybody isn't already doing this. Is it that this functionality from clang is so new and nobody is familiar with the huge class hierarchy of clang's AST? That can't be it.

Perhaps I am just underestimating the difficulty of this a little bit, but doing "compile-time string manipulation" with a clang tool is nearly criminally simple. It's verbose, but it's insanely straightforward. All that's needed are a bunch of no-op macro functions that map to actual real std::string operations. The clang plugin implements this by fetching all the relevant no-op macro calls, and performs the operations with strings. This tool is then inserted as a part of the build process. During build, these no-op macro function calls are automatically evaluated into their results, and then inserted back as plain old compile-time strings in the program. The program can then be compiled as usual. In fact this resulting program is also much more portable as a result, not requiring a fancy new compiler supporting C++11.

答:
Yes, Virginia, there is a Santa Claus.

The notion of using programs to modify programs has been around a long time. The original idea came from John von Neumann in the form of stored-program computers.  But machine code modifying machine code in arbitrary ways is pretty inconvenient.

People generally want to modify source code.  This is mostly realized in the form of program transformation systems (PTS).

PTS generally offer, for at least one programming language, the ability to parse to ASTs, manipulate that AST, and regenerate valid source text.  If in fact you dig around, for most mainstream languages, somebody has built such a tool (Clang is an example for C++, the Java compiler offers this capability as an API, Microsoft offers Rosyln, Eclipse's JDT, ...) with a procedural API that is actually pretty useful.  For the broader community, almost every language-specific community can point to something like this, implemented with various levels of maturity (usually modest, many "just parsers producing ASTs").  Happy metaprogramming.

[There's a reflection-oriented community that tries to do metaprogramming from inside the programming language, but only achieve "runtime" behaviour modifiation, and only to the extent that the language compilers made some information available by reflection. With the exception of LISP, there are always details about the program that are not available by reflection ("Luke, you need the source") that always limit what reflection can do.]

The more interesting PTS do this for arbitrary languages (you give the tool a language description as a configuration parameter, including at a minimum the BNF).  Such PTS also allow you to do "source to source" transformation, e.g., specify patterns directly using the surface syntax of the targeted language; using such patterns, you can code fragments of interest, and/or find and replace code fragments.  This is far more convenient than the programming API, because you don't have to know every microscopic details about the ASTs to do most of your work.  Think of this as meta-metaprogramming :-}

A downside: unless the PTS offers various kinds of useful static analyses (symbol tables, control and data flow analyses), it is hard to write really interesting transformations this way, because you need to check types and verify information flows for most practical tasks.  Unfortunately, this capability is in fact rare in the general PTS.  (It is always unavailable with the ever-proposed "If I just had a parser... "  See my bio for a longer discussion of "Life After Parsing").

There's a theorem that says if you can do string rewriting [thus tree rewriting] you can do arbitrary transformation; and thus a number of PTS lean on this to claim you can metaprogram anything with just the tree rewrites they offer. While the theorem is satisfying in the sense you are now sure you can do anything, it is unsatisfying in the same way that a Turing Machine's ability to do anything doesn't make programming a Turing Machine the method of choice. (The same holds true for systems with just procedural APIs, if they will let you make arbitrary changes to the AST [and in fact I think this is not true of Clang]).

What you want is the best of both worlds, a system that offers you the generality of the language-parameterized type of PTS (even handling multiple languages), with the additional static analyses, the ability to mix source-to-source transformations with procedural APIs.  I only know of two that do this:

Rascal (MPL) MetaProgramming Language

our DMS Software Reengineering Toolkit

Unless you want the write the language descriptions and static analyzers yourself (for C++ this is a tremendous amount of work, which is why Clang was constructed both as a compiler and as general procedural metaprogramming foundation), you will want a PTS with mature language descriptions already available.  Otherwise you will spend all your time configuring the PTS, and none doing the work you actually wanted to do. [If you pick a random, non-mainstream language, this step is very hard to avoid].

Rascal tries to do this by co-opting "OPP" (Other People's Parsers) but that doesnt help with the static analysis part.  I think they have Java pretty well in hand, but I'm very sure they don't do C or C++. But, its a academic research tool; hard to blame them.

I emphasize, our [commercial] DMS tool does have Java, C, C++ full front ends available. For C++, it covers almost everything in C++14 for GCC and even Microsoft's variations (and we are polishing now), macro expansion and conditional management, and method-level control and data flow analysis.  And yes, you can specify grammar changes in a practical way; we built a custom VectorC++ system for a client that radically extended C++ to use what amount to F90/APL data-parallel array operations.   DMS has been used to carry out other massive metaprogramming tasks on large C++ systems (e.g., application architectural reshaping).  (I am the architect behind DMS).

Happy meta-metaprogramming.


答: Like the other respondents I would collect zip codes, for all the reasons stated. In addition, it is possible for geocoding to give incorrect information. I have not dealt with Bing, but I do know that Google (and some GPS systems) can give incorrect information when dealing with addresses. I have never got to the bottom of the incompatibility, but the post code and the actual location do not match for my address when using these services, and I am forever having to give couriers and others seeking my address false information to guide them to my actual location.</p>


问:
Gradual reveal in REST APIs
In the article Building Web Services the REST Way, the author states:

Design to reveal data gradually. Don't reveal everything in a single response document. Provide hyperlinks to obtain more details.

Why is this considered a good practice?

UPDATE: I realize that this practice is also known as HATEOAS.

答:
I think the main advantage you gain when following this principle is the API's browsability. If different resources are interconnected in this way, you only need to provide a couple of entry points (well known URLs that provide clients a way to start exploring your API) and the clients are virtually free from the responsibility of building URLs. You can just provide them with links.

Another important point is that with each link, you can provide some semantically significant description that describes the nature of the link. This is a good way to describe relationships between resources.

Consider the following examples:

A non-granular approach

```<code>GET /users/1
Response:
{
    "id": 1,
    "name" : "Tom"
    "addresses" : [
        {
            "id" : "1",
            "email" : "foo@bar.baz",
            "street" : "Sesame Street",
            "city" : "London",
            "country" : "United Kingdom"
        }
    ],
    "posts" : [
         {
            "id" : "1",
            "title" : "HATEOAS Examples",
            "content" : "Yada yada yada",
            "created" : "2014-01-01"
         },
         {
            "id" : "2",
            "title" : "Foo bar baz",
            "content" : "Lorem ipsum dolor",
            "created" : "2014-01-05"
         },
         // many many more
    ]
}
</code>```

How do I limit the number of posts I retrieve?

How do I limit the number of addresses bound to my profile that I retrieve?

How do I delete an address related to my profile?

How do I update a post?

How do I get the posts from a specific day?

Can you cache this entire response? When to invalidate the cache?

You cannot immediately tell how to do any of these things. Trying to implement them using a non-granular API like this, you'll and up with numerous parameters that are not really specific to the resource you're fetching and the user of your API will have to spend a lot of time browsing the documentation just to render an appropriate interface for the end user to interact with an API like this.

A hierarchy of granular, interconnected resources

Now consider the sub-resources as separate, discoverable entities. The data is revealed gradually, as the consumer performs further requests.

```<code>GET /users/1
Response:
{
    "id": 1,
    "name" : "Tom",
    "self" : "/users/1",
    "links" : [
        { "rel" : "addresses", "url" : "/users/1/addresses" },
        { "rel" : "posts", "url" : "/posts?user=1" },
        { "rel" : "all.users", "url" : "/users" }
    ]
}
</code>```

And the separate resources:

All addresses

```<code> GET /users/1/addresses
 Response:
 {
     "title" : "Tom's addresses",
     "self" : "/users/1/addresses",
     "links" : [
         { "rel" : "user", "/users/1" }
         { "rel" : "address", "/users/1/addresses/1"}
     ]
 }
</code>```

A single address

```<code> GET /users/1/addresses/1
 Response:
 {
     "id" : "1",
     "email" : "foo@bar.baz",
     "street" : "Sesame Street",
     "city" : "London",
     "country" : "United Kingdom",
     "self" : "/users/1/addresses/1"
     "links" : {
         { "rel" : "all.addresses", "/users/1/addresses" },
         { "rel" : "update.form", "/users/1/addresses/1/update-form" },
     }
 }
</code>```

All posts

```<code>GET /posts?user=1
Response:
{
    "title" : "Tom's posts",
    "self" : "/posts?user=1",
    "links" : [
        { "rel" : "user", "/users/1" },
        { "rel" : "post", "url" : "/posts/1" },
        { "rel" : "post", "url" : "/posts/2" },
        // many more
    ]
}
</code>```

Example single post

```<code>GET /posts/1
Response
{
    "title" : "HATEOAS Examples",
    "content" : "Yada yada yada",
    "created" : "2014-01-01",
    "self" : "/posts/1",
    "links" : [
        { "rel" : "user", "url" : "/users/1" },
        { "rel" : "user.all.posts", "url" : "/posts?user=1" }
        { "rel" : "edit.form", "url" : "posts/1/edit-form" }
    ]
}
</code>```

Again, the same questions:

How do I limit the number of posts I retrieve? - Now you can have an application-wide parameters to handle pagination, say, limit and offset. You can provide these already embedded into various links. Even if you don't, such a convention is very easy to adopt by API consumers.

How do I limit the number of addresses bound to my profile that I retrieve? - Same as above, no need for additional parameters to remember.

How do I delete an address related to my profile? - Obtain the rel link to the address and issue a DELETE request, again, this can be an application-wide convention. You can just follow links and delete whatever you can. Another way would be to provide additional metadata, you could easily provide a link with additional information saying that a DELETE request is allowed for the resource linked... or maybe make this a property of a resource and not a link itself. Ideally, you could serve such information in response to OPTIONS requests. Either way, it's easy to understand by API consumers.

How do I update a post? - You can provide a link to a form, this can be a piece of HTML you prepared or even a JSON/XML response with information on how to render a form like this (this can be used by non-browser clients)

Can you cache this entire response? When to invalidate the cache? You can cache every single one of these responses. An update of a small, lightweight resource, like changing a post title does not require you to recreate a huge response. You also need to invalidate caches when a resource linked to something is created or deleted (to update the links).

What I like the most about this approach is that it's easy to understand and using the API feels like browsing a website. This allows you to drive the application state using just the responses. The consumer just needs to follow the links you provide to move around.

It's much harder for a client of such an API to break when you change something. Even if you decide to move some resources around and change their links, the clients can use their relationships, which are generally much more inert. Particularly if you use well-thought-out relations. I didn't go this far in the examples above but in a real API, you should ideally take a look around and see what known link relations you could use. IANA keeps a registry of those. Reusing standardized links will make it easier for others to understand your API (especially if they know other APIs using them) and it will save you the work of documenting the relations (you can just point to the right RFC or other applicable document)

Potential Pitfalls

Of course none of this comes for free. Creating an API like this is not easy and it may cost you a lot of effort.

APIs designed this way tend to be more difficult to build and understand. Scalability and flexibility are very important in public APIs, for which many clients can be written by unrelated parties. This is where you can gain the most by properly using hypermedia. However, if your API is only to be consumed within your company or even in a single intranet solution, you might prefer to save yourself the effort and opt for an easy to implement (or even generate out of a service description document) design that relies on human-readable documentation and conventions rather than rich hypermedia. There's nothing wrong with betraying the principles of REST if your use case really calls for it. Just don't say your API is RESTful when you do so.

Another downside of this approach is the sheer amount of calls using an API like this requires. The impact of this is reduced by the API's cache-ability and scalability. If this isn't enough, you can consider providing the user with a way to reach deeper into the hierarchy (like, provide a parameter instructing the server to embed some of the linked resources into the single response server-side)

Some resources you might find interesting:

Richardson's Maturity Model

The Netflix REST API using rel links in a similar manner

An article describing the usage of a REST API

An Apigee article on HATEOAS

A stackoverflow answer to a similar question about HATEOAS

Roy Fielding's very own blog post on the importance of hypertext in REST

I can also wholeheartedly recommend RESTful Web APIs by Amundsen, Richardson and Ruby. Hypermedia and its proper use in RESTful APIs is the key subject of the book.

Title: Gradual reveal in REST APIs

Body:
I think the main advantage you gain when following this principle is the API's browsability. If different resources are interconnected in this way, you only need to provide a couple of entry points (well known URLs that provide clients a way to start exploring your API) and the clients are virtually free from the responsibility of building URLs. You can just provide them with links.

Another important point is that with each link, you can provide some semantically significant description that describes the nature of the link. This is a good way to describe relationships between resources.

Consider the following examples:

A non-granular approach

GET /users/1
Response:
{
    "id": 1,
    "name" : "Tom"
    "addresses" : [
        {
            "id" : "1",
            "email" : "foo@bar.baz",
            "street" : "Sesame Street",
            "city" : "London",
            "country" : "United Kingdom"
        }
    ],
    "posts" : [
         {
            "id" : "1",
            "title" : "HATEOAS Examples",
            "content" : "Yada yada yada",
            "created" : "2014-01-01"
         },
         {
            "id" : "2",
            "title" : "Foo bar baz",
            "content" : "Lorem ipsum dolor",
            "created" : "2014-01-05"
         },
         // many many more
    ]
}

How do I limit the number of posts I retrieve?

How do I limit the number of addresses bound to my profile that I retrieve?

How do I delete an address related to my profile?

How do I update a post?

How do I get the posts from a specific day?

Can you cache this entire response? When to invalidate the cache?

You cannot immediately tell how to do any of these things. Trying to implement them using a non-granular API like this, you'll and up with numerous parameters that are not really specific to the resource you're fetching and the user of your API will have to spend a lot of time browsing the documentation just to render an appropriate interface for the end user to interact with an API like this.

A hierarchy of granular, interconnected resources

Now consider the sub-resources as separate, discoverable entities. The data is revealed gradually, as the consumer performs further requests.

GET /users/1
Response:
{
    "id": 1,
    "name" : "Tom",
    "self" : "/users/1",
    "links" : [
        { "rel" : "addresses", "url" : "/users/1/addresses" },
        { "rel" : "posts", "url" : "/posts?user=1" },
        { "rel" : "all.users", "url" : "/users" }
    ]
}

And the separate resources:

All addresses

 GET /users/1/addresses
 Response:
 {
     "title" : "Tom's addresses",
     "self" : "/users/1/addresses",
     "links" : [
         { "rel" : "user", "/users/1" }
         { "rel" : "address", "/users/1/addresses/1"}
     ]
 }

A single address

 GET /users/1/addresses/1
 Response:
 {
     "id" : "1",
     "email" : "foo@bar.baz",
     "street" : "Sesame Street",
     "city" : "London",
     "country" : "United Kingdom",
     "self" : "/users/1/addresses/1"
     "links" : {
         { "rel" : "all.addresses", "/users/1/addresses" },
         { "rel" : "update.form", "/users/1/addresses/1/update-form" },
     }
 }

All posts

GET /posts?user=1
Response:
{
    "title" : "Tom's posts",
    "self" : "/posts?user=1",
    "links" : [
        { "rel" : "user", "/users/1" },
        { "rel" : "post", "url" : "/posts/1" },
        { "rel" : "post", "url" : "/posts/2" },
        // many more
    ]
}

Example single post

GET /posts/1
Response
{
    "title" : "HATEOAS Examples",
    "content" : "Yada yada yada",
    "created" : "2014-01-01",
    "self" : "/posts/1",
    "links" : [
        { "rel" : "user", "url" : "/users/1" },
        { "rel" : "user.all.posts", "url" : "/posts?user=1" }
        { "rel" : "edit.form", "url" : "posts/1/edit-form" }
    ]
}

Again, the same questions:

How do I limit the number of posts I retrieve? - Now you can have an application-wide parameters to handle pagination, say, limit and offset. You can provide these already embedded into various links. Even if you don't, such a convention is very easy to adopt by API consumers.

How do I limit the number of addresses bound to my profile that I retrieve? - Same as above, no need for additional parameters to remember.

How do I delete an address related to my profile? - Obtain the rel link to the address and issue a DELETE request, again, this can be an application-wide convention. You can just follow links and delete whatever you can. Another way would be to provide additional metadata, you could easily provide a link with additional information saying that a DELETE request is allowed for the resource linked... or maybe make this a property of a resource and not a link itself. Ideally, you could serve such information in response to OPTIONS requests. Either way, it's easy to understand by API consumers.

How do I update a post? - You can provide a link to a form, this can be a piece of HTML you prepared or even a JSON/XML response with information on how to render a form like this (this can be used by non-browser clients)

Can you cache this entire response? When to invalidate the cache? You can cache every single one of these responses. An update of a small, lightweight resource, like changing a post title does not require you to recreate a huge response. You also need to invalidate caches when a resource linked to something is created or deleted (to update the links).

What I like the most about this approach is that it's easy to understand and using the API feels like browsing a website. This allows you to drive the application state using just the responses. The consumer just needs to follow the links you provide to move around.

It's much harder for a client of such an API to break when you change something. Even if you decide to move some resources around and change their links, the clients can use their relationships, which are generally much more inert. Particularly if you use well-thought-out relations. I didn't go this far in the examples above but in a real API, you should ideally take a look around and see what known link relations you could use. IANA keeps a registry of those. Reusing standardized links will make it easier for others to understand your API (especially if they know other APIs using them) and it will save you the work of documenting the relations (you can just point to the right RFC or other applicable document)

Potential Pitfalls

Of course none of this comes for free. Creating an API like this is not easy and it may cost you a lot of effort.

APIs designed this way tend to be more difficult to build and understand. Scalability and flexibility are very important in public APIs, for which many clients can be written by unrelated parties. This is where you can gain the most by properly using hypermedia. However, if your API is only to be consumed within your company or even in a single intranet solution, you might prefer to save yourself the effort and opt for an easy to implement (or even generate out of a service description document) design that relies on human-readable documentation and conventions rather than rich hypermedia. There's nothing wrong with betraying the principles of REST if your use case really calls for it. Just don't say your API is RESTful when you do so.

Another downside of this approach is the sheer amount of calls using an API like this requires. The impact of this is reduced by the API's cache-ability and scalability. If this isn't enough, you can consider providing the user with a way to reach deeper into the hierarchy (like, provide a parameter instructing the server to embed some of the linked resources into the single response server-side)

Some resources you might find interesting:

Richardson's Maturity Model

The Netflix REST API using rel links in a similar manner

An article describing the usage of a REST API

An Apigee article on HATEOAS

A stackoverflow answer to a similar question about HATEOAS

Roy Fielding's very own blog post on the importance of hypertext in REST

I can also wholeheartedly recommend RESTful Web APIs by Amundsen, Richardson and Ruby. Hypermedia and its proper use in RESTful APIs is the key subject of the book.


答:
It depends on what you want to do with that data.

If you need to search that data and only need small parts of it at a time, then keeping all of it in the database is a good idea.  The database already implements fast searching and memory caching algorithms for the data.  The database is also a natural structure for data if the data itself has many relations.  Finally the database also provides a way to load data into your system without having to recompile\redeploy the system.

However, if you need all of the data for almost all of the computations, the data doesn't change, your application is performance critical (and does no searches) and you'll never need to look or search for a slice of the data, then you could place the data in the application code.

In terms of setting up and moving a database from computer to computer, that's typically the job of an installer\deployment process.  If you keep all of your configuration settings (server name, server id, user name, password, etc) in a editable settings file, then you can more easily move the software from one machine to another.  If the database's license permits, you could install the database software along with the schema and data as part of your installation process.


问:
What's the worst question you were ever asked at interview?
It doesn't have to be programming or software development related, but just asked during an interview for an IT related job.

I know some "left field" questions are meant to see how the candidate copes with unexpected and novel situations, but here I'm looking for a question that appeared to be completely unrelated to the job they were interviewing you for, or something that made you think "what useful information could they possibly get from my answer to that question?".

答:
I was in a phone interview for a .NET job and the interviewer was aware that I am a fresh graduate with 6 months of part time ASP.NET(C#) experience.

She first asked me, "How come you don't list sharepoint on your resume?"

I respond, "Because I don't have any sharepoint experience."

She responds, "Well I thought you said you have 6 mos. of ASP.NET experience?"

I respond, "Correct, but I didn't utilize sharepoint at all."

She responds, "Well my client is asking for .NET Sharepoint experience, sorry."

End of interview.

ContentLicense: CC BY-SA 2.5


问:
Why is type inference useful?
I read code way more often than I write code, and I'm assuming that most of the programmers working on industrial software do this. The advantage of type inference I assume is less verbosity and less written code. But on the other hand if you read code more often, you'll probably want readable code.

The compiler infers the type; there are old algorithms for this. But the real question is why would I, the programmer, want to infer the type of my variables when I read the code? Isn't it more faster for anyone just to read the type than to think what type is there?

Edit: As a conclusion I understand why it is useful. But in the category of language features I see it in a bucket with operator overloading - useful in some cases but affecting readability if abused.

答:
I think type inference is quite important and should be supported in any modern language. We all develop in IDEs and they could help a lot in case you want to know the inferred type, just few of us hack in vi.
Think of verbosity and ceremony code in Java for instance.

```<code>  Map<String,HashMap<String,String>> map = getMap();
</code>```

But you can say it's fine my IDE will help me, it could be a valid point. However, some features wouldn't be there without the help of type inference, C# anonymous types for instance.

```<code> var person = new {Name="John Smith", Age = 105};
</code>```

Linq wouldn't be as nice as it is now without the help of type inference, Select for instance

```<code>  var result = list.Select(c=> new {Name = c.Name.ToUpper(), Age = c.DOB - CurrentDate});
</code>```

This anonymous type will be inferred neatly to the variable.

I dislike type inference on return types in Scala because I think your point applies here, it should be clear for us what a function returns so we can use the API more fluently

Title: Why is type inference useful?

Body:
I think type inference is quite important and should be supported in any modern language. We all develop in IDEs and they could help a lot in case you want to know the inferred type, just few of us hack in vi.
Think of verbosity and ceremony code in Java for instance.

  Map<String,HashMap<String,String>> map = getMap();

But you can say it's fine my IDE will help me, it could be a valid point. However, some features wouldn't be there without the help of type inference, C# anonymous types for instance.

 var person = new {Name="John Smith", Age = 105};

Linq wouldn't be as nice as it is now without the help of type inference, Select for instance

  var result = list.Select(c=> new {Name = c.Name.ToUpper(), Age = c.DOB - CurrentDate});

This anonymous type will be inferred neatly to the variable.

I dislike type inference on return types in Scala because I think your point applies here, it should be clear for us what a function returns so we can use the API more fluently


答:
Let's take a look at Java. Java 8 can't have variables with inferred types. This means I frequently have to spell out the type, even if it is perfectly obvious to a human reader what the type is:

int x = 42;  // yes I see it's an int, because it's a bloody integer literal!

// Why the hell do I have to spell the name twice?
SomeObjectFactory<OtherObject> obj = new SomeObjectFactory<>();
```
<p>And sometimes it's just plain annoying to spell out the whole type.</p>
<pre class="lang-java prettyprint-override"><code>// this code walks through all entries in an "(int, int) -> SomeObject" table
// represented as two nested maps
// Why are there more types than actual code?
for (Map.Entry<Integer, Map<Integer, SomeObject<SomeObject, T>>> row : table.entrySet()) {
    Integer rowKey = entry.getKey();
    Map<Integer, SomeObject<SomeObject, T>> rowValue = entry.getValue();
    for (Map.Entry<Integer, SomeObject<SomeObject, T>> col : rowValue.entrySet()) {
        Integer colKey = col.getKey();
        SomeObject<SomeObject, T> colValue = col.getValue();
        doSomethingWith<SomeObject<SomeObject, T>>(rowKey, colKey, colValue);
    }
}
</code>```

This verbose static typing gets in the way of me, the programmer. Most type annotations are repetitive line-filler, content-free regurgiations of what we already know. However, I do like static typing, as it can really help with discovering bugs, so using dynamic typing isn't always a good answer. Type inference is the best of both worlds: I can omit the irrelevant types, but still be sure that my program (type-)checks out.

While type inference is really useful for local variables, it should not be used for public APIs which have to be unambiguously documented. And sometimes the types really are critical for understanding what's going on in the code. In such cases, it would be foolish to rely on type inference alone.

There are many languages that support type inference. For example:

C++. The auto keyword triggers type inference. Without it, spelling out the types for lambdas or for entries in containers would be hell.

C#. You can declare variables with var, which triggers a limited form of type inference. It still manages most cases where you want type inference. In certain places you can leave out the type completely (e.g. in lambdas).

Haskell, and any language in the ML family. While the specific flavour of type inference used here is quite powerful, you still often see type annotations for functions, and for two reasons: The first is documentation, and the second is a check that type inference actually found the types you expected. If there is a discrepancy, there's likely some kind of bug.

And since this answer was originally written, type inference has become more popular. E.g. Java 10 has finally added C#-style inference. We're also seeing more type systems on top of dynamic languages, e.g. TypeScript for JavaScript, or mypy for Python, which make heavy use of type inference in order to keep the overhead of type annotations manageable.

Title: Why is type inference useful?

Body:
I read code way more often than I write code, and I'm assuming that most of the programmers working on industrial software do this. The advantage of type inference I assume is less verbosity and less written code. But on the other hand if you read code more often, you'll probably want readable code.

The compiler infers the type; there are old algorithms for this. But the real question is why would I, the programmer, want to infer the type of my variables when I read the code? Isn't it more faster for anyone just to read the type than to think what type is there?

Edit: As a conclusion I understand why it is useful. But in the category of language features I see it in a bucket with operator overloading - useful in some cases but affecting readability if abused.

Body:
Let's take a look at Java. Java 8 can't have variables with inferred types. This means I frequently have to spell out the type, even if it is perfectly obvious to a human reader what the type is:

int x = 42;  // yes I see it's an int, because it's a bloody integer literal!

// Why the hell do I have to spell the name twice?
SomeObjectFactory<OtherObject> obj = new SomeObjectFactory<>();

And sometimes it's just plain annoying to spell out the whole type.

// this code walks through all entries in an "(int, int) -> SomeObject" table
// represented as two nested maps
// Why are there more types than actual code?
for (Map.Entry<Integer, Map<Integer, SomeObject<SomeObject, T>>> row : table.entrySet()) {
    Integer rowKey = entry.getKey();
    Map<Integer, SomeObject<SomeObject, T>> rowValue = entry.getValue();
    for (Map.Entry<Integer, SomeObject<SomeObject, T>> col : rowValue.entrySet()) {
        Integer colKey = col.getKey();
        SomeObject<SomeObject, T> colValue = col.getValue();
        doSomethingWith<SomeObject<SomeObject, T>>(rowKey, colKey, colValue);
    }
}

This verbose static typing gets in the way of me, the programmer. Most type annotations are repetitive line-filler, content-free regurgiations of what we already know. However, I do like static typing, as it can really help with discovering bugs, so using dynamic typing isn't always a good answer. Type inference is the best of both worlds: I can omit the irrelevant types, but still be sure that my program (type-)checks out.

While type inference is really useful for local variables, it should not be used for public APIs which have to be unambiguously documented. And sometimes the types really are critical for understanding what's going on in the code. In such cases, it would be foolish to rely on type inference alone.

There are many languages that support type inference. For example:

C++. The auto keyword triggers type inference. Without it, spelling out the types for lambdas or for entries in containers would be hell.

C#. You can declare variables with var, which triggers a limited form of type inference. It still manages most cases where you want type inference. In certain places you can leave out the type completely (e.g. in lambdas).

Haskell, and any language in the ML family. While the specific flavour of type inference used here is quite powerful, you still often see type annotations for functions, and for two reasons: The first is documentation, and the second is a check that type inference actually found the types you expected. If there is a discrepancy, there's likely some kind of bug.

And since this answer was originally written, type inference has become more popular. E.g. Java 10 has finally added C#-style inference. We're also seeing more type systems on top of dynamic languages, e.g. TypeScript for JavaScript, or mypy for Python, which make heavy use of type inference in order to keep the overhead of type annotations manageable.


答:
It's true that code is read far more often than it is written. However, reading also takes time, and two screens of code are harder to navigate and read than one screen of code, so we need to prioritize to pack the best useful-information/reading-effort ratio. This is a general UX principle: Too much information at once overwhelms and actually degrades the effectiveness of the interface.

And it is my experience that often, the exact type isn't (that) important. Surely you sometimes nest expressions: x + y * z, monkey.eat(bananas.get(i)), factory.makeCar().drive(). Each of these contains sub-expressions that evaluate to a value whose type is not written out. Yet they are perfectly clear. We're okay with leaving the type unstated because it's easy enough to figure out from the context, and writing it out would do more harm than good (clutter the understanding of the data flow, take valuable screen and short-term memory space).

One reason to not nest expressions like there's no tomorrow is that lines get long and the flow of values becomes unclear. Introducing a temporary variable helps with this, it imposes an order and gives a name to a partial result. However, not everything that benefits from these aspects also benefits from having its type spelled out:

```<code>user = db.get_poster(request.post['answer'])
name = db.get_display_name(user)
</code>```

Does it matter whether user is an entity object, an integer, a string, or something else? For most purposes, it does not, it's enough to know that it represents a user, comes from the HTTP request, and is used to fetch the name to display in the lower right corner of the answer.

And when it does matter, the author is free to write out the type. This is a freedom that must be used responsibly, but the same is true for everything else that can enhance readability (variable and function names, formatting, API design, white space).
And indeed, the convention in Haskell and ML (where everything can be inferred without extra effort) is to write out the types of non-local functions functions, and also of local variables and functions whenever appropriate. Only novices let every type be inferred.

Title: Why is type inference useful?

Body:
It's true that code is read far more often than it is written. However, reading also takes time, and two screens of code are harder to navigate and read than one screen of code, so we need to prioritize to pack the best useful-information/reading-effort ratio. This is a general UX principle: Too much information at once overwhelms and actually degrades the effectiveness of the interface.

And it is my experience that often, the exact type isn't (that) important. Surely you sometimes nest expressions: x + y * z, monkey.eat(bananas.get(i)), factory.makeCar().drive(). Each of these contains sub-expressions that evaluate to a value whose type is not written out. Yet they are perfectly clear. We're okay with leaving the type unstated because it's easy enough to figure out from the context, and writing it out would do more harm than good (clutter the understanding of the data flow, take valuable screen and short-term memory space).

One reason to not nest expressions like there's no tomorrow is that lines get long and the flow of values becomes unclear. Introducing a temporary variable helps with this, it imposes an order and gives a name to a partial result. However, not everything that benefits from these aspects also benefits from having its type spelled out:

user = db.get_poster(request.post['answer'])
name = db.get_display_name(user)

Does it matter whether user is an entity object, an integer, a string, or something else? For most purposes, it does not, it's enough to know that it represents a user, comes from the HTTP request, and is used to fetch the name to display in the lower right corner of the answer.

And when it does matter, the author is free to write out the type. This is a freedom that must be used responsibly, but the same is true for everything else that can enhance readability (variable and function names, formatting, API design, white space).
And indeed, the convention in Haskell and ML (where everything can be inferred without extra effort) is to write out the types of non-local functions functions, and also of local variables and functions whenever appropriate. Only novices let every type be inferred.