问:
Is there a math theory or a model behind programming languages design
I'm trying to understand if a programming languages design is built on some a theoretical model.

I came across few links that was describing Programming Language Theory, Lambda Calculus, Formal Languages and Turing machine.

I got lost in all that theory, what I understood from all that is that (any ..?) programming language is built on lambda calculus, that boils down to few language constructs.

is my understanding correct?

are there any models other than lambda calculus?

if the languages shares the same model, can we use that to convert a source code from one language to the other?

答:
is my understanding correct?

Not really. Functional programming is more a set of features originally inspired by lambda calculus than a foundation for an entire language design. Some purely functional languages might come close but I suspect they'd still have to have some rules that don't relate directly to lambda calculus. And of course not all languages have the features required for functional programming.

are there any models other than lambda calculus?

If by that you mean feature sets inspired by other branches of mathematics, then absolutely, without a doubt. Basic features implemented in most languages are tied directly to all manner of specific branches of math. But not all features necessarily are. Object Oriented Programming, for instance, is a concept meant to help programmers structure and model code more intuitively while avoiding some of the pitfalls people tend to run into in procedural programming. If it has a direct branch of mathematics analogue, I've never seen that pointed out anywhere.

if the languages shares the same model, can we use that to convert a
  source code from one language to the other?

Well, what does "same model" mean. They follow all the same rules, varying slightly only in syntax? That would be easy enough. But a single core rule-change could make translating one to the other very messy. Strict vs dynamic types for instance. How would you write a JavaScript object's methods to follow all the same rules as a Java object? Other features like how scope works, or the absence/presence of closures would require a lot of overhead to emulate in universal way between language paradigms.

I think the closest thing to a common link you could find between all languages is that ultimately they all have to boil down to instructions that can somehow be broken down and executed in machine code terms on a given system (and machine code varies depending on architecture too). The complexity inherent in making a universal programming translator would be both insanely hard, if possible, but also massively fail to produce legible translated code between languages without massaging and special libraries that would make it fail the 'universal' test. I wouldn't be shocked if someone had proven this feat to be technically impossible.


问:
Improving the Java development workflow
I will like to assist my group standardize to a reproducable Java tooling environment that aligns with some good practices to improve on our workflow.  We are predominantly a .NET shop that has been doing quite a bit of Java development recently and have been burned too many times with our current Java development process.

The process is ad-hoc, since we are kind of new to all things Java.  Each developer decides on their tool of choice (somewhat a good thing) and due to the lack of any kind of procedure in terms of 3rd party dependency management, we more often than not run into build or deployment problems and hit serious setbacks when developer machines have to be rebuilt for one reason or another.  Our Java development environments are simply neither consistent nor repeatable from one machine to another.

We do not have a similar problem with our .NET projects.  Everyone runs the same version of Visual Studio, Resharper, and all 3rd party and open source libraries.  Possibly because we pay for most of the stuff but there is also a consistent pattern across our C# projects where everything one needs is encapsulated into the solution file and all 3rd party dlls required for this solution are checked into sub a directory relative to the parent solution in source control.  Visual Studio helps here too with its version check but this process  is working well and I feel it could be replicated for our Java development efforts.

To help achieve this goal, I have compiled the following list of questions to gauge what the experts are using out there.

What Java development IDE do you use?   Eclipse, NetBeans or IntelliJ ?

Do you use a dependency management tool such as Apache Maven, Gradle, a standardize home grown solution, or does each developer determine what works best for them?  What we have

If the answer to 2, is yes, how do you integrate such tools with your build system?

Do you standardize on a specific version of the IDE, related tools and runtime?   For example, are all devs running Eclipse IDE for Java EE Developers 3.7, IntelliJ 12.1.6, JDK1.7 or 1.8 and are there any policies to enforce that all devs are using the same version?

How do you ensure that projects settings are consistent and repeatable across dev machines?   Do you mandate checking in all of a project settings into source control or just the respective source files?

For each tool, including IDE, dependency management and build, what selection process did you use?

Items highlighted in bold is what we are learning towards based on past experiences.  But it will be good to learn from what others are doing.

I will start by answering some of the questions, listing some of the problems we are facing:

Every developer uses Eclipse.  However Eclipse and JDK versions could differ from one machine to another.  Dev A could be running Eclipse Juno with JDK 1.6 while Dev B is  running Eclipse Galileo with JDK 1.7.  The build machine could be running something different and we will only know there is a problem next morning when build is broken.  WIth resources also distributed across continents, this causes serious headaches.  For IDE standardization, I am leaning towards IntelliJ for usability and consistency, just to name a few.

We do not use any such tool.  Instead all 3rd party libs are stored in a 3rdParty central folder outside of the solution tree.  Then we have an Eclipse project setup to reference these JARs.  This works well but this 3rdparty folder is very large.  So if you do not want to selectively checkout the JARs you need just to get this project compile, you are in for a long morning waiting to check out the entire 3rdParty folder from SVN.  For dependency management, I am leaning towards Maven.

We use raw ANT scripts.  Each developer needs to ensure that all the stuff required to  build the project is checked into source control. But because these resources are all over the place, remember, the 3rd party folder is not part of the project tree, it is very easy  to forget checking in that new dependent JAR downloaded from somewhere.  And if you use Maven, like I do, I need to copy the JAR from my local Maven repo to the relevant centrll 3rdParty folder so that the build machine does not complain.  However, there is still a good chance that this build will fail since the build environment could also be different.  For build and packaging, I am also leaning towards  Maven to ensure that the build environment is similar to the dev environment.  I want to relieve the pain of having to remember where to put dependencies.

No.  See answer 1.

We do not, possibly because we are not saving the entire Eclipse workspace into source control.  So if I receive a new machine and check out an Eclipse project, I will have to spend a good portion of my day configuring project settings that should have been saved in source control.

TIA for all comments.

EDIT:  Just to add that we do have a CI server and use Jenkins/ANT scripts for building.

Klaus

答:
First: Get a copy of Clean Code and Effective Java for every developer. And use Git and Gerrit.

Standardize on one version of one IDE (we use Eclipse) that everybody uses. Make sure it's kept up-to-date (you seem to be using Eclipse versions that are seriously out of date). Make sure that most of the settings (like code formatting) are shared between machines. Make sure everybody runs the latest JDK.

Set up a CI server

We use ant but you should seriously consider Maven or Gradle.

Check in all files the IDE needs on a clean install of the project.

Open source software is cheaper in the long run and you can fix errors yourself. If needed, commercial support is available.

ContentLicense: CC BY-SA 3.0

Title: Improving the Java development workflow


答:
I'm trying to understand if a programming languages design is built on some a theoretical model.

No unifying theory has surfaced, but different aspects of programming languages are studied separately and may introduce their own theories. To name a few:

Type systems

Exception handling mechanisms and models

Co-routines

Concurrency stuff (models and mechanisms)

Macros

Binding/composition/extensions (ex: aspects, subject-oriented, context-oriented, prototypes, traits, multi methods, predicate dispatch, etc)

I came across few links that was describing Programming Language Theory, Lambda Calculus, Formal Languages and Turing machine.

These are more used and appropriated to investigate limits of computation, etc. Though lambda calculus (and other calculi) is used as medium to model programming mechanisms to be used in practice.

I got lost in all that theory, what I understood from all that is that (any ..?) programming language is built on lambda calculus, that boils down to few language constructs.

Depends on how you interpret "built on lambda calculus". Many language are not designed from lambda calculus (or any other formal system), that is, a designer does not start with lambda calculus and end up with, say, Go. These two just share  a theoretical correspondence, and when you want to investigate computational complexity, you go to these systems which are better suited for such study.

Title: Is there a math theory or a model behind programming languages design

Body:
I'm trying to understand if a programming languages design is built on some a theoretical model.

I came across few links that was describing Programming Language Theory, Lambda Calculus, Formal Languages and Turing machine.

I got lost in all that theory, what I understood from all that is that (any ..?) programming language is built on lambda calculus, that boils down to few language constructs.

is my understanding correct?

are there any models other than lambda calculus?

if the languages shares the same model, can we use that to convert a source code from one language to the other?


问:
Approach to algorithm for assignment of resources
We have a requirement to be able to match people with locations based on availability and certain conditions.

Let's say I have a group of people each with 3 types of things they may need to park.  A car, a truck and a boat.  Each person also indicates their preferred parking location (choices 1, 2 and 3).

I also have a list of parking locations which can handle a certain number of each of those things.  The goal is to match everyone up so that we maximum usage.  The main requirement is that each individual person has to be able to park everything in the same location OR they don't get to park at all.

Example:

Starting with the parking locations I have:

```<code>Lot    Cars    Trucks    Boats
A       2       0         2
B       2       1         3
C       0       5         0
</code>```

For people I have:

```<code>Person    Cars    Trucks    Boats    Choice 1  Choice 2  Choice 3
Tom        2       1         0         A         B         C
Betty      1       0         1         B         C         A
Sam        0       2         0         C         A         B
Pat        3       2         1         A         C         B
</code>```

My initial thought is to simply sort the people by the number of items they have (largest to smallest).  Then attempt to place each one based on choice.  IE: I'd try to place Pat first (most items), but couldn't because no lot meets the requirements.  Then I'd try Tom, who would go into Lot B.  Etc.

Do you know of any issues with that approach?

Bonus points: is there a name for this type of problem?

答:
This seems like a variant of the Knapsack problem however instead of having a single bag you have several and each item has a preference about which bag it belongs to. Consult your local Computer Science department for confirmation.

If it is a Knapsack problem variant then you're into NP-Complete territory in terms of complexity. Which means pragmatically you're looking at an optimisation problem, so find the solution that is as close to optimal as possible.

OwnerDisplayName: Chris Lively


答:
How about something like this:

```<code>Create a list of Lots lots.
Sort this list by the number of resources (cars + trucks + boats)

While lots is not empty:
    Lot next_lot = The lot that has the least amount of resources.
    Find the Person person who fits in this lot and takes up most of its resources.
    Place person into next_lot.
    Remove next_lot from lots.
</code>```

I would imagine that this would minimize fragmentation.

Title: Approach to algorithm for assignment of resources

Body:
We have a requirement to be able to match people with locations based on availability and certain conditions.

Let's say I have a group of people each with 3 types of things they may need to park.  A car, a truck and a boat.  Each person also indicates their preferred parking location (choices 1, 2 and 3).

I also have a list of parking locations which can handle a certain number of each of those things.  The goal is to match everyone up so that we maximum usage.  The main requirement is that each individual person has to be able to park everything in the same location OR they don't get to park at all.

Example:

Starting with the parking locations I have:

```<code>Lot    Cars    Trucks    Boats
A       2       0         2
B       2       1         3
C       0       5         0
</code>```

For people I have:

```<code>Person    Cars    Trucks    Boats    Choice 1  Choice 2  Choice 3
Tom        2       1         0         A         B         C
Betty      1       0         1         B         C         A
Sam        0       2         0         C         A         B
Pat        3       2         1         A         C         B
</code>```

My initial thought is to simply sort the people by the number of items they have (largest to smallest).  Then attempt to place each one based on choice.  IE: I'd try to place Pat first (most items), but couldn't because no lot meets the requirements.  Then I'd try Tom, who would go into Lot B.  Etc.

Do you know of any issues with that approach?

Bonus points: is there a name for this type of problem?

Body:
How about something like this:

Create a list of Lots lots.
Sort this list by the number of resources (cars + trucks + boats)

While lots is not empty:
    Lot next_lot = The lot that has the least amount of resources.
    Find the Person person who fits in this lot and takes up most of its resources.
    Place person into next_lot.
    Remove next_lot from lots.

I would imagine that this would minimize fragmentation.


问:
Is it possible to be good at both programming and graphic design?
The stereotypical view of a programmer can't do graphics very well, from what I've read and seen. However, I love programming (preferably OOP, PHP, C++, Objective-C) and can't deny the fact I have a unique taste in web design and others have said I am doing well at it (CSS). I thought to myself "Hey, wait, I'm a programmer - how can I design well?". Question is: is it possible to be good at programming and designing? Does anyone here feel the same?

For the record: actual images I have created have been called programmer art several times before by friends

答: You can be good at anything you wish.  It just takes enough practice.  But we're talking practice on the level of thousands of hours, so it takes some dedication.</p>

ContentLicense: CC BY-SA 2.5


问:
What is the difference between method header and method signature?
I want to know what is exactly a method header and what is a method signature and is this the same among programming languages or just in C#?

So, is it correct to say the following is a method header:

```<code>public void SumNumbers(int firstNumber, int secondNumber)
</code>```

and the following is the method signature:

```<code>public void SumNumbers(int, int)
</code>```

?

答:
According to the C# spec, a method header consists of:

attributesopt method-modifiersopt return-type member-name (formal-parameter-listopt)

So to extend what you've shown:

```<code>[OperationContract]
public void SumNumbers(int firstNumber, int secondNumber)
</code>```

Above example contains examples of the possible parts that make up a method header, while the minimum (all non-optional parts) would be something like:

```<code>void Foo()
</code>```

As for the signature, see 3.6 Signatures and overloading:

The signature of a method consists of the name of the method and the type and kind (value, reference, or output) of each of its formal parameters, considered in the order left to right. The signature of a method specifically does not include the return type, nor does it include the params modifier that may be specified for the right-most parameter.

The following example shows a set of overloaded method declarations along with their signatures.

```<code>interface ITest
{
   void F();                  // F()
   void F(int x);             // F(int)
   void F(ref int x);         // F(ref int)
   void F(int x, int y);      // F(int, int)
   int F(string s);           // F(string)
   int F(int x);              // F(int)         error, F(int) already exists
   void F(string[] a);        // F(string[])
   void F(params string[] a); // F(string[])      error, F(string[]) already exists
}
</code>```

So the signature of your second example would be:

```<code>SumNumbers(int, int)
</code>```

See also Method Signature in C# on SO, especially Eric Lippert's answer.

Body:
According to the C# spec, a method header consists of:

attributesopt method-modifiersopt return-type member-name (formal-parameter-listopt)

So to extend what you've shown:

[OperationContract]
public void SumNumbers(int firstNumber, int secondNumber)

Above example contains examples of the possible parts that make up a method header, while the minimum (all non-optional parts) would be something like:

void Foo()

As for the signature, see 3.6 Signatures and overloading:

The signature of a method consists of the name of the method and the type and kind (value, reference, or output) of each of its formal parameters, considered in the order left to right. The signature of a method specifically does not include the return type, nor does it include the params modifier that may be specified for the right-most parameter.

The following example shows a set of overloaded method declarations along with their signatures.

interface ITest
{
   void F();                  // F()
   void F(int x);             // F(int)
   void F(ref int x);         // F(ref int)
   void F(int x, int y);      // F(int, int)
   int F(string s);           // F(string)
   int F(int x);              // F(int)         error, F(int) already exists
   void F(string[] a);        // F(string[])
   void F(params string[] a); // F(string[])      error, F(string[]) already exists
}

So the signature of your second example would be:

SumNumbers(int, int)

See also Method Signature in C# on SO, especially Eric Lippert's answer.


问:
What to consider when designing a web application that will be deployed under a load balancer?
I am currently maintaining a Java web application that is initially designed to work only as a single instance (not in a cluster/farm). Now, the client is planning to upgrade their infrastructure and part of their plan is to place our web application behind a load balancer.

I have already identified several serious design problems:

Users can upload files and our application store those files in the local filesystem.

There are scheduled jobs that might cause problems when executed concurrently (i.e. generating files).

Session variables are heavily used in most modules.

I need opinion on my proposed solutions below.

I can solve item 1 by storing all files in an external/shared storage (SAN, etc..)

With item 2, I can create a locking mechanism in the database so when the scheduled jobs run, the web apps will first check the table and only the first one to update will run the said job.

Actually, I'm still not sure if item 3 can cause problems. If a user logs in to our application and the load balancer directs him to Server 1, is it possible that the load balancer will point him to Server 2 the next time he click a link? I have no idea yet how the load balancer works in this level.

Also, what are the other things that I should consider when designing a horizontal-scalable web application [from scratch]?

答:
Users can upload files and our application store those files in the local filesystem.

  I can solve item 1 by storing all files in an external/shared storage (SAN, etc..)

Storing the common static resources on an external system that is accessible to all is certainly one way to approach the issue of users uploading files that you then have to save.  This cuts down many problems and completely bypasses the ugly issue of trying to do synchronization of local file systems (don't go down that route, it only leads to madness).

There are scheduled jobs that might cause problems when executed concurrently (i.e. generating files).

  With item 2, I can create a locking mechanism in the database so when the scheduled jobs run, the web apps will first check the table and only the first one to update will run the said job.

Dealing with scheduled jobs that write 'static' data, you get into some other ugly situations.

The first thing to consider is what are they generating?  If they are generating other smallish files, why not store the generated data in the database instead.  This also solves the 'locking' problem to a degree (in that it offloads it to the database).  Then, the application would need to read the data out of the database instead of the file system.

When you go "ewww" when thinking about a heavy oracle database doing this, you might also consider a lighter nosql database.  Using the file system for locking has other problems that make it a bit less desirable.  Using multiple different systems (database and file system) doesn't quite have the same race conditions (they are other ones to consider), but it also means the two need to stay properly in sync.  The joys of removing database locks when the application terminates improperly.

Store the generated content in the database, and you should be good.  It makes several things much easier.  Consider things such as records with timestamps and then you just select the most recent time stamp that is done.

There are other things to think of here, such as having a service on the application servers that will write a file that comes in from a specific client (so your scheduled job pushes the to the application server which writes it to the common file system), or having some messaging system that notifies the application servers of new content in a certain location that triggers an application to pull the data to a local file system.

There are lots of different ways to approach this for single updates that get pushed to the content area.  This could be the subject of a whole new question itself depending on the specifics of the problem and the constraints of the system.

Session variables are heavily used in most modules.

  Actually, I'm still not sure if item 3 can cause problems. If a user logs in to our application and the load balancer directs him to Server 1, is it possible that the load balancer will point him to Server 2 the next time he click a link? I have no idea yet how the load balancer works in this level.

The key concept you are looking for there is 'sticky session'.  It falls under the area of 'load balancer persistance'

In this, the load balancer also is aware of the sessions created and when a session request comes through for one system it will always keep it 'stuck' to the application server that generated it.

This isn't without its own set of issues (one system goes down, the sessions switch to the other one (you've got failover, right?) and then comes back up, but now all the load is stuck to the other server).

Realize that the exact nature of this support is dependent on the load balancer being used.  Some have their own cookie, some use JSESSIONID and the like, others use ip (and if you've got a firewall/proxy of some sort there, it may look like all the requests come from the same ip).

You may also want to look at an external cache for sessions so they are shared between both machines rather than doing load balancing between them.  Some frameworks have this, or you might look at other caching solutions to go down this route.  Again, possibly a topic of a new question if there is more information on the environment and the constraints as this is getting reasonably long too.


问:
How do we keep dependent data structures up to date?
Suppose you have a parse tree, an abstract syntax tree, and a control flow graph, each one logically derived from the one before. In principle it is easy to construct each graph given the parse tree, but how can we manage the complexity of updating the graphs when the parse tree is modified? We know exactly how the tree has been modified, but how can the change be propagated to the other trees in a way that doesn't become difficult to manage?

Naturally the dependent graph can be updated by simply reconstructing it from scratch every time the first graph changes, but then there would be no way of knowing the details of the changes in the dependent graph.

I currently have four ways to attempt to solve this problem, but each one has difficulties.

Nodes of the dependent tree each observe the relevant nodes of the original tree, updating themselves and the observer lists of original tree nodes as necessary. The conceptual complexity of this can become daunting.

Each node of the original tree has a list of the dependent tree nodes that specifically depend upon it, and when the node changes it sets a flag on the dependent nodes to mark them as dirty, including the parents of the dependent nodes all the way down to the root. After each change we run an algorithm that is much like the algorithm for constructing the dependent graph from scratch, but it skips over any clean node and reconstructs each dirty node, keeping track of whether the reconstructed node is actually different from the dirty node. This can also get tricky.

We can represent the logical connection between the original graph and the dependent graph as a data structure, like a list of constraints, perhaps designed using a declarative language. When the original graph changes we need only scan the list to discover which constraints are violated and how the dependent tree needs to change to correct the violation, all encoded as data.

We can reconstruct the dependent graph from scratch as though there were no existing dependent graph, and then compare the existing graph and the new graph to discover how it has changed. I'm sure this is the easiest way because I know there are algorithms available for detecting differences, but they are all quite computationally expensive and in principle it seems unnecessary so I'm deliberately avoiding this option.

What is the right way to deal with these sorts of problems? Surely there must be a design pattern that makes this whole thing almost easy. It would be nice to have a good solution for every problem of this general description. Does this class of problem have a name?

Let me elaborate on the troubles that this problem causes. This issue pops up in various places, whenever two parts of a project operate on graphs, with each graph being a different representation of the same thing that changes while the software is running. It's like making an adapter for an interface, but instead of wrapping a single object or a fixed number of objects, we need to wrap an entire graph of arbitrary size.

Every time I try this I end up with a confusing unmaintainable mess. The control flow of observers can be difficult to follow when it gets complicated, and the algorithm for converting one graph to another is usually tricky enough to follow when its laid out plainly and not spread across multiple classes. The problem is that there seems to be no way to use just a plain, straight-forward graph conversion algorithm when the original graph is changing.

Naturally we can't just use an ordinary graph conversion algorithm directly because that can't respond to changes in any way other than starting from scratch, so what are the alternatives? Perhaps the algorithm could be written in a continuation-passing style where each step of the algorithm is represented as an object with a method for each type of node in the original graph, like a visitor. Then the algorithm can be assembled by composing various simple visitors together.

Another example: Suppose you have a GUI that is laid out like you might in Java Swing, using JPanels and layout managers. You can simplify that process by using nested JPanels in place of complex layout managers, so you end up with a tree of various containers that includes nodes that exist only for layout purposes and are otherwise meaningless. Now suppose that the same tree that is used to generate your GUI is also used in another part of your application, but instead of laying the tree out graphically it is working with a library that will generate an abstract representation tree as a system of folders. In order to use this library, we need to have a version of the tree that doesn't have the layout nodes; the layout nodes need to be flattened into their parent nodes, but the library still needs to be notified each time the tree changes as though the two versions of the tree were a single data structure.

Another way to look at it: The very concept of working with mutable trees violates the Law of Demeter. It wouldn't really be a violation of the law if the tree were a value as parse trees and syntax trees normally are, but in that case there would be no problem since nothing would need to be kept up-to-date. So then this problem exists as a direct result of violating the Law of Demeter, but how do you avoid that in general when your domain seems to be about manipulating trees or graphs?

The Composite pattern is a wonderful tool for turning a graph into a single object and obeying the Law of Demeter. Is it possible to use the Composite pattern to effectively turn one kind of tree into another? Can you make a Composite parse tree so that it acts like an abstract syntax tree and even a control flow graph? Is there a way to do it without violating the single responsibility principle? The Composite pattern tends to cause classes to absorb every responsibility that they touch, but perhaps it could be combined with the Strategy pattern somehow.

答:
You seem to be thinking of a general case of 2 graphs, where the second can be entirely derived from the first, and you want to efficiently re-compute the 2nd graph when a portion of the first changes.

This doesn't seem conceptually different than the problem of minimizing re-computation in just the first graph, though I suppose when implemented in a particular system they are probably different types in each graph.

It's pretty much all about tracking dependencies, both within and between graphs.  For each node that is changed, update all dependents, recursively.

Of course, before doing any updates, you want to topologically sort your dependency graph.  This lets you know if you have circular dependencies creating a potentially infinite wave of updates, and also insures that for any node you will update all of its dependents before updating that node, thus avoided pointless computation that will have to be redone later.

You don't particularly have to express the dependencies in a declarative language, but you can, that's an entirely independent issue.

This is a general algorithm, and in particular cases there might be more you can do to speed it up.  It may be that some of the work you are doing to update one dependency is also useful in updating other dependencies, and a good algorithm would take advantage of that.

As far as the graph conversion algorithm being an unmaintainable mess, the solution is somewhat language specific but an object-oriented approach might be to have some classes that purely deal with updating dependencies in general - representing dependencies, doing a topological sort, and triggering calculations.  To do the calculation, they delegate to your actual classes, possibly using a first-class function they were handed when they were created, possibly because the classes they hand off to must implement an interface (as usual if they can't because, for example, you didn't create them, you can use an adaptor).  I suppose in some cases you could use reflection to gather the graph information from the graph of object relationships and call the methods that way, if that's easier to set up and you don't mind that kind of meta-programming.


答:
Yes. It is possible. Don't listen to anyone who says it's not.

I myself started with system programming then did some applied programming. All I did before was programming algorithms, designing data structures, designing database models and all the usual stuff. I thought I was a programmer with all the usual limitations.

Then I went programming for the web. I guess it only natural that the graphical thing found me. I got fascinated by a new realm and soon afterward discovered a designer gene in me. Now I'm more interested in design than in code.

Know this. If you possess la fibre du design, you need to nurture it, let it grow and blossom. Try things out, experiment, let it develop into whatever it is meant to be with you.

Title: Is it possible to be good at both programming and graphic design?

Body:
The stereotypical view of a programmer can't do graphics very well, from what I've read and seen. However, I love programming (preferably OOP, PHP, C++, Objective-C) and can't deny the fact I have a unique taste in web design and others have said I am doing well at it (CSS). I thought to myself "Hey, wait, I'm a programmer - how can I design well?". Question is: is it possible to be good at programming and designing? Does anyone here feel the same?

For the record: actual images I have created have been called programmer art several times before by friends


问:
Code repetition vs multi responsible method
I try to follow the Single Responsibility Principle (SRP) and also to omit Code Repetitions. However there are often places where there are code repetitions that are nothing more than code blocks of invocations that are resistant to extracting them into at least meaningfull named method:

```<code>DoAction1();
DoAction2();

if (value)
    DoAction3();

DoAction4();
</code>```

What is the best way to extract such code into a method and how to name it?

答:
If you're truly following Single Responsibility Principle, then this block of code must have some specific purpose, right? Otherwise these methods would be in separate classes.

So then, what is the purpose of this code block? Determine that and you ought to be able to come up with a name.

If you still cannot figure out the name for this thing, then maybe these methods don't actually belong together at all. I.e. this class/code block has more than one responsibility. In that case, refactoring to split up the tasks may reveal better purpose-revealing name.

OwnerDisplayName: yBee


问:
How to ensure that a member variable is initialized before calling a class method
There's a class with a parametrized constructor that initializes a member variable. All public methods of the class then use this member variable to do something.

I want to ensure that the caller always creates an object using the parametrized constructor (there is also a setter for this member variable) and then call that object's methods. In essence, it should be impossible for the caller to call any method without setting a value to the member variable (either by using the parametrized constructor or the setter). Here's the catch - there is just one method that itself generates a value to be initialized in the member variable (and returns it) - and to call that function, one would need a default constructor.

Currently, a caller can simply make an object using the default constructor and then call that object's method - I want to avoid checking whether or not the member variable is set in each and every one of the 20-odd methods of the class (and throw an exception if it is not) - except for the one method mentioned above.

Though a runtime solution is acceptable (better than the one I mentioned above); a compile-time solution is preferable so that any developer will not be allowed to make that mistake and then waste hours debuggging it!

Update: Here's an artist's impression of the current implementation in code:

```<code>class MyClass
{
private:
string m_strProperty;

void InternalNonStaticMethod(int iSomeParam);

public:
MyClass(string strValue)
{
m_strProperty = strValue;
}

MyClass() {}

void setProperty(string strValue)
{
    m_strProperty = strValue;
}

string MethodOddManOut()
{
    /* Do some computations to generate a value for the property */
    string strGeneratedValue("");
    InternalNonStaticMethod(4);
    /* ... */
    return strGeneratedValue;  // The value has to be returned and this method cannot simply update the member due to design issues that are beyond the realm of this question
}

void MethodLikeEveryoneElse()
{
    /* Do some computation based on the property */
    string strTemp = m_strProperty + "EXTEND";

    /* If strProperty is empty/garbage then this is going to fail miserably
       Trying to avoid the following snippet at 20 other similar methods:
       if (!strProperty.empty()) {
           strTemp = m_strProperty + "EXTEND";
       } else {
           throw exception
       }
    */
}

void MethodLikeEveryoneElse2()
{
    /* Similar to the above method */
}

}
</code>```

The caller would be a function in some other class using it like this:

```<code>void MethodThatUsesThis()
{
    MyClass objA;
    m_strHandle = objA.MethodOddManOut();  // Save the handle as a member of this object

    /* Some other lines of code */

    objA.setProperty(strHandle);
    objA.MethodLikeEveryoneElse();
}

void AnotherMethodThatUsesThisLater(string strHandle)
{
    MyClass objA(strHandle);  // The handle that the above method received was passed to this method since they are in different classes
    objA.MethodLikeEveryoneElse2();
}
</code>```

This code snippet is bound to raise tons of allegations on the horrendous design that is being implemented - but my only defense is, this is legacy code (ha! you saw this coming) and I only have the right to change anything in class A (it's more of an API and a library module) but the caller is not in my jurisdiction.

答:
This is the approache taken to get around the problem (better solutions are still welcome):

Write a private getter for the member in question that validates it's value and throws an exception. Use this getter in all member functions instead of directly using the member.

```<code>private:
hstring GetProperty()
{
    if (m_strProperty.empty()) {
        throw exception;
    } else {
        return m_strProperty;
    }
}

public:
void MethodLikeEveryoneElse()
{
    /* Do some computation based on the property */
    string strTemp = GetProperty() + "EXTEND";

    /* If strProperty is empty/garbage then this is going to fail miserably
       Trying to avoid the following snippet at 20 other similar methods:
       if (!strProperty.empty()) {
           strTemp = m_strProperty + "EXTEND";
       } else {
           throw exception
       }
    */
}
</code>```

This is still susceptible to programmer error (some developer may accidentally use the member variable directly) and is a runtime solution rather than a compile-time enforcement.

Body:
This is the approache taken to get around the problem (better solutions are still welcome):

Write a private getter for the member in question that validates it's value and throws an exception. Use this getter in all member functions instead of directly using the member.

private:
hstring GetProperty()
{
    if (m_strProperty.empty()) {
        throw exception;
    } else {
        return m_strProperty;
    }
}

public:
void MethodLikeEveryoneElse()
{
    /* Do some computation based on the property */
    string strTemp = GetProperty() + "EXTEND";

    /* If strProperty is empty/garbage then this is going to fail miserably
       Trying to avoid the following snippet at 20 other similar methods:
       if (!strProperty.empty()) {
           strTemp = m_strProperty + "EXTEND";
       } else {
           throw exception
       }
    */
}

This is still susceptible to programmer error (some developer may accidentally use the member variable directly) and is a runtime solution rather than a compile-time enforcement.


答:
I've had a situation which may be similar to yours:

There's a class that defines functionality of the object that it represents:

```<code>class Functionality
{
protected:
void functionA();
void functionB();
...
void functionZ();
}
</code>```

Then there's a class that defines the workflows for high-level operations that the object performs:

```<code>class Workflows: private Functionality
{
    void WorkflowA()
    {
        functionA();

        if (m_bValue) {
            functionB();
        }

        functionC();
    }
    ...
    void WorkflowB();
}
</code>```

If you're in a similar situation, then identify what your classes represent (in this case functionality/workflows) and then name the methods accordingly.

Disclaimer: The class names used in this example are grossly inaccurate, but the method names give a clue. Discretion advised.

Title: Code repetition vs multi responsible method

Body:
I try to follow the Single Responsibility Principle (SRP) and also to omit Code Repetitions. However there are often places where there are code repetitions that are nothing more than code blocks of invocations that are resistant to extracting them into at least meaningfull named method:

```<code>DoAction1();
DoAction2();

if (value)
    DoAction3();

DoAction4();
</code>```

What is the best way to extract such code into a method and how to name it?

Body:
I've had a situation which may be similar to yours:

There's a class that defines functionality of the object that it represents:

class Functionality
{
protected:
void functionA();
void functionB();
...
void functionZ();
}

Then there's a class that defines the workflows for high-level operations that the object performs:

class Workflows: private Functionality
{
    void WorkflowA()
    {
        functionA();

        if (m_bValue) {
            functionB();
        }

        functionC();
    }
    ...
    void WorkflowB();
}

If you're in a similar situation, then identify what your classes represent (in this case functionality/workflows) and then name the methods accordingly.

Disclaimer: The class names used in this example are grossly inaccurate, but the method names give a clue. Discretion advised.


问:
As a software engineer, who should I be following on Twitter?
Who in the software engineering and software development fields uses Twitter to tweet about relevant happenings in the field?</p>

答:
It depends. Each person has his/her own specialty.

I program in ASP.NET MVC, so I follow shanselman (Scott Hanselman), haacked (Phil Haack), scottgu (Scott Guhrie), and igoro (Igor Ostrovsky).
I am really glad they share their knowledge. I learn a lot from them.


问:
What are the data structures behind a spreadsheet?
I would like to understand how a spreadsheet (a group of named or otherwise identified cells containing values or formulas referencing other cells) is solved. I have tried looking at existing projects, but there was so much going on with the GUI, serialization, events, etc. that I couldn't find the spreadsheet.

At its simplest how does it work?

答: Conceptually, each cell is a node of a directed acyclic graph, and references to other cells create edges in that graph.  When you change a cell, a topological sorting of all the nodes reachable from the cell you changed will give you the order you need to evaluate the cells.  Once you've determined the correct order, it's just standard expression parsing.</p>


问:
How to compare features of two curves?
I need to compare two curves f(x) and g(x). They are in the same x range (say -30 to 30). f(x) may have some sharp peaks or smooth peaks and valleys. g(x) may have the same peaks and valleys. If so I want a measure on how well these features coincide without visual inspection. I have tried to solve this problem in the following way.

Normalize both functions by dividing each data point by the total area of the function. Now the area of the normalized function is 1.0

At each x get the minimum value out of f(x) and g(x). This will give me a new function that is basically the overlapping area between f(x) and g(x).

When I integrate the resulting function of step 2 I get the total overlapping area out of 1.0

However this does not tell me whether the peaks and valleys coincide or not. I am not sure if this can be done but if someone knows a method I would appreciate your help.

==EDIT==
For clarification I have included an image.

The difference between the two curves (black and blue) may not be the same but
will have complementing shapes.

Background:
The functions are projected density of states (PDOS) of atomic orbitals of a compound. So I have states for s,p,d orbitals. I want to determine whether the material has s-p, p-d or d-d hybridizations (orbital mixing). The only data I have is the PDOS. If say the PDOS of s orbital (function f(x)) has the peaks and valleys as at the same energies (x values) of the PDOS of p orbital (function g(x)) then there is s-p mixing in that material.

答:
As I undesrtand it, the information you are looking for is conveyed by the “tableau des variations” of the function—I am very sorry that I do not know the english name for this!

This table is associated to a differentiable function f and you construct it by finding the roots of f' and determine the sign of f' on each interval between these zeroes.

So, if the zeroes of f' and g' more or less coincide and the signs of theses functions agree, they will have a similar profile.

The first thing I would try to program would be:

Select a small ε

Draw randomly a large number N of points x[i] in the interval where the functions are defined.

For each node, compute the differences F[i] = f(x[i] + ε) - f(x[i] - ε) and G[i] = g(x[i] + ε) - g(x[i] - ε).

If at each node, F[i] and G[i] are both smaller than ε² OR have both the same sign, conclude that the two functions nearly have the same profile.

Does it work?

Title: How to compare features of two curves?


答: Sure you can be good at both.  Prior to being a programmer I was an Architect, a building Architect.  I've designed plenty of great, professional looking web sites (as described by clients, not techy people).  Now while this sites looked great, I'm by no means as skilled at graphic design as someone who does it full time, nor do I desire to be...</p>


问:
What are the downsides of RoR?
I'm currently trying to decide what server-side language to learn and use for web development, and while it's relatively easy to get information on why x, y, or z is a good thing, it's harder to figure out the downsides to each of them.

In particular, I'm curious about what drawbacks there are to learning and/or using Ruby on Rails as opposed to any other given language/framework.

答: I honestly can't understand those who wax poetically about what a walk in the garden Ruby-on-Rails is. I came to it as an experienced ASP.NET-MVC, Java, PHP, Python developer -- and found it to be the most horrible time-waster ever! 90 percent of the online google-answers are wrong or incomplete. Why? Has it changed that much every single year? Or is it that nobody cares about making code actually work? It took me massive amounts of time to just do simple things; far, far more than it would take me in C#/ASP.NET-MVC, for example. It certainly never took me anywhere near that long to learn my original technologies. Granted, ROR is terse. If that's important to you. But I found it rarely clear how to create code that would accomplish a task.  Personally, I would rather type on a keyboard for 20 seconds to write code that definitely works, is clear and you can follow it, rather than type terse Ruby code for 2 seconds, but which never works until I am up all night searching for some way to actually make it work. It is a horrible, stinking pile of dodo. Why? Is it that open-source (as in free) code, produces no incentives to make it a quality tool? Too many script-kiddies pumping revisions and modules and bad documentation into it? I don't know. But when I was finally able to escape that first Ruby-Rails project, I swore I'd never step into that mess again!</p>

Title: What are the downsides of RoR?


问:
Resources for understanding a programming language and its specifications and grammar deeply
I'm a computer engineer and all the courses we have had about programming and computer languages were an introduction to C/Java and OOP. Now I feel like reading Java language specification to learn a deep understanding on Java language but I understand that there are something like grammar description in the specifications which I have no idea about. What should I study to be able to understand a programming language deeply(Especially specification elements such as grammar)? Have I missed some computer science courses? or I should understand all intuitively?

I was pondering about reading some books about compilers but I thought it'd be better asking it from the experts!

答: Study a programming language as you would study a spoken language.  Grammar is important, and you can learn that from the formal specification of the language, but grammar only goes so far.  Vocabulary matters too - actually, more.  Every programming language has its collection of "words" - Java's Base Class Library, Lisp's common functions, C's Standard Library, etc.  But even practice with vocabulary will only get you so far.  Every programming language also has its idioms, and being able to use those well is the mark of a native speaker.


问:
GIT and different versions of a project: what are the best practices?
I'm very new in using GIT as a versioning system and despite a lot of searches, I can't seem to really understand how to handle my scenario.

I have this web project that needs to be developed in two versions:

the first is a general version used for demos

the second is a customized version for my client.

As for now, the second versions differs in minor things, mainly branding (i.e. icons, some titles) and database connections.

The idea is to enhance its code with suggestions and real use cases provided by the client and, as we progress with bugfixes and new features, port the changes to the "general/unbranded version" - but keeping those minor differences.

In the future the "general" version could be forked and enhanced more with some independent features.

Are branches an useful way to deal with this scenario? I think they're not, as (at least so I understood) they're more meant to make changes to be merged back in short- or mid-term.

答:
Take a look here:

https://stackoverflow.com/questions/19840921/override-configured-user-for-a-single-git-commit/19841122#19841122

Although the question is somewhat different, the answers provided by myself and others explain how you can create 2 separate/local git versions of the same system.

Based on what you're trying to do, I would think of a "Master/Slave" scenario, where the demo (=Master) is where most of the work will be done. You can then fork over the demo into a separate folder and run git on that, where you can do work on it (meaning a you will need to see .git in each custom folder where work is being done)

Now when you do updates to the demo and would like to see these updates in your "slave" custom work, you will need to merge the new "master" with the "slave" on the custom-work(=slave) folder.

That way:

The demo project always remains a demo

Custom work is kept separate

You can create as many different customs as you like, each with their
own version control

You can merge updated demo work to each custom,
without mixing up the core demo (you need to remember and learn how
to merge onto the slave)

Take a look at this video for using git: http://vimeo.com/46010208

Somebody once referred it to me for learning git and I found it very useful, that is why I am referring it to you.


答:
Yes.

I'm actually good at programming and at graphic design. I program since I was 10 and design since I was 16 (now I'm 31). I always liked both fields, and practiced and learned both. But I was able to raise to a professional level only programming. But my graphic skills this helped me a lot also in GUI design.

I know a lot of programmers that are stuck with the idea that a programmer can't do design. So they just skip that part. When they had to prototype a GUI or sketch some graphic, they do that with such a bad attitude, that the results are actually horrible. But isn't programming itself a creative work?


问:
How is it called when you define constants that simply refer to a large namespace?
I am using JRuby.

I have many classes implemented in Java, and I want to create objects off of them in my Ruby scripts.

Suppose that I have a class Sprite in Java. In Ruby, to refer to it, I use the following:

```<code>Java::ComMyWebsiteMyProjectName::Sprite
</code>```

Because Sprite is defined in the package com.myWebsite.myProjectName.

Now then, to simplify things, I like to do this:

```<code>Sprite = Java::ComMyWebsiteMyProjectName::Sprite
</code>```

Which sets the constant Sprite to the Sprite class defined in Java. Now my Ruby code can refer to it by just writing Sprite.

I have a file full of that kind of declarations. Something like:

```<code>Sprite   = Java::ComMyWebsiteMyProjectName::Sprite
Texture  = Java::ComMyWebsiteMyProjectName::Texture
Bitmap   = Java::ComMyWebsiteMyProjectName::Bitmap
Math     = Java::ComMyWebsiteMyProjectName::Math
Geometry = Java::ComMyWebsiteMyProjectName::Geometry
</code>```

Now, I am not exactly very familiar with programming concepts. I am having problems giving this file a name, because I don't even know if there is a name for this kind of thing. Does this kind of "practice" have an actual name?

答:
This is known by many different names - and probably called even more.  And sometimes what you think is type aliasing in one language is something completely different in another.

In Perl, you've got code that looks like:

```<code>#!/usr/bin/perl

package Foo::Bar::Qux::Bletch;
$var = 42;

package main;
print $Foo::Bar::Qux::Bletch::var, "\n";
*A = *Foo::Bar::Qux::Bletch::var;
print $A,"\n";
</code>```

Which is known by various things such as a typeglob alias or just glob aliasing - though it should be realized that a glob is something else.

In Clojure, this is simply an alias:

```<code>user=> (require 'clojure.string)
nil

user=> (alias 'string 'clojure.string)
nil

user=> (string/capitalize "hONdURas")
"Honduras"
</code>```

In Ruby it appears to have the name of namespace alias as described in ruby-forum: Namespaces too looooooong

However it occurred to me that there is a difference between
  namespace aliases in PHP and the closest thing in Ruby (as
  described above): Autoloading.

In php, this is again, a namespace alias - php.net: Using namespaces: Aliasing/Importing

The ability to refer to an external fully qualified name with an alias, or importing, is an important feature of namespaces. This is similar to the ability of unix-based filesystems to create symbolic links to a file or to a directory.

  PHP namespaces support three kinds of aliasing or importing: aliasing a class name, aliasing an interface name, and aliasing a namespace name. Note that importing a function or constant is not supported.

In Lisp, this isn't part of the standard language but there libraries which do it and call themselves 'package-local alias' or 'nicknames'.  One such library is cl-package-aliases which provides some additional functionality:

```<code>* (defpackage :foo (:use :cl) (:alias (:common-lisp :bar)))

# <PACKAGE "FOO">
* (in-package :foo)

# <PACKAGE "FOO">
* (bar:format t "Hello World~%")
Hello World
NIL
</code>```

In python, this is a namespace alias. (Examples from Can you define aliases for imported modules in Python?)

```<code>import a_ridiculously_long_module_name as short_name
</code>```

Though you can also do it with an assigment

```<code>import long_module_name
lmn = long_module_name
</code>```

In C# this is a namespace alias.

From Java equivalent to C# using alias

```<code>namespace TheirNamespace
{
    public class ContestedClassName
    {
    }
}

namespace MyNamespace
{
    public class ContestedClassName
    {
    }
}

namespace MyBoundaryNamespace
{
    using MyRenamedClass = MyNamespace.ContestedClassName;
    using TheirRenamedClass = TheirNamespace.ContestedClassName;

    public class Translator
    {
        public TheirRenamedClass Translate(MyRenamedClass value)
        {
            return null;
        }
    }
}
</code>```

In Java, one doesn't alias a namespace, but rather imports specific items into the current namespace, though it does serve the question asked (how to reduce the amount of typing):

The code

```<code>double r = cos(Math.PI * theta);
</code>```

can be reduced with a static import to:

```<code>import static java.lang.Math.PI;
...
double r = cos(PI * theta);
</code>```

One often sees this usage with Junit to avoid having to specify each static method.

```<code>import static org.junit.Assert.*;
</code>```

When people speak of type aliasing in Java it is more along the lines of:

A problem I often encounter in Java is that I want to say “these two
  things are the same”, but Java won’t let me. Suppose I want to
  maintain an int[] array which is always sorted in my program.

which gets to more of the type aliasing rather than namespace aliasing, because these are different things.

Type aliasing in Scala appears to be something quite different based on Beginner: Scala type alias in Scala 2.10? and Scala type alias including companion object

More about what type aliasing in Scala is can be found at Effective Scala

In C++11 type aliases are a type of typedef which does more things other than namespace juggling.

```<code>using identifier = type_name;
</code>```

An example of this would be:

```<code>user=> (require 'clojure.string)
nil

user=> (alias 'string 'clojure.string)
nil

user=> (string/capitalize "hONdURas")
"Honduras"
</code>```0

Though realize, there are some differences between these concepts as descried in  Difference between typedef and C++11 type alias

The playing of namespaces however, is a namespace alias as described in In C++, what is a "namespace alias"?

```<code>user=> (require 'clojure.string)
nil

user=> (alias 'string 'clojure.string)
nil

user=> (string/capitalize "hONdURas")
"Honduras"
</code>```1

More on this at msdn namespace Alias

```<code>user=> (require 'clojure.string)
nil

user=> (alias 'string 'clojure.string)
nil

user=> (string/capitalize "hONdURas")
"Honduras"
</code>```2

http://hyperpolyglot.org/ml shows a few languages with various forms of namespace aliasing.

OCaml:

```<code>module Gr = Graphics;;
</code>```

Haskell:

```<code>import qualified Data.Bytestring as B
</code>```

Namespaces aren't unique to programming languages, but also extend to other structured data such as XSL  which has namespace aliases.  These tend to be rather terse transformations (converting 'alt' to 'xsl' or something like that - but they serve the same purpose.

So, as noted, these concepts go by different names in different languages and what is known as 'type aliasing' in one language may mean something completely different in another language.

There is no standard name

Body:
This is known by many different names - and probably called even more.  And sometimes what you think is type aliasing in one language is something completely different in another.

In Perl, you've got code that looks like:

#!/usr/bin/perl

package Foo::Bar::Qux::Bletch;
$var = 42;

package main;
print $Foo::Bar::Qux::Bletch::var, "\n";
*A = *Foo::Bar::Qux::Bletch::var;
print $A,"\n";

Which is known by various things such as a typeglob alias or just glob aliasing - though it should be realized that a glob is something else.

In Clojure, this is simply an alias:

user=> (require 'clojure.string)
nil

user=> (alias 'string 'clojure.string)
nil

user=> (string/capitalize "hONdURas")
"Honduras"

In Ruby it appears to have the name of namespace alias as described in ruby-forum: Namespaces too looooooong

However it occurred to me that there is a difference between
  namespace aliases in PHP and the closest thing in Ruby (as
  described above): Autoloading.

In php, this is again, a namespace alias - php.net: Using namespaces: Aliasing/Importing

The ability to refer to an external fully qualified name with an alias, or importing, is an important feature of namespaces. This is similar to the ability of unix-based filesystems to create symbolic links to a file or to a directory.

  PHP namespaces support three kinds of aliasing or importing: aliasing a class name, aliasing an interface name, and aliasing a namespace name. Note that importing a function or constant is not supported.

In Lisp, this isn't part of the standard language but there libraries which do it and call themselves 'package-local alias' or 'nicknames'.  One such library is cl-package-aliases which provides some additional functionality:

* (defpackage :foo (:use :cl) (:alias (:common-lisp :bar)))

# <PACKAGE "FOO">
* (in-package :foo)

# <PACKAGE "FOO">
* (bar:format t "Hello World~%")
Hello World
NIL

In python, this is a namespace alias. (Examples from Can you define aliases for imported modules in Python?)

import a_ridiculously_long_module_name as short_name

Though you can also do it with an assigment

import long_module_name
lmn = long_module_name

In C# this is a namespace alias.

From Java equivalent to C# using alias

namespace TheirNamespace
{
    public class ContestedClassName
    {
    }
}

namespace MyNamespace
{
    public class ContestedClassName
    {
    }
}

namespace MyBoundaryNamespace
{
    using MyRenamedClass = MyNamespace.ContestedClassName;
    using TheirRenamedClass = TheirNamespace.ContestedClassName;

    public class Translator
    {
        public TheirRenamedClass Translate(MyRenamedClass value)
        {
            return null;
        }
    }
}

In Java, one doesn't alias a namespace, but rather imports specific items into the current namespace, though it does serve the question asked (how to reduce the amount of typing):

The code

double r = cos(Math.PI * theta);

can be reduced with a static import to:

import static java.lang.Math.PI;
...
double r = cos(PI * theta);

One often sees this usage with Junit to avoid having to specify each static method.

import static org.junit.Assert.*;

When people speak of type aliasing in Java it is more along the lines of:

A problem I often encounter in Java is that I want to say “these two
  things are the same”, but Java won’t let me. Suppose I want to
  maintain an int[] array which is always sorted in my program.

which gets to more of the type aliasing rather than namespace aliasing, because these are different things.

Type aliasing in Scala appears to be something quite different based on Beginner: Scala type alias in Scala 2.10? and Scala type alias including companion object

More about what type aliasing in Scala is can be found at Effective Scala

In C++11 type aliases are a type of typedef which does more things other than namespace juggling.

using identifier = type_name;

An example of this would be:

// type alias, identical to
// typedef void (*func)(int, int);
using func = void (*) (int,int);
// the name 'func' now denotes a pointer to function:
void example(int, int) {}
func fn = example;

Though realize, there are some differences between these concepts as descried in  Difference between typedef and C++11 type alias

The playing of namespaces however, is a namespace alias as described in In C++, what is a "namespace alias"?

namespace ublas = boost::numeric::ublas;

ublas::vector<double> v;

More on this at msdn namespace Alias

namespace a_very_long_namespace_name { ... }
namespace AVLNN = a_very_long_namespace_name;
// AVLNN is now a namespace-alias for a_very_long_namespace_name.

http://hyperpolyglot.org/ml shows a few languages with various forms of namespace aliasing.

OCaml:

module Gr = Graphics;;

Haskell:

import qualified Data.Bytestring as B

Namespaces aren't unique to programming languages, but also extend to other structured data such as XSL  which has namespace aliases.  These tend to be rather terse transformations (converting 'alt' to 'xsl' or something like that - but they serve the same purpose.

So, as noted, these concepts go by different names in different languages and what is known as 'type aliasing' in one language may mean something completely different in another language.

There is no standard name


问:
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.

答:
You should use exceptions when something exceptional occurs.  That is, something that should not occur given proper use of the application.  If it is allowable and expected for the consumer of your method to search for something that will not be found, then "not found" is not an exceptional case.  In this case, you should return null or "None" or {}, or something indicating an empty return set.

If, on the other hand, your really do expect the consumers of your method to always (unless they screwed up somehow) find what is being searched for, then not finding it would be an exception and you should go with that.

The key is that exception handling can be expensive--exceptions are supposed to gather information about the state of your application when they occur, such as a stack trace, in order to help folks decipher why they occurred.  I don't think that's what you are trying to do.

Title: When and how should I use exceptions?


答:
At its core, a spreadsheet is a functional language with dynamic typing and each function or value being able to be referenced as a cell in the matrix.

Instead of things like (defn some-name ...) the some-name part is placed in a cell itself.

If you go to a dynamically updating functional language ide (such as lighttable for clojure), you will see much of the same functionality as a spreadsheet.  Bind a value to a name, write a function that uses that value, change the value and the output of the function changes immediately. This is the same as doing something like writing =A1 + B2 in the location of C3 in excel.

Thus, functional programmers often like to write spreadsheets as toy programs... and the subject of research papers too. (Yes, I'm sorry, they are all behind an ACM.org paywall)

Spreadsheet functional programming

The functional programming community has shown some interest in spreadsheets, but surprisingly no one seems to have considered making a standard spreadsheet, such as Excel, work with a standard functional programming language, such as Haskell. In this paper, we show one way that this can be done. Our hope is that by doing so, we might get spreadsheet programmers to give functional programming a try.

Forms/3: A first-order visual language to explore the boundaries of the spreadsheet paradigm

Although detractors of functional programming sometimes claim that functional programming is too difficult or counter-intuitive for most programmers to understand and use, evidence to the contrary can be found by looking at the popularity of spreadsheets. The spreadsheet paradigm, a first-order subset of the functional programming paradigm, has found wide acceptance among both programmers and end users. Still, there are many limitations with most spreadsheet systems. In this paper, we discuss language features that eliminate several of these limitations without deviating from the first-order, declarative evaluation model.

Implementing function spreadsheets

A large amount of end-user development is done with spreadsheets. The spreadsheet metaphor is attractive because it is visual and accommodates interactive experimentation, but as observed by Peyton Jones, Blackwell and Burnett, the spreadsheet metaphor does not admit even the most basic abstraction: that of turning an expression into a named function. Hence they proposed a way to define a function in terms of a worksheet with designated input and output cells; we shall call it a function sheet.

The start of Spreadsheet at Wikipedia gives some hints as to how to implement one:

A spreadsheet is an interactive computer application program for organization and analysis of data in tabular form. Spreadsheets developed as computerized simulations of paper accounting worksheets. The program operates on data represented as cells of an array, organized in rows and columns. Each cell of the array is a model–view–controller element that can contain either numeric or text data, or the results of formulas that automatically calculate and display a value based on the contents of other cells.

Building on this from Outline of Model-View-Controller paradigm as expressed in the Java libraries. The author goes on to mention applets (a bit dated, it was written in '93-'96) and mentions his web page which goes to http://csis.pace.edu/~bergin/Java/applets.htm (yes, applets) for the corresponding spreadsheet code http://csis.pace.edu/~bergin/Java/Spreadsheet.java

I will point out that the entirety of the spreadsheet, is not that big in this applet 570 lines including documentation.

That said, depending on the language, you could probably do it all with just function pointers in a sparse array.

Title: What are the data structures behind a spreadsheet?

Body:
I would like to understand how a spreadsheet (a group of named or otherwise identified cells containing values or formulas referencing other cells) is solved. I have tried looking at existing projects, but there was so much going on with the GUI, serialization, events, etc. that I couldn't find the spreadsheet.

At its simplest how does it work?


问:
Good example of complex code using TDD
What would be a good example of the use of TDD in large, real-life, complex, projects?  All the examples I've seen so far are toy projects for the purpose of a book or a paper...

Can you name an open-source project that heavily uses TDD? Preferably in C++ but I can read Java and C# or other similar languages.

答:
SQLite. All their code is very, very heavily tested:

As of version 3.7.14, the SQLite library consists of approximately
  81.3 KSLOC of C code. (KSLOC means thousands of "Source Lines Of Code" or, in other words, lines of code excluding blank lines and comments.)
  By comparison, the project has 1124 times as much test code and test
  scripts - 91421.1 KSLOC.

Title: Good example of complex code using TDD


问:
When defining directory path, should a trailing slash be included?
Say I'm defining a directory and then including files from it. Is it better practice to do:

```<code>define('PATH', 'C:/xampp/htdocs/includes/');
require PATH.'header.php;
</code>```

or:

```<code>define('PATH', 'C:/xampp/htdocs/includes');
require PATH.'/header.php;
</code>```

答:
To avoid ambiguity, you should always add the trailing slash.

Not all files have extensions, so if you use this consistently in your codebase, you (and others) will be able to tell whether a path references a directory or a file at a glance.


问:
C# LinqExtensions implement multiple inheritance
According to WikiPedia

"Some languages do not support mixins on the language level, but can easily mimic them by copying methods from one object to another at runtime, thereby "borrowing" the mixin's methods. Note that this is also possible with statically typed languages, but it requires constructing a new object with the extended set of methods."

1)  LinqExtensions static library functions ( .Where() ) applied to collections of regular objects (int[]) that implement IEnumerable do essentially this.  They use a new object (LinqExtensions) to add the extended set of methods ( Where(),etc ).

Conclusion. LinqExtensions are mixins with all classes that support IEnumerable.

2)  According to WikiPedia

"In object-oriented programming languages, a mixin is a class which contains a combination of methods from other classes. How such combination is done depends on language, but it is not by inheritance. If a combination contains all methods of combined classes it is equivalent to multiple inheritance."

By mixing ALL methods of classes that support IEnumerable ( List.HashCode, List.ToString, other List hierarchy baseline capabilities ), with ALL methods from the LinqExtensions static library ( .Where(), Max(), etc ) an equivalent to multiple inheritance is produced.

An equivalent to multiple inheritance is produced, yes or no?

答:
No.

The methods are not added to IEnumerable but are only available if the LinqExtensions type is within scope. This means that in some parts of the code .Where and its kin are available, and some parts they're not.

For Scala style mix-ins the methods are part of the mixed type and as such are available regardless of scope and can participate in subtyping checks.

Further, a requisite behavior for something to be called multiple inheritance involves actual inheritance. If you have two extension methods - one for IEnumerable and one for List no actual runtime dispatch occurs. If you have a List, what extension method is invoked depends wholly on the compile-time type of the variable.

Beyond that, extension methods cannot extend the state of the object they extend (without inglorious hacks). When people talk about inheritance, they generally assume that you can add variables to a baseclass during inheritance.

So no - extension methods are not in any meaningful way an equivalence to multiple inheritance.


问:
Make a big deal out of == true?
There is a colleague of mine who constantly writes:

```<code>if (someBool == true)
</code>```

It drives me up the wall!  Should I make a big deal of it or just drop it?

答:
The young know the rules, but the old know the exceptions ;)

In latest C#, if you are dealing with a null-able bool, then you have to:

```<code>bool? x = null;
bool? y = true;
bool? z = false;
if (x == true || y == true || z == true) {
    // That was the only way that is reasonably readable that I know of
    // to accomplish this expression.
}
</code>```

If tristate is not a problem, then there usually should not be a reason to compare something to true/True. However, in Python and several other languages such as C/C++ you can perform an if on a non-bool expression. These languages have unique rules for interpreting integers, pointers, lists, etc. as either true or false. Sometime you do not want that. For example, in this Python snippet:

```<code>x = True
y = 'abcdef'
z1 = x and y
z2 = (x == True) and (y == True)
</code>```

Here z should be True, but z2 should be False. Now, a Clojure language approaches this in yet another way - there and function does not necessarily evaluate to a bool, but the if can handle that.

Regardless of the language, any time you find yourself comparing something to True or False, it is probably worth commenting.

Title: Make a big deal out of == true?

Body:
The young know the rules, but the old know the exceptions ;)

In latest C#, if you are dealing with a null-able bool, then you have to:

bool? x = null;
bool? y = true;
bool? z = false;
if (x == true || y == true || z == true) {
    // That was the only way that is reasonably readable that I know of
    // to accomplish this expression.
}

If tristate is not a problem, then there usually should not be a reason to compare something to true/True. However, in Python and several other languages such as C/C++ you can perform an if on a non-bool expression. These languages have unique rules for interpreting integers, pointers, lists, etc. as either true or false. Sometime you do not want that. For example, in this Python snippet:

x = True
y = 'abcdef'
z1 = x and y
z2 = (x == True) and (y == True)

Here z should be True, but z2 should be False. Now, a Clojure language approaches this in yet another way - there and function does not necessarily evaluate to a bool, but the if can handle that.

Regardless of the language, any time you find yourself comparing something to True or False, it is probably worth commenting.


问:
Designing a database with circular references for the-one-of-many case
Consider the following case: there are two models Image and User. Users have associated images and they can pick one of them as their profile image. There are essentially two ways of modeling this:

1)

```<code>User:
   id - primary key
   profile_image - nullable foreign key to Image

Image:
   id - primary key
   user - foreign key to User
</code>```

2)

```<code>User:
   id - primary key

Image:
   id - primary key
   user - foreign key to User
   profile - boolean true/false
</code>```

Both of these approaches have some problems.

In the first case:

well-known chicken-egg problem (e.g. foreign keys must be off when recovering from backup)

It can happen that profile image points outside of domain of images associated with user

There is a redundant dependency link (i.e. one more relation when compared to the first solution). That will have some impact on an application code

What if we later decide to have an ordering on images where the first one is the profile one?

The second case:

There is slight data redundancy (many times false)

true can occur more than once

slightly less intuitive (at least for me)

So my question is, which of these two solutions is better/cleaner?

答:
For a simple project I would probably adopt the second solution. On the other hand, first solution may be slightly modified to avoid your mentioned drawbacks. You could model a profile image as a special case of an image, i.e. inheritance in OOP or is-a hierarchy in relational DB.

Therefore, leaving out the profile_image column and introducing table

```<code>Profile image:
   image_id - foreign key to Image
   user_id - foreign key to User
</code>```

with unique constraint on user_id and possibly dedicated primary key column + indexes on columns used for the desired use case.

Only problem may be the sorting, where you'd need keep some weights (a column in Image table) in consistence with Profile image table.

Body:
For a simple project I would probably adopt the second solution. On the other hand, first solution may be slightly modified to avoid your mentioned drawbacks. You could model a profile image as a special case of an image, i.e. inheritance in OOP or is-a hierarchy in relational DB.

Therefore, leaving out the profile_image column and introducing table

Profile image:
   image_id - foreign key to Image
   user_id - foreign key to User

with unique constraint on user_id and possibly dedicated primary key column + indexes on columns used for the desired use case.

Only problem may be the sorting, where you'd need keep some weights (a column in Image table) in consistence with Profile image table.


问:
How to estimate cost with very little information?
I have a client who wants a web app that will let him do the following (as he told me word for word):

User registration

Recurring payments for users

Online conference room reservation

I am supposed to give him a cost estimate very fast and I don't have any time to do any deeper requirements analysis! How would you deal with that kind of situation? Should I just give a very broad estimate and work out the exact requirements once he has accepted the estimate? At which point do you usually gather requirements, after or before getting a contract?

答:
Here is what I usually do to limit problems:

Define the information yourself, by describing what you are going to do in details.

Bid on that, and only that.

Refer to that document in your official purchase order form you will ask your customer to sign.

As an altenative, I suggest you to sell your customer with iterations instead of fixed features, with the flexibility to stop or continue development at the end of each iteration.

If you don't know how to estimate your own document, try to do some collective estimation using planning poker. You can also split each functionnality into tasks and estimate each. Sum and multiplicate the result by two if you are pretty confident, or three if you are not sure.

If you not confortable with your estimations, it's a pretty good indication that you are not experienced enough to accept the job in a fixed price scheme.


答:
I think you are taking the Code Repetition principle too far.  Think of the point of avoiding Code Repetition.  The point is to reduce the amount of code that has to be checked when there is a change in the logic, and to increase comprehension by factoring out obviously similarly-intended blocks.

The downfalls of factoring out in order to avoid Repetition are that if one of the shared blocks has to change, now you need even more complex inheritance or some switching between standard and non-standard implementation.

So carefully weigh the possibility of the logic for even one of these blocks changing without the others against the comprehension benefits gained by factoring this commonality out.  If one implementation could split from the others you may very well be better off simply repeating the code.

While maintaining this repeated code, as it becomes more complex and your problem domain becomes more defined, you may then find it more appropriate to factor the repeated, now more complex, but also more defined sections out.

I usually try to maintain text-editor same-ness for a while until I can see whether something that looks to be repetitive turns out to be worth factoring.  I just keep the repetition, but I keep my eye toward the future of that block by keeping it textually easy to match up later.

A lot of the time, the same-ness, and the possible factoring, starts to dissipate, as real, capricious, business rules and highly dependent, often arbitrary logic; like dealing with the oddities of several common database implementations (ANSI_NULLS or some such comes to mind) are added; forcing what seemed like a pure logic into a twisted mess, trying to provide reasonable, defensible decision logic when confronted with the mess of the state of the industry.

It seems to me that if people tried to factor out what you are trying to factor, we would have an entire library of worthless constructs like
Do1Then2If2False Do1IfTrueDo2.

It has to more complex and more clear that the block is not going to change to warrant factoring it out.

It's software.  You can go back and edit a couple blocks that are the same right now.  It'll take 5 minutes.  And you may save hours of wasted factoring, and then hours more of wasted inheritance and switching development, by just leaving it, and making sure you have a good , anti-RSI keyboard.


问:
Where does the tradition of shell prompts in code snippets come from?
Most code samples I see that demonstrate shell code preface each command with $. Having a prefix makes sense, but I'm confused as to why $ is used in particular. Some other symbol, like !, that can be copied and pasted into a prompt without affecting the command's execution makes far more sense to me. So where does this notation come from?

答: $ is the default prompt prefix for a non-escalated bourn or sh shell on most *nix systems.  It signifies that the code exemplified should be executed using one of those associated shells.  zsh and csh have % as a prefix.  The fish shell uses >.  Putting the prefix is simply a quick way to let the reader know what shell the command is destined for.


问:
"state" or "status"? When should a variable name contain the word "state", and when should a variable name instead contain the word "status"?
Reading code and discussions pertaining to code, I often see the words "state" and "status" used interchangeably, but the following tendencies seem to exist:

When a variable holds a value intended to indicate that something is in a certain state, the name of that variable more often than not contains the word "state", or an abbreviation thereof.

However, when the return value of a function serves to indicate some such state, we tend to call that value a "status code"; and when that value is stored in a variable, this variable is commonly named "status" or something similar.

In isolation that's all fine I guess, but when the aforementioned variables are actually one and the same, a choice needs to be made involving the perverted intricacies of English language (or human language in general).

What is the prevailing coding-standard or convention when it comes to disambiguating between the two? Or should one of those two always be avoided?

This english.stackexchange question is also relevant, I suppose.

答:
From what I've seen "state" is often used for things that can change and the programmer has at least some modicum of control over how/when it changes (even if indirectly). It also almost always is used to refer to positive states. "You have placed the connection into a disconnected state."

"Status" tends to be the opposite. It tends to be used for things that happen without the programmer's input - and often that the programmer cannot change. It also tends to be used for for negative statuses. "The status of your connection is (checking...) disconnected."


答: You can't.  Tell the customer it is similar to building a bridge or a house, and require the same amount of preparation to give an accurate estimate.</p>

Title: How to estimate cost with very little information?

Body:
I have a client who wants a web app that will let him do the following (as he told me word for word):

User registration

Recurring payments for users

Online conference room reservation

I am supposed to give him a cost estimate very fast and I don't have any time to do any deeper requirements analysis! How would you deal with that kind of situation? Should I just give a very broad estimate and work out the exact requirements once he has accepted the estimate? At which point do you usually gather requirements, after or before getting a contract?


答:
"State" makes me think of "state machine", and I typically use it to refer to something internal / technical, like, "open", "parsing header", "negotiating formats", "reading text", "reading video", etc.  Something a fellow programmer might care about, but not intended (much) for the end user.  Maybe if they ask for more details on an error, but not the first thing they see.

"Status" is less techie and more for an end user, e.g. "reading", "error 404", "success 200".

All IMHO.

Title: "state" or "status"? When should a variable name contain the word "state", and when should a variable name instead contain the word "status"?

Body:
Reading code and discussions pertaining to code, I often see the words "state" and "status" used interchangeably, but the following tendencies seem to exist:

When a variable holds a value intended to indicate that something is in a certain state, the name of that variable more often than not contains the word "state", or an abbreviation thereof.

However, when the return value of a function serves to indicate some such state, we tend to call that value a "status code"; and when that value is stored in a variable, this variable is commonly named "status" or something similar.

In isolation that's all fine I guess, but when the aforementioned variables are actually one and the same, a choice needs to be made involving the perverted intricacies of English language (or human language in general).

What is the prevailing coding-standard or convention when it comes to disambiguating between the two? Or should one of those two always be avoided?

This english.stackexchange question is also relevant, I suppose.


问:
How to test the data access layer?
I have a DAO method that utilizes Spring for JDBC access. It calculates a seller's success rate of selling an item.

Here is the code:

```<code>public BigDecimal getSellingSuccessRate(long seller_id) {
    String sql = "SELECT SUM(IF(sold_price IS NOT NULL, 1, 0))/SUM(1)
                  FROM transaction WHERE seller_id = ?";
    Object[] args = {seller_id};
    return getJdbcTemplate().queryForObject(sql, args, BigDecimal.class);
}
</code>```

How should I go about testing this method or any DAO method with JUnit? What are some best practices to test the data access logic? I am thinking of testing it against an embeddable database loaded with some data, but shouldn't we do integration tests similar to a production environment in terms of RDBMS and the schema?

答:
First, you should never do testing in a production environment.  You should have a test environment that mirrors your production environment and do integration tests there.

If you do that, then you can do a number of things.

Write unit tests that test to see if the appropriate SQL is being submitted to a mock item using a mocking framework such as Mockito.  This will ensure that your method is doing what it is supposed to do and takes integration out of the picture.

Write test SQL scripts demonstrating the appropriateness of the SQL you tested for in your unit tests.  This can help with any tuning issues you may come upon, as you can also run explains and such based on your test scripts.

Use DBUnit, as mentioned by @Sergio.

Title: How to test the data access layer?


答:
I like this question. The following is from my head but I think it fits quite well.

status is used to describe an outcome of an operation (e.g. success/fail).

state  is used to describe a stage in a process (e.g. pending/dispatched).

I also like this definition:

status is a final (resulting) state.

It is quite clear when applied to programming. Much less clear when you apply it to natural language. Let's take the examples from the english thread and see if it holds with the most upvoted answer.

"What is the current status of this project?" The answer should be "In testing."

Well, this might seem to contradict my definitions at a first look but we must realize the context. Probably some supervisor is asking his team about the project and how far they have reached. The point is that the supervisor is interested in the outcome up to now. The fact that there will be something after is just put away because it is not the point of the question.

"What is the current state of this project?" The answer should be "On hold for financial analysis."

So I think that this very nicely demonstrates an essence of a state. "On hold for financial analysis." clearly focuses on the fact that the current situation is a part of some encompassing process and even suggests the next state.

I would say it holds pretty well.