问:
When does one hard-code actual data values into the code as opposed to using a DB?
A long-standing question for me has been: when do I store data (actual values) in a database table, and when do I store them right in the code?

The untold consensus has typically been as such(*):

If it is a single variable or a simple structure, or an array of a few values, put data right in the code.

[* consensus has been debated in comments and answers, but basically I wanted some kind of a premise to jump-start the question, so feel free to challenge and improve upon it]

Example:

```<code>$number = 44;
$colors = array("blue", "yellow", ... "mauve");
</code>```

If it has hundreds+ of rows of data of the same type, use a database.

But there seems to be a gray area; what about cases that are not so clear? What considerations and factors does one need to pay attention to in order to make a decision?

Example:

Say your company uses 10-15 different types of motors frames that can be represented as "412T". You have about 30 of them and they change rarely.  You can either create a DB table for those or hard-code them in a database.  In this case, motors are static, physical things that are not likely to change often.

Keeping them in code subjects them to source control, where in a database, DB changes are typically not tracked.  But keeping them in a database frees up (separates) code from data.

Another (actual) example I can use is this question of mine: https://stackoverflow.com/questions/26169751/how-to-best-get-the-data-out-of-a-lookup-table (currently 48 rows of option data).

答:
What you are also missing is "program control" type information say max buffer size, number of items aloud in an order, max page size for a screen is always better either hard coded in the program or in a configuration file.

If you keep this sort of data in a database there is always the possibility of someone changing it on the fly and completely changing the behavior of a system.

The other problem is that there is no easy way to get database entries through the source control/change management/automatic build systems that you should be using.


问:
Sending multiple resources under REST endpoints
I am designing an API where-

```<code>1. There can be multiple devices under a gateway.
2. There are multiple sensors on every device.
</code>```

GET /devices/d1/sensors/s1 returns the status of sensor s1 on device d1.
Moving forward, I need to allow querying sensors across multiple devices.

Something like- GET /devices/d1,d2,d7,d30,d45,d500/sensors/s1,s5 would not scale as I'd be dealing with a lot of devices+sensors and increasing the URL length linearly would be bad design.

How can I approach this more elegantly?

答:
One of the core ideas behind REST is that each URL provides a representation for a single resource (although that resource can be a collection that gives information about other resources).

If you want to get information about multiple sensors, where you don't know/care which device each sensor is connected to, the canonical way is to provide a top-level sensors resource: GET /sensors. This would give you all sensors in the system. If you wan't to restrict the list in some way, you use query parameters:

```<code>GET /sensors?device=d1,d2,d7,d30,d45,d500&type=temperature
</code>```

would give you the temperature sensors connected to the listed devices.

If you do care which device each sensor is connected to, there is no way around performing multiple requests, one for each device.

ContentLicense: CC BY-SA 3.0

Body:
One of the core ideas behind REST is that each URL provides a representation for a single resource (although that resource can be a collection that gives information about other resources).

If you want to get information about multiple sensors, where you don't know/care which device each sensor is connected to, the canonical way is to provide a top-level sensors resource: GET /sensors. This would give you all sensors in the system. If you wan't to restrict the list in some way, you use query parameters:

GET /sensors?device=d1,d2,d7,d30,d45,d500&type=temperature

would give you the temperature sensors connected to the listed devices.

If you do care which device each sensor is connected to, there is no way around performing multiple requests, one for each device.


问:
BNF parsing rule for left associativity
Can someone please assist me with the following question.

Write a BNF rule to parse into

```<code>C -> E
C -> E && E
C -> E && E && E
</code>```

so that C generates as many E && E as needed and enforces left association.

Is the following correct?

```<code>C -> C && E | E
</code>```

It should force left association because of the left recursion and make as many && E's it wants to because of the recursion.

答:
Apart from some formatting issues (-> doesn't exist in formal BNF), your rule is correct.
Written in proper BNF syntax and using quotes around literals, it would be

```<code>C ::= C '&&' E | E
</code>```

The left-recursion indeed creates a parse tree for a left-associative operator.

Title: BNF parsing rule for left associativity

Body:
Apart from some formatting issues (-> doesn't exist in formal BNF), your rule is correct.
Written in proper BNF syntax and using quotes around literals, it would be

C ::= C '&&' E | E

The left-recursion indeed creates a parse tree for a left-associative operator.


问:
Where to perform datatype.ParseString (MVC)
Using the MVC pattern, asume a simple situation where you want to send a number (for example the number of pages in a book) with a controller to a setter.

Now, the set method looks like this

```<code>public void setPages(int pgs)
{
pages = pgs;
}
</code>```

and the controller, which retrieves the information from a textbox in view, recieves this as a String.

Where would we perform the conversion?

Would we have the controller do

```<code>int pgs = Integer.parseInt(String textFromView);
someClass.setPages(pgs);
</code>```

Or would it be better to have a setter which accepts string input from the controller, and does the conversion itself?

If we do this conversion in the setter, would that not imply business logic is getting into our controller?

答:
The conversion to int should take place in the Controller.

The fact that the user enters the number of pages into a control that was designed for general text input is a pure User Interface concern and that should not bleed through to the Model.

Similarly, if the value is received over a text-based communication channel (such as HTTP), the conversion should also take place in the Controller.

All the Model should care about is that it gets a number that it can use in subsequent calculations. The Model should not care about all the ways that the number could be communicated from the user to the Model. That is the responsibility of the View and Controller.


问:
Define fields only once
I'm looking for a method to describe fields in a structured way, so I am able to reuse it in various languages and levels of my application.

For instance, if I'm developing an Android application about food items, I might be dealing with fields like Name, Description, Price and Kcal. However, these fields will appear multiple times: In the viewholder of my Android application, in the C++ server which handles the messages, in my SQL database which stores them, etc. Imo, this violates the DRY principle, and if I also want to save the barcode of a food item for example, I need to add it to all these places.

I've been thinking about using XML or TDL, but I'm not sure if those languages are intended for this goal. Preferably, I would have a file like this:

```<code>Fieldname   Type        Lower bound Upper bound May be NULL
-----------------------------------------------------------
Name        string      3           100         No
Price       float       0           *           Yes
...
</code>```

Of course I could create such a thing myself, but would that be a good way to go? Or is there something out there which is used for this purpose (I want to avoid beginners mistakes). Preferably, I would have these definitions been read out at compile-time because the definition won't be altered at runtime anyway.

答:
There are already frameworks like this, for example the ORM ones. This will ensure that you don't have to define the SQL structure too. I'm more familiar with the Java ones, like DataNucleus or Hibernate.

Based on the same code annotations, you can generate the domain model for the Android application.

But, in my experience, maintaining such a framework, will soon become very expensive, as most probably you will need a lot of exceptions, like different constraints (URL, all lowercase, list etc).

If you would use Java on the server side, you can actually use the same classes for the domain model on both client and server. But, there could also be the case that you want a thinner model on the client side (the Android app) than on the server side (Java or C++ server).

Title: Define fields only once


问:
Is using os.environ to store the value of command line switches pythonic?
I write CLI-executable Python 3 scripts regularly to do data compilation and some maintenance tasks, and try to adhere to PEP 8 and the Google Python Style Guide when doing so. Google's guide says to avoid using global variables, while PEP 8 offers naming conventions but doesn't really encourage or discourage use of them, so I don't use them.

However, I've lately found myself using a "verbose" option/switch a lot along with a "printv" function to use while debugging. It usually looks like this:

```<code>def printv(opts, msg, **kwargs):
    if opts.verbose: print(msg, **kwargs)
</code>```

As incredibly lazy as I am, I'd like to make it so I don't need to pass the opts argument (which is an OptionParser object) to printv. The simplest method would be to use a global variable, sure. Another thought I had would be to set a "VERBOSE" variable in os.environ, since the switch is, conceptually, making a change to the execution environment. Obviously it's counter-intuitive, but is it pythonic?

答:
Storing program state in the environment is not Pythonic.

Looking at the GPSG section on Global Variables it says explicitly that one of the exceptions includes default options for scripts;  I would say if your CLI is a single file script, then having your opts object be global is just fine.


问:
Is there a way to prevent variables from changing their type in Python?
It is useful to have the interpreter derive the type of a variable automatically. This on its own is similar to the auto keyword in C++11. However, in Python variables can change their type after being declared for the first time. This potentially can cause a lot of errors. I haven't seen any reasonable use case for this, besides changing from or to None.

For performance reasons, PyPy claims to be written in what they call RPython, which goes into this direction. However, it seems like there is neither a standard for this nor a way to make the interpreter complain about type changing.

Is there a way to prevent variables from changing their type in Python?

答:
A Python variable is not like a C variable, which is to say it is not a box with data inside it.  A Python variable is more like a sticky note that has been stuck on a box with data inside it.

The type of the box's data rarely changes, but the sticky note can be passed from box to box to box.

So, the type isn't really changing.

Having said that, there are ways to limit this:  Use a class with custom descriptors to check and enforce what new value is trying to be assigned to your sticky-note variable name, and use a custom metaclass to prevent the class variable sticky note from being reassigned to something else.

I beleive Enthought Traits have this ability.


问:
What should config files and the bootstrap do?
I already read dozens of articles and questions/answers on SO and Programmers but I can't understand what config and bootstrap files are, in the context of a web application.

So my questions are :

What information should I put in config files?

What should my bootstrap process do?

How should I call in to my applications code?

答:
The config file should contain those settings that might need to change between deployments. Typically, this will be stuff like database locations and credentials, mail server address, etc.

If it is information that depends on the environment where the application runs, then the software should read those values from a config file.

The bootstrap file sits between the webserver (which wants to just invoke a single script) and the many files of your application.

The task of the bootstrap file is to bring the application/framework in a state where it can start handling the requests. This typically means setting up paths/autoloaders so that all relevant files can be located and installing routes so that the controllers can be matched to the URIs they handle and that the parameters can be extracted from the URIs.

Once the setup is done, the bootstrap file will typically call the Router class/function to interpret the received URI and invoke the corresponding controller. In most frameworks, the controller is the first part of your application (as in non-framework code) that gets called.


问:
Is it appropriate to ask for reasons after rejected after the interview?
I thought I did okay in the interviews but apparently the interviewers didn't think so. Is it appropriate to ask for a reason after I have received the rejection email? After all I don't want to annoy the HR person.

I am a student, so not so much job hunting experience so far. Bear with me if this question sounds stupid.

答:
Don't underestimate the Thank You letter, both after having your interview, and yes, even after a rejection.

The "thank you" after being rejected may seem counter-intuitive.  However, you can frame it as to ask your "what can I do to become a better candidate in the future?" questions.  This will show your interest in improving yourself, and that you may be a better candidate in the future with a little guidance.

You may or may not get a response.  However, a little extra politeness like this may help you stick in the hiring managers mind, and give you a slight edge later on.  It's a small world, and you may run into the same person again, even at another company.  It may even help if the candidate they did make an offer to rejects the offer or otherwise doesn't work out.

ContentLicense: CC BY-SA 2.5


答:
One thing you should never keep in the database are the details needed to access the database.

You've a bit of a catch-22 if you need to access the database to retrieve the connect strings, username, and password for that same database after all.

Hardcode it? hmm, might work if you're using some sort of database that installs and ships with the application.

Configuration file? More promising but what about account security?

Of course you could store the database information in that config file in encrypted form, but then you'd need to have the decryption keys stored somewhere, and that'd be hardcoded almost certainly.

Apart from that, there are things that never change. Things like the natural constants (G, pi, e, you name it), things maybe like certain regular expressions, like email validation.

Title: When does one hard-code actual data values into the code as opposed to using a DB?

Body:
A long-standing question for me has been: when do I store data (actual values) in a database table, and when do I store them right in the code?

The untold consensus has typically been as such(*):

If it is a single variable or a simple structure, or an array of a few values, put data right in the code.

[* consensus has been debated in comments and answers, but basically I wanted some kind of a premise to jump-start the question, so feel free to challenge and improve upon it]

Example:

```<code>$number = 44;
$colors = array("blue", "yellow", ... "mauve");
</code>```

If it has hundreds+ of rows of data of the same type, use a database.

But there seems to be a gray area; what about cases that are not so clear? What considerations and factors does one need to pay attention to in order to make a decision?

Example:

Say your company uses 10-15 different types of motors frames that can be represented as "412T". You have about 30 of them and they change rarely.  You can either create a DB table for those or hard-code them in a database.  In this case, motors are static, physical things that are not likely to change often.

Keeping them in code subjects them to source control, where in a database, DB changes are typically not tracked.  But keeping them in a database frees up (separates) code from data.

Another (actual) example I can use is this question of mine: https://stackoverflow.com/questions/26169751/how-to-best-get-the-data-out-of-a-lookup-table (currently 48 rows of option data).


问:
Is this a pattern: stand-alone classes
Having recently discovered python, I attempted to write a simple logger. Data is read from a device, processes, displayed and stored on disc. Those different tasks belong to different modules, of course.

What appeared to be cool at the time, was to provide command-line interface to each module, as explained here: https://docs.python.org/2/tutorial/modules.html#executing-modules-as-scripts

The result is tat although the program as a whole uses import x and the uses the classes in the modules, the modules can be used form the command line as well. For example, invoking hw_comm.py would open the default device with default options and stream to stdout. Also plot.py expects data form stdin and draws a plot.

I can see a ton of advantages to this design, such as

easy to debug

easy to adapt for different use cases

easy to test

provides immediate value to the end user, long before the project is finished.

I have read only a few thousand lines of python yet, but haven't seen this approach (modules as both importable classes and stand-alone scripts) elsewhere. Why would be that? Is the extra work to support this format too much for an enterprise project? Or maybe, unlike my tiny project, business scale projects can not easily support this behavior, with hundreds of modules doing different things just to accomplish one complex goal together?

答: The reason you don't see this more often is that having a file be both a module and a script doesn't work well except in simple cases.  The primary reason is that as a system get more complex you end up with more modules, and at some point the __main__ script will get imported, and at that point you then have two copies of that module in memory -- once as sys.modules['__main__'] and once as sys.modules[actual_name].  At that point weird errors start happening and if you don't know what's going on you can lose hours figuring it out.

Title: Is this a pattern: stand-alone classes


问:
Should you reuse an Entity Framework EDMX between multiple solutions?
We currently have 1 giant EDMX for our corporate database. It, along with all of the generated POCOs, are in a separate project (we'll call it the EDMX project) which we pull in to any solution that uses the main database. In other words, any new application we develop uses this same EDMX project. Naturally, the EDMX project requires a reference to Entity Framework. But so do the main projects for each application. Thus, a given solution has 2 separate Entity Framework references - which could end up being completely different versions.

I inherited this setup and now have the opportunity to make some big changes. I have a suspicion we shouldn't be using this one EDMX for multiple solutions, but am not 100% sure.

Questions

Could having 2 different versions of Entity Framework in a given solution cause issues? It seems like it would, and we certainly do not want to constrain our newer applications to an old version of EF to work with the EDMX project which in turn works with older solutions.

Are there any other reasons this would be bad?

Note: I have read similar questions about using 1 EDMX within the same solution (vs. splitting it up by schema, etc.), but my question is different because I am talking about using 1 EDMX for all solutions.

EDIT 10/16/14: So I pretty much have my first question answered. At least between Entity Framework 5 and Entity Framework 6, it does indeed cause issues. When my EDMX project has EF5 installed, and I upgrade my main project to EF6, many of my LINQ queries (inside the main project, referencing the generated-POCO classes inside the EDMX project) break. As I understand it, this has something to do with namespace changes. If there is a workaround to make the two versions work together, I haven't found it.

My 2nd question still needs answered, however. Are there any other reasons it'd be bad to do, besides conflicting versions of Entity Framework? From a design perspective, does having 1 EDMX make sense?
Pros could be ease of updating (if a database table used by multiple projects changes, there is 1 place to update it). The obvious con is new projects being constrained to an old EF version until all other projects got updated. Any other issues that would crop up? Really just looking for some direction.

EDIT 10/17/14 I've accepted an answer but comments about your/your company's usage of the EDMX would still be helpful/upvoted. The more perspective the better.

答:
It depends.

The main thing I would focus on is "don't repeat yourself". If you have a bunch of applications using the same entities, it doesn't make sense to spend a bunch of time and effort making and then maintaining the same thing over and over again. Worse, it can become a headache to keep all of them correct and in sync.

On the other hand, if you really have a bunch of different schemas that just happen to live in the same database (and don't interact), then it can make sense to have multiple independent EDMX files.

I have seen both ways, and they worked well enough in their environments. But given the Entity Framework's difficulties in playing nice with others, I would err towards putting all of a database into a single project, as it's less work to "just use part of it" than "make it work with that other stuff too" should my guess be wrong about future usage.


答:
What you present in your question is a context-free (CF) grammar,
omitting details about terminal (which symbols are in the generated
text) and non-terminals (which symbols are used only to be rewritten
(expanded), and the initial symbol (which non-terminal you start
with).

BNF (Backus-Naur Form) is a specific syntax (syntactic style) for
presenting CF grammars, so that this missing information is visible
just by looking at the rules.

So, written in BNF your grammar would look like this:

```<code><C> ::= <C> "&&" <E> | <E>
</code>```

The <> are for non-terminals and the "" are for terminals.

But actually it is only a grammar fragment. This is also clearly true of the
first given definition, though it is not explicit.

The reason is that E is clearly intended to be a non-terminal that can
derive further in other expression, such as (I am guessing an example)
x == y.  But the rules for that are missing.

Other than that syntax issue, you are quite correct with your answer, as Bart van Ingen Schenau already told you.

It is very possible that your instructor does not distinguish BNF and
CF grammar.  Many people do not. The name CF grammar is more used by
theoreticians, while BNF is a common, 50 years old, notation used by
many practitioners for computer input ... and much less for casual
work because it is longer to write.

Title: BNF parsing rule for left associativity

Body:
Can someone please assist me with the following question.

Write a BNF rule to parse into

```<code>C -> E
C -> E && E
C -> E && E && E
</code>```

so that C generates as many E && E as needed and enforces left association.

Is the following correct?

```<code>C -> C && E | E
</code>```

It should force left association because of the left recursion and make as many && E's it wants to because of the recursion.

Body:
What you present in your question is a context-free (CF) grammar,
omitting details about terminal (which symbols are in the generated
text) and non-terminals (which symbols are used only to be rewritten
(expanded), and the initial symbol (which non-terminal you start
with).

BNF (Backus-Naur Form) is a specific syntax (syntactic style) for
presenting CF grammars, so that this missing information is visible
just by looking at the rules.

So, written in BNF your grammar would look like this:

<C> ::= <C> "&&" <E> | <E>

The <> are for non-terminals and the "" are for terminals.

But actually it is only a grammar fragment. This is also clearly true of the
first given definition, though it is not explicit.

The reason is that E is clearly intended to be a non-terminal that can
derive further in other expression, such as (I am guessing an example)
x == y.  But the rules for that are missing.

Other than that syntax issue, you are quite correct with your answer, as Bart van Ingen Schenau already told you.

It is very possible that your instructor does not distinguish BNF and
CF grammar.  Many people do not. The name CF grammar is more used by
theoreticians, while BNF is a common, 50 years old, notation used by
many practitioners for computer input ... and much less for casual
work because it is longer to write.


问:
In ASP.NET MVC, should the view models have an ID?
When developing an ASP.NET MVC application that allows the model to be updated, you need some way to know how to take the updated view model and match it back to the model that is now updated.  There seems to be a few different ways of doing this and I'm wondering if any of these are not proper MVC (much like having your controller store data that should be in the model is not proper MVC)?

All View Models have an ID:
Pros

Always ensure you can match to your model.

Cons

You have to be real careful that none of the IDs were changed else you can have users updating rows they shouldn't have access to.

Only the bare minimum view models have an ID:
Pros

Far less checking needed to avoid users updating data they shouldn't access.

Cons

Far more difficult to track what view models matches what model.

You still have to check the few view models with IDs to make sure the user isn't updating data they shouldn't have access to.

No view models have ID:

Pros

No need to check IDs for updates.

Cons

You have to abandon statelessness.

So I have two questions.

First, is there a correct/incorrect choice?  (If not, that means the choice is a matter of opinion and my second question opinion based and should be ignored.)

Second, if there is a correct/incorrect choice, which is it?

To clarify on a comment, I'm talking when you have a view model that is a mimic of your database object.

Think this:

```<code>public class InvoiceViewModel  //Does not have ID, does not relate to model.
{
    public CustomerViewModel CustomerVM { get; set; }  //Maybe has ID?  Does relate to model.
    public AddressViewModel BillingAddressVM { get; set; } //Ditto
    public AddressViewModel ShippingAddressVM { get; set; } //Ditto
    public List<InvoiceLineItemViewModel> ItemVMs { get; set; }  //Each one has an ID?
}
</code>```

not this:

```<code>public class InvoiceViewModel
{
    public Customer Customer { get; set; }
    public Address BillingAddress { get; set; }
    public Address ShippingAddress { get; set; }
    public List<InvoiceLineItem> Items { get; set; }
}
</code>```

答:
The ViewModel object is not what gets stored in a database table, generally.  It's the individual items in the ViewModel object that get stored.  Each of those items already has an ID.

For example:

```<code>public class InvoiceViewModel
{
    public Customer Customer { get; set; }
    public Address BillingAddress { get; set; }
    public Address ShippingAddress { get; set; }
    public List<InvoiceLineItem> Items { get; set; }
}
</code>```

Since there's no single table in the database that corresponds to an InvoiceViewModel, there is no ID for an InvoiceViewModel object.

Of course, you can always use the InvoiceID as the id for this particular ViewModel.  InvoiceID is handy, because that's what this object ultimately represents.  But I could see having a ViewModel object that doesn't correspond to any particular ID in the database.

Body:
The ViewModel object is not what gets stored in a database table, generally.  It's the individual items in the ViewModel object that get stored.  Each of those items already has an ID.

For example:

public class InvoiceViewModel
{
    public Customer Customer { get; set; }
    public Address BillingAddress { get; set; }
    public Address ShippingAddress { get; set; }
    public List<InvoiceLineItem> Items { get; set; }
}

Since there's no single table in the database that corresponds to an InvoiceViewModel, there is no ID for an InvoiceViewModel object.

Of course, you can always use the InvoiceID as the id for this particular ViewModel.  InvoiceID is handy, because that's what this object ultimately represents.  But I could see having a ViewModel object that doesn't correspond to any particular ID in the database.


问:
In TDD should I have to write Test first or Interface first?
I am learning TDD using c#, as far as I know test should drive the development, that is first write a failing test after write the bare minimum code to pass the test then do refactoring.

But it is also said that "Program to Interface, not Implementation", so write an interface first. This is where my confusion starts, If I am writing Interface first then it is violating two things

The code that is written for interface is not driven by test.

It is not the bare minimum obviously i can write it with a simple class.

Should I start by writing tests for interface also ? without any implementation what am I going to test ?

If this question sounds silly sorry for that, but I am utterly confused. May be I am taking things too literally.

答:
Your first violation ("The code that is written for interface is not driven by test.") is not valid. Let's use a trivial example. Suppose you're writing a calculator class, and you're writing an addition operation. What test might you write?

```<code>public class CalculatorTest {
    @Test
    public void testAddTwoIntegers() {
        Calculator calc = new Calculator();
        int result = calc.add(2, 2)
        Assert.assertEquals(4, result);
    }
}
</code>```

Your test has just defined the interface. It is the add method, see? add takes two arguments and returns their sum. You might later determine that you need multiple Calculators, and extract an (in this case) Java interface at that time. Your tests shouldn't change then, since you tested the public interface of that class.

At a more theoretical level, tests are the executable specification for a system. Interfaces to a system should be driven by the users of that system, and tests are the first method you have to define interactions.

I don't think you can separate interface design from test design. Defining interactions and designing tests for them are the same mental operation - when I send this information into an interface, I expect a certain result. When something is wrong with my input, I expect this error. You can do this design work on paper and then write your tests from that, or you can do them at the same time - it doesn't really matter.

Body:
Your first violation ("The code that is written for interface is not driven by test.") is not valid. Let's use a trivial example. Suppose you're writing a calculator class, and you're writing an addition operation. What test might you write?

public class CalculatorTest {
    @Test
    public void testAddTwoIntegers() {
        Calculator calc = new Calculator();
        int result = calc.add(2, 2)
        Assert.assertEquals(4, result);
    }
}

Your test has just defined the interface. It is the add method, see? add takes two arguments and returns their sum. You might later determine that you need multiple Calculators, and extract an (in this case) Java interface at that time. Your tests shouldn't change then, since you tested the public interface of that class.

At a more theoretical level, tests are the executable specification for a system. Interfaces to a system should be driven by the users of that system, and tests are the first method you have to define interactions.

I don't think you can separate interface design from test design. Defining interactions and designing tests for them are the same mental operation - when I send this information into an interface, I expect a certain result. When something is wrong with my input, I expect this error. You can do this design work on paper and then write your tests from that, or you can do them at the same time - it doesn't really matter.


答:
In TDD should I have to write Test first or Interface first?

It all depends on how orthodox / religious you want to do TDD.

I am learning TDD

Since you are learning, you should experiment to get a personal workflow, which works for you.

If you want to do it according to the books, you write at first a test, which obviously will fail, because you are starting with no code at all. Then you write some code to make the test pass. If that is done, you are free to refactor the existing code, since you have a test which provides some kind of safety-net for refactorings. Deciding to use an Interface is some kind of refactoring.

Besides TDD or not: The question, whether to use an interface or not isn't interesting in the first place. Of course if you are sure, you have different behaviour you want to spread across several objects, it makes sense to think about using an Interface: For example, if you have some kind of output to different destinations, it makes sense to implement it via an interface Writer and have different classes for the output (FileWriter, Printer etc.). Although it is a common saying to write to an interface, but that doesn't mean: use an interface for everything. Sometimes it is one level of indirection to much. Btw. the same goes for services. But that's a different topic.

On the other hand, you could develop test driven in another way: design your code for testability. Which means, you write code, which is easy to test - although you write the tests afterwards. It doesn't matter if you write tests beforehand or afterwards, as long as you test anyways.

Body:
I am learning TDD using c#, as far as I know test should drive the development, that is first write a failing test after write the bare minimum code to pass the test then do refactoring.

But it is also said that "Program to Interface, not Implementation", so write an interface first. This is where my confusion starts, If I am writing Interface first then it is violating two things

The code that is written for interface is not driven by test.

It is not the bare minimum obviously i can write it with a simple class.

Should I start by writing tests for interface also ? without any implementation what am I going to test ?

If this question sounds silly sorry for that, but I am utterly confused. May be I am taking things too literally.


问:
Name for this type of parser, OR why it doesn't exist
Conventional parsers consume their entire input and produce a single parse tree.  I'm looking for one that consumes a continuous stream and produces a parse forest [edit: see discussion in comments regarding why this use of that term may be unconventional].  My gut says that I can't be the first person to need (or think I need) such a parser, but I've searched off and on for months to no avail.

I recognize that I may be ensnared by the XY problem.  My ultimate purpose is to parse a stream of text, ignoring most of it, and produce a stream of parse trees from the sections that are recognized.

So my question is conditional: if a class of parsers with these characteristics exists, what is it called?  And if not, why not?  What is the alternative?  Perhaps I'm missing some way I can make conventional parsers do what I want.

答:
What you are describing can be described as SAX vs. SOM.

SAX - (Simple API for XML) is an event sequential access parser API developed by the XML-DEV mailing list for XML documents.

SOM - (XML Schema Object Model) random access to in memory representation of an XML file

There are implementations of both types in C#, and Java, and probably many more. Usually an XSD or DTD is optional.

The joy of SAX is that it is low memory overhead, which is great for large XML files. The trade off is that random access using SAX is either non-existent or slow, and worse the development time is usually considerable more than with SOM. The obvious problem with SOM is potentially large RAM requirements.

This answer is not applicable for all platforms and all languages.


问:
How to make Doxygen documentation that helps in understanding the code?
So a few years ago I came across a statement that most of the Doxygen generated documentation out there is quite bad.  "Bad" in the sense that defies the purpose of documentation and doesn't help in understanding the code. To an extent,  I think this also applies to other automatic documentation generators.

The majority of Doxygen-ated stuff I have seen was okay; you could work with it. Of course there's always the really bad apple that leaves scars in your memory.

So far, I've not come across some documentation which made me go: "Oh, wow, this is written really well, I love it."

My question(s):

What should a developer do in order to avoid auto-generating bad documentation that doesn't help future developers?

And are there additional things that could be done that would make the auto-generated documentation good so it actually helps future developers?

答:
Generated documentation's audience is developers who are trying to use the code. Meaning the code is a reusable library or framework.

If code is named and structured properly, documentation is not as important. I have found that the most important documentation is at the class or module (namespace, package, etc) level. The least important documentation is at the function or method level.

In order to make the documentation meaningful and useful to developers, be sure to describe the purpose of classes and how they are used together. If I have an e.g. PrintJob class, I know what it is. But how does it interact with a PrintManager or PrinterProperties? What is the process of taking an object and printing it? How do these objects work together? I would expect to see a short code example showing the class interactions.

Generated documentation must also include pre- and post-conditions in plain English at the function level where appropriate. If your print() function expects a job to be in a certain state, tell me. I do not want to dig around in the code to decipher what it needs. Once the printing is done, can I reuse the job to print a second copy or is it now invalid?

Finally, omit documentation for entities that truly are simple and do not need it. If you have a List, you do not need to document the size() function. I understand it will be a nonnegative integer, and based on the data type, I know how big it can be. This reduces fluff. When I am scanning documentation, I know that if I see text, it is important. It is not documenting something that is common-sense to a developer.


问:
Should I have separate units of work for each EF bounded context?
I have some EF bounded contexts like follows

```<code>public class BoundedContext_1 : DbContext
{
    IDbSet<A> As { get; set; }
    IDbSet<B> Bs { get; set; }
}

public class BoundedContext_2 : DbContext
{
    IDbSet<C> Cs { get; set; }
    IDbSet<D> Ds { get; set; }
}

public class BoundedContext_3 : DbContext
{
    IDbSet<D> Ds { get; set; }
    IDbSet<E> Es { get; set; }
    IDbSet<F> Fs { get; set; }
}
</code>```

I am trying to implement UoW/Repository pattern for my solution.

Now it seems to me that I will end up creating many repositoris (7 in this case) each of which dedicated to a separate IDbSet of a bounded context and therefore having many units of work (3 in this case) having their own repositories - that's a lot of effort and does not seem feasible since my actual model is much more complicated than the example above.

The question is "Am I forced to go that way? should I have a separate UoW for each bounded context with its own repos?" Or there is a way to avoid this and do it in a simpler way?

Thanks in advance

答:
No, you are not forced to go that way. In fact, you could use your DbContexts and IDbSets just the way they are.

A DbContext is an implementation of the unit of work pattern. Once created, it will aggregate any changes made to its entities, and will commit when instructed.

In a same way, an IDbSet is an implementation of the repository pattern. It serves as an abstract collection of entities (IQueryable), that can be queried and has basic CRUD operations.

Here are a couple of examples:

```<code>public class BService
{
    public void DoSomethingToB(Guid bId)
    {
        using (var unitOfWork = new BoundedContext_1())
        {
            var BRepository = unitOfWork.Bs;
            var b = BRepository.Find(bId);
            b.DoSomething();
            unitOfWork.SaveChanges();
        }
    }

    public B AddNewB()
    {
        var newB = new B();
        using (var unitOfWork = new BoundedContext_1())
        {
            var BRepository = unitOfWork.Bs;
            BRepository.Add(newB);
            unitOfWork.SaveChanges();
        }
        return newB;
    }
}
</code>```

This will most definitely work. Not a single class created.

The question is whether the EF implementation is sufficient. You should check whether your project's requirements call for a layer of abstraction around EF's implementation.

Such reasons could be:

You have some non-generic logic in a repository or a unit of work that you want to unit test. It isn't straightforward to unit test EF, so you could consider calling EF from your own repo/uow and mock it when unit testing.

You want an explicit API for your repositories. e.g. BRepository.AddNewB(newB) instead of BRepository.Add(newB), or bRepo.GetBWithId(bId) instead of bRepo.Find(bId).

You estimate that you will have to replace your DAL one day and support a technology other than EF. I hear this a lot but never seen such replacement in practice. Usually when a project changes its DAL, the new technology is significantly different and the API is changed together with the implementation (e.g. switching from a RDBS to a NoSQL DB).

Body:
No, you are not forced to go that way. In fact, you could use your DbContexts and IDbSets just the way they are.

A DbContext is an implementation of the unit of work pattern. Once created, it will aggregate any changes made to its entities, and will commit when instructed.

In a same way, an IDbSet is an implementation of the repository pattern. It serves as an abstract collection of entities (IQueryable), that can be queried and has basic CRUD operations.

Here are a couple of examples:

public class BService
{
    public void DoSomethingToB(Guid bId)
    {
        using (var unitOfWork = new BoundedContext_1())
        {
            var BRepository = unitOfWork.Bs;
            var b = BRepository.Find(bId);
            b.DoSomething();
            unitOfWork.SaveChanges();
        }
    }

    public B AddNewB()
    {
        var newB = new B();
        using (var unitOfWork = new BoundedContext_1())
        {
            var BRepository = unitOfWork.Bs;
            BRepository.Add(newB);
            unitOfWork.SaveChanges();
        }
        return newB;
    }
}

This will most definitely work. Not a single class created.

The question is whether the EF implementation is sufficient. You should check whether your project's requirements call for a layer of abstraction around EF's implementation.

Such reasons could be:

You have some non-generic logic in a repository or a unit of work that you want to unit test. It isn't straightforward to unit test EF, so you could consider calling EF from your own repo/uow and mock it when unit testing.

You want an explicit API for your repositories. e.g. BRepository.AddNewB(newB) instead of BRepository.Add(newB), or bRepo.GetBWithId(bId) instead of bRepo.Find(bId).

You estimate that you will have to replace your DAL one day and support a technology other than EF. I hear this a lot but never seen such replacement in practice. Usually when a project changes its DAL, the new technology is significantly different and the API is changed together with the implementation (e.g. switching from a RDBS to a NoSQL DB).


问:
How to prevent third party misuse of what is intended to be a private api (avoiding what happened to Snapchat)?
I have never used Snapchat and do not intend to but I have been reading up about what happened to them with respect to the recent media coverage about pictures being leaked especially because I am also writing an api for my app right now and I want to avoid this from ever happening to me.

Having looked into what happened it seems Snapchat has not actually done anything wrong. It appears a third party web app sniffed out their api calls - not something to be surprised about, anyone can do it, and that's why apis should require authentication, how this is done can vary but probably through some kind of token.

In any case, Snapchat api did require authentication so I thought they would have been safe but it turns out that the third party apps got users to voluntarily enter their usernames and passwords into the app, thereby allowing login and authentication.

Remember this was a third party app, not the official snapchat app. I would never have expected users to do something like this, it's like giving away the keys to your car to anyone who passes by instead of the hotel valet.

Now to the point, are they any techniques to avoid this from happening that I can apply for my api? I am not sure how I can prevent myself from ending up in the same situation.

答:
It is impossible to prevent this issue from happening completely. There are two things you can do that will help but not completely migrate the problem:

Use SSL only: If you control both the client and the server than there is no reason you can't encrypt the traffic, this prevents people from sniffing out your API calls by studying your traffic - it also protects user secrets and help prevent man-in-the-middle attacks.

Use a Api Key. This should be a hidden key that can be attached to transactions that validates that the API call came from an approved application. Note that this is only useful if the traffic is encrypted, since the key is useless if it's visible over plain text.

Again, it is not possible to protect oneself completely as the nature of the web is pretty insecure. It wasn't built with security in mind initially so you should assume that anything exposed publicly can/will be used by another party at some point.


问:
Register user in mobile app without e-mail
We are currently developing an app for Android and iOS which requires the user to perform a registration. However we don't want the user to go through all this e-mail and password activation link stuff as we aim to let him use the app almost instantly.

The basic idea is that the user enters some mandatory data, clicks a "Register" button and all the verification stuff happens "behind the curtain" (REST via HTTPs). I have heard of some concepts with security tokens but don't know what to look for exactly.

Do you know any techniques for the above? Ideally one which works for both, iOS and Android.

答:
You could consider SMS verification, which is probably a bit easier to use compared to an email solution.

Basically you'd enter your phone number in the app and you'd receive an SMS with an activation code on said number. In iOS you even see the SMS appear in a "toast", so you don't even need to switch apps if the code is easy enough to enter.

Of course such a solution might have several disadvantages, so you should figure out for yourself if this would fit your needs.


问:
Is JSF and JPA worth learning?
I'm attending a company sponsored training event for JSF and JPA that crams 10 days of training into 5 days. I plan on getting all that I can out of the class, but there is no "final exam".</p>

答:
JPA - Yes absolutely, it's the standard underpining most Java ORM libraries out there (e.g. Hibernate).

JSF? - Not so much, it's not seen as a dominant std (that said, no web framework is the dominant std) and is expected to keep slipping in terms of mind-share and deployment (unless some radical changes are made).

Title: Is JSF and JPA worth learning?


问:
In a generic method, what exception should I throw when a type parameter is unacceptable?
When the value of a normal parameter is unacceptable (and the requirements can't be checked completely at compile time), we check at runtime and throw an ArgumentException if the check fails.

When the "value" of a type parameter is similarly unacceptable, what kind of exception do we throw? Are there any guidelines on this?

(Note: If I try ArgumentException, ReSharper wants to complain - which makes me think there may be another kind of exception that's recommended for this.)

答:
There isn't a native exception in the .NET Framework for "Invalid Type Parameter Argument."  Jon Skeet asked about this on Stack Overflow, and ultimately decided to write his own:</p>

```<code>#region License and Terms
// Unconstrained Melody
// Copyright (c) 2009-2011 Jonathan Skeet. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion

using System;
using System.Runtime.Serialization;

namespace UnconstrainedMelody
{
    /// <summary>
    /// Exception thrown to indicate that an inappropriate type argument was used for
    /// a type parameter to a generic type or method.
    /// </summary>
    public class TypeArgumentException : Exception
    {
        /// <summary>
        /// Constructs a new instance of TypeArgumentException with no message.
        /// </summary>
        public TypeArgumentException()
        {
        }

        /// <summary>
        /// Constructs a new instance of TypeArgumentException with the given message.
        /// </summary>
        /// <param name="message">Message for the exception.</param>
        public TypeArgumentException(string message)
            : base(message)
        {
        }

        /// <summary>
        /// Constructs a new instance of TypeArgumentException with the given message and inner exception.
        /// </summary>
        /// <param name="message">Message for the exception.</param>
        /// <param name="inner">Inner exception.</param>
        public TypeArgumentException(string message, Exception inner)
            : base(message, inner)
        {
        }

        /// <summary>
        /// Constructor provided for serialization purposes.
        /// </summary>
        /// <param name="info">Serialization information</param>
        /// <param name="context">Context</param>
        protected TypeArgumentException(SerializationInfo info, StreamingContext context) : base(info, context)
        {
        }
    }
}
</code>```

Body:
There isn't a native exception in the .NET Framework for "Invalid Type Parameter Argument."  Jon Skeet asked about this on Stack Overflow, and ultimately decided to write his own:

#region License and Terms
// Unconstrained Melody
// Copyright (c) 2009-2011 Jonathan Skeet. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion

using System;
using System.Runtime.Serialization;

namespace UnconstrainedMelody
{
    /// <summary>
    /// Exception thrown to indicate that an inappropriate type argument was used for
    /// a type parameter to a generic type or method.
    /// </summary>
    public class TypeArgumentException : Exception
    {
        /// <summary>
        /// Constructs a new instance of TypeArgumentException with no message.
        /// </summary>
        public TypeArgumentException()
        {
        }

        /// <summary>
        /// Constructs a new instance of TypeArgumentException with the given message.
        /// </summary>
        /// <param name="message">Message for the exception.</param>
        public TypeArgumentException(string message)
            : base(message)
        {
        }

        /// <summary>
        /// Constructs a new instance of TypeArgumentException with the given message and inner exception.
        /// </summary>
        /// <param name="message">Message for the exception.</param>
        /// <param name="inner">Inner exception.</param>
        public TypeArgumentException(string message, Exception inner)
            : base(message, inner)
        {
        }

        /// <summary>
        /// Constructor provided for serialization purposes.
        /// </summary>
        /// <param name="info">Serialization information</param>
        /// <param name="context">Context</param>
        protected TypeArgumentException(SerializationInfo info, StreamingContext context) : base(info, context)
        {
        }
    }
}


问:
In an Agile Environment, who is responsible for software architecture
In an agile team, who is responsible for making high-level architecture and design decisions that affect the entire system, not just the work being done in the current sprint?

Maybe product owner, scrum master, the scrum team or someone else?

答:
"The software architecture is performed by the entire team. This
  practice does not remove the need for a software architect, it just
  means that the architect contributes to the discussion with a broader
  and probably more experienced perspective, nevertheless all members of
  the team contribute towards the architecture of the software."

Source: http://www.executivebrief.com/blogs/software-architecture-agile-environment-sashimi-approach/


问:
Is the JVM "heap" inside the JVM software, or inside the physical computer?
I wanted to as this question about VMs in general, but focused it to JVM implementations only so this doesn't get closed as too broad.

The JVM has a concept of a "heap". If my understanding is correct, the heap is simply the "free store" where you can save data, i.e. anywhere in RAM that doesn't have another purpose (such as the stack).

When we say "the heap" in the context of the JVM, are we talking about somewhere inside the VM itself (which may or may not be allocated on the heap of the underlying physical computer)? Or do we refer to the heap of the physical computer?

答:
The specification is very clear about it

2.5.3. Heap

The Java Virtual Machine has a heap that is shared among all Java Virtual Machine threads. The heap is the run-time data area from which memory for all class instances and arrays is allocated.

The heap is created on virtual machine start-up. Heap storage for objects is reclaimed by an automatic storage management system (known as a garbage collector); objects are never explicitly deallocated. The Java Virtual Machine assumes no particular type of automatic storage management system, and the storage management technique may be chosen according to the implementor's system requirements. The heap may be of a fixed size or may be expanded as required by the computation and may be contracted if a larger heap becomes unnecessary. The memory for the heap does not need to be contiguous.

A Java Virtual Machine implementation may provide the programmer or the user control over the initial size of the heap, as well as, if the heap can be dynamically expanded or contracted, control over the maximum and minimum heap size.

The following exceptional condition is associated with the heap:

If a computation requires more heap than can be made available by the automatic storage management system, the Java Virtual Machine throws an OutOfMemoryError.

To answer your question:

When we say "the heap" in the context of the JVM, are we talking about somewhere inside the VM itself (which may or may not be allocated on the heap of the underlying physical computer)? Or do we refer to the heap of the physical computer?

When we speak of heap, we speak of already allocated memory for the JVM. So, it is inside (?) the JVM (if that makes any sense to say). The JVM has its own memory management.


问:
Architecture guidelines for a "single page web-app"
I'm going to start a side project to build a "single page" web application. The application needs to be real-time, sending updates to the clients as changes happen.

Are there any good resources for best-practice approaches wrt the architecture for these kinds of applications. The best resource I've found so far is the trello architecture article here: http://blog.fogcreek.com/the-trello-tech-stack/

To me, this architecture, although very sexy, is probably over-engineered for my specific needs - although I do have similar requirements. I'm wondering if I need to bother with a sub/pub at the server side, could I not just push updates from the server when something happens (e.g. when the client sends an update to the server, write the update to the db, and then send an update to the clients).

Tech-wise, I'm probably looking to build this out in Node.JS or maybe Ruby, although the architecture guidelines should to some extent apply to any underlying server technologies.

答:
This is a no brainer IMO. AngularJS for the front end because it's awesome.  NodeJS/express/SocketIO for a dynamic and sexy backend with pub/sub goodness and a minimum of fuss.  And as a bonus, you can use one language for the front and the back!

Check out my implementation of same https://github.com/hackify/hackify-server for an example

One caveat, some folks are recommending a NodeJS alternative to socketio called sockjs but I haven't checked this out so I can't recommend it


问:
Different operators in query string like ?var!=value
This one may actually be 2 questions in one.

Studying some APIs I came across an api suggesting to have operand different from equal (=) inside the query string (http://www.salesboard.com/api/):

```<code>mycompany.salesboard.com/api/contacts?CompanyId!=5
or
mycompany.salesboard.com/api/contacts?Id<=5
</code>```

Is that possible?? and by "possible" I mean: is that legal according to the standards?
And if yes what are the possible problems to use such a url (compatibility, browser support, etc).

Now the second part of the question is: What is the best way to parse a URL such as this in PHP, has anyone ever used it?

PS: My question is not really problem but I thought it would be nice also for others to know.

答:
The standard for URIs is STD 66, which currently maps to RFC 3986.

In section 3.4, it is defined what the query component may contain. (Note that it can’t contain an unencoded <).

However, it does not define any meanings for characters (like =) that can appear in the query component. Using a format like key=value is just a convention as far as the general URI standard is concernced.

Specific URI schemes might define such meanings, but the http URI scheme doesn’t seem to.

So semantically, there is no difference between using foo/bar, CompanyId!=5, or CompanyId-is-not-equal-to-5. They are just characters and it’s up to the consumers to interpret them.


问:
How to clean up nested try/except/else?
When writing code, I often want to do something like this:

try:
    foo()
except FooError:
    handle_foo()
else:
    try:
        bar()
    except BarError:
        handle_bar()
    else:
        try:
            baz()
        except BazError:
            handle_baz()
        else:
            qux()
finally:
    cleanup()
```

<p>Obviously, this is completely unreadable.  But it's expressing a relatively simple idea: execute a series of functions (or short code snippets), with an exception handler for each one, and stop as soon as a function fails.  I imagine Python could provide syntactic sugar for this code, perhaps something like this:</p>

<pre class="lang-py prettyprint-override"><code># NB: This is *not* valid Python
try:
    foo()
except FooError:
    handle_foo()
    # GOTO finally block
else try:
    bar()
except BarError:
    handle_bar()
    # ditto
else try:
    baz()
except BazError:
    handle_baz()
    # ditto
else:
    qux()
finally:
    cleanup()
</code>```

If no exceptions are raised, this is equivalent to foo();bar();baz();qux();cleanup().  If exceptions are raised, they're handled by the appropriate exception handler (if any) and we skip to cleanup().  In particular, if bar() raises a FooError or BazError, the exception will not be caught and will propagate to the caller.  This is desirable so we only catch exceptions we're truly expecting to handle.

Regardless of syntactic ugliness, is this kind of code just a bad idea in general?  If so, how would you refactor it?  I imagine context managers could be used to absorb some of the complexity, but I don't really understand how that would work in the general case.

答:
There are a couple different ways, depending on what you need.

Here's a way with loops:

```<code>try:
    for func, error, err_handler in (
            (foo, FooError, handle_foo),
            (bar, BarError, handle_bar),
            (baz, BazError, handle_baz),
        ):
        try:
            func()
        except error:
            err_handler()
            break
finally:
    cleanup()
</code>```

Here's a way with an exit after the error_handler:

```<code>def some_func():
    try:
        try:
            foo()
        except FooError:
            handle_foo()
            return
        try:
            bar()
        except BarError:
            handle_bar()
            return
        try:
            baz()
        except BazError:
            handle_baz()
            return
        else:
            qux()
    finally:
        cleanup()
</code>```

Personally I think the loop version is easier to read.

Title: How to clean up nested try/except/else?

Body:
There are a couple different ways, depending on what you need.

Here's a way with loops:

try:
    for func, error, err_handler in (
            (foo, FooError, handle_foo),
            (bar, BarError, handle_bar),
            (baz, BazError, handle_baz),
        ):
        try:
            func()
        except error:
            err_handler()
            break
finally:
    cleanup()

Here's a way with an exit after the error_handler:

def some_func():
    try:
        try:
            foo()
        except FooError:
            handle_foo()
            return
        try:
            bar()
        except BarError:
            handle_bar()
            return
        try:
            baz()
        except BazError:
            handle_baz()
            return
        else:
            qux()
    finally:
        cleanup()

Personally I think the loop version is easier to read.


答:
It seems like you have sequence of commands that may throw an exception that needs to be handled before returning.  Try grouping your code and and exception handling in separate locations.  I believe this does what you intend.</p>

```<code>try:
    foo()
    bar()
    baz()
    qux()

except FooError:
    handle_foo()
except BarError:
    handle_bar()
except BazError:
    handle_baz()

finally:
    cleanup()
</code>```

Title: How to clean up nested try/except/else?

Body:
When writing code, I often want to do something like this:

try:
    foo()
except FooError:
    handle_foo()
else:
    try:
        bar()
    except BarError:
        handle_bar()
    else:
        try:
            baz()
        except BazError:
            handle_baz()
        else:
            qux()
finally:
    cleanup()
```

<p>Obviously, this is completely unreadable.  But it's expressing a relatively simple idea: execute a series of functions (or short code snippets), with an exception handler for each one, and stop as soon as a function fails.  I imagine Python could provide syntactic sugar for this code, perhaps something like this:</p>

<pre class="lang-py prettyprint-override"><code># NB: This is *not* valid Python
try:
    foo()
except FooError:
    handle_foo()
    # GOTO finally block
else try:
    bar()
except BarError:
    handle_bar()
    # ditto
else try:
    baz()
except BazError:
    handle_baz()
    # ditto
else:
    qux()
finally:
    cleanup()
</code>```

If no exceptions are raised, this is equivalent to foo();bar();baz();qux();cleanup().  If exceptions are raised, they're handled by the appropriate exception handler (if any) and we skip to cleanup().  In particular, if bar() raises a FooError or BazError, the exception will not be caught and will propagate to the caller.  This is desirable so we only catch exceptions we're truly expecting to handle.

Regardless of syntactic ugliness, is this kind of code just a bad idea in general?  If so, how would you refactor it?  I imagine context managers could be used to absorb some of the complexity, but I don't really understand how that would work in the general case.

Body:
It seems like you have sequence of commands that may throw an exception that needs to be handled before returning.  Try grouping your code and and exception handling in separate locations.  I believe this does what you intend.

try:
    foo()
    bar()
    baz()
    qux()

except FooError:
    handle_foo()
except BarError:
    handle_bar()
except BazError:
    handle_baz()

finally:
    cleanup()


答:
Its okay to write the interface/code/test at the same time as long as their incorporation into the project is atomic.

Unless your boss is religious about TDD, in which case you probably have to write empty interface -> test -> minimal code (pointless step) -> more tests -> more pointless code -> more tests -> finally write the real code -> done.

Title: In TDD should I have to write Test first or Interface first?


答:
First of all, appropriate use of with can often reduce or even eliminate a lot of the exception handling code, improving both maintainability and readability.

Now, you can reduce the nesting in many ways; other posters have already provided a few, so here's my own variation:

```<code>for _ in range(1):
    try:
        foo()
    except FooError:
        handle_foo()
        break
    try:
        bar()
    except BarError:
        handle_bar()
        break
    try:
        baz()
    except BazError:
        handle_baz()
        break
    qux()
cleanup()
</code>```

Title: How to clean up nested try/except/else?

Body:
First of all, appropriate use of with can often reduce or even eliminate a lot of the exception handling code, improving both maintainability and readability.

Now, you can reduce the nesting in many ways; other posters have already provided a few, so here's my own variation:

for _ in range(1):
    try:
        foo()
    except FooError:
        handle_foo()
        break
    try:
        bar()
    except BarError:
        handle_bar()
        break
    try:
        baz()
    except BazError:
        handle_baz()
        break
    qux()
cleanup()


答:
```<code>try:
    foo()
except FooError:
    handle_foo()
else:
    ...
finally:
    cleanup()
</code>```

What does handle_foo do? There are a few things we typically do in exception handling blocks.

Cleanup after the error: But in this case, foo() should cleanup after itself, not leave us to do so. Additionally, most cleanup jobs are best handled with with

Recover to the happy path: But you aren't doing this as you don't continue to the rest of the functions.

Translates the exception type: But you aren't throwing another exception

Log the error: But there shouldn't be any need to have special exception blocks for each type.

It seems to me that you are doing something odd in your exception handling. Your question here is simple a symptom on using exceptions in an unusual way. You're not falling into the typical pattern, and that's why this has become awkward.

Without a better idea of what you're doing in those handle_ functions that's about all I can say.

Title: How to clean up nested try/except/else?

Body:
try:
    foo()
except FooError:
    handle_foo()
else:
    ...
finally:
    cleanup()

What does handle_foo do? There are a few things we typically do in exception handling blocks.

Cleanup after the error: But in this case, foo() should cleanup after itself, not leave us to do so. Additionally, most cleanup jobs are best handled with with

Recover to the happy path: But you aren't doing this as you don't continue to the rest of the functions.

Translates the exception type: But you aren't throwing another exception

Log the error: But there shouldn't be any need to have special exception blocks for each type.

It seems to me that you are doing something odd in your exception handling. Your question here is simple a symptom on using exceptions in an unusual way. You're not falling into the typical pattern, and that's why this has become awkward.

Without a better idea of what you're doing in those handle_ functions that's about all I can say.


答:
There are some great resources from the Scaled Agile Framework (SAFe) team on their site.

It essentially helps you scale out agile across your organization, going above a single release and into portfolio and program planning. Their documentation shows suggestions on how to involve your Enterprise and System Architects in the process to introduce architectural epics into the release train.

Edit for clarity to address the question more directly:

In a scaled agile environment there are multiple tiers of ownership over the architecture. The agile implementation team will own the low-level emerging architecture by refactoring as needed to continue their implementation of their backlogs. Higher-level architectural decisions (supported operating systems, browsers, platforms, libraries) are under the responsibility of your system and enterprise architects. They will make the business cases for when these changes need to occur and will recommend for these architectural changes be added to the release train for the implementation teams.

So, in regards to the high-level architecture decisions that go beyond the sprint, you will usually have these made at a level above the team. These professionals traditionally have an 'architect' role within the enterprise already.

Title: In an Agile Environment, who is responsible for software architecture

Body:
In an agile team, who is responsible for making high-level architecture and design decisions that affect the entire system, not just the work being done in the current sprint?

Maybe product owner, scrum master, the scrum team or someone else?


答:
If you want real-time client updates, then you will either have to implement the long-blocking "AJAX" calls, or preferably use the modern websockets. These allow you to push updates to a connected client which will be handled by a bit of javascript.

I understand the current state-of-the-art (or latest fad) is AngularJS by Google. Its partly designed to make writing SPAs easier.

Title: Architecture guidelines for a "single page web-app"

Body:
I'm going to start a side project to build a "single page" web application. The application needs to be real-time, sending updates to the clients as changes happen.

Are there any good resources for best-practice approaches wrt the architecture for these kinds of applications. The best resource I've found so far is the trello architecture article here: http://blog.fogcreek.com/the-trello-tech-stack/

To me, this architecture, although very sexy, is probably over-engineered for my specific needs - although I do have similar requirements. I'm wondering if I need to bother with a sub/pub at the server side, could I not just push updates from the server when something happens (e.g. when the client sends an update to the server, write the update to the db, and then send an update to the clients).

Tech-wise, I'm probably looking to build this out in Node.JS or maybe Ruby, although the architecture guidelines should to some extent apply to any underlying server technologies.


答:
The best architectures, requirements, and designs emerge from
  self-organizing teams

-- Agile Manifesto

So the team self-organizes to make architectural decisions in whatever way it sees fit. There's no hard and fast rule, it can range from consensus to a "council" of the most senior members, to designating one particular member as the architecture authority, to letting the architect choose if there is a member with such a job title...


问:
What is RESTful way of action confirmation?
Some of my API actions require SMS confirmation due to security reasons, like creation of payment and CRUD for scheduled payments.

Right now I just return an entity with AwaitingSMSConfirmation state and confirmationId.
And then POST /SMSConfirmation with one time password and id.

Is my decision with state correct? Is there any canonical generic RESTful way for this?

答:
I don't know of any canon, and IMHO that approach sounds quite workable...

Since you're interested in a "RESTful" aesthetic, you might start from the first principle of "RESTful": "representational state transfer". The general emphasis in RESTful is to accomplish changes in the server by sending over the new state of the entity. In this case, you're changing the state of the ScheduledPayment entity from "AwaitingSMSConfirmation" to, say, "Confirmed". I think it's more RESTful to say:

```<code>POST /ScheduledPayment/123
state=Confirmed&confirmation_code=1a2b3c4d5e6f7
</code>```

Aside: You might find something interesting by searching on REST and email-based confirmation codes, e.g. https://stackoverflow.com/questions/6664154/restful-reset-password-and-confirm-email In that discussion, you'll see several variations, and IMHO all of them would be equally recognizable to a general audience of programmers.

Body:
I don't know of any canon, and IMHO that approach sounds quite workable...

Since you're interested in a "RESTful" aesthetic, you might start from the first principle of "RESTful": "representational state transfer". The general emphasis in RESTful is to accomplish changes in the server by sending over the new state of the entity. In this case, you're changing the state of the ScheduledPayment entity from "AwaitingSMSConfirmation" to, say, "Confirmed". I think it's more RESTful to say:

POST /ScheduledPayment/123
state=Confirmed&confirmation_code=1a2b3c4d5e6f7

Aside: You might find something interesting by searching on REST and email-based confirmation codes, e.g. https://stackoverflow.com/questions/6664154/restful-reset-password-and-confirm-email In that discussion, you'll see several variations, and IMHO all of them would be equally recognizable to a general audience of programmers.


问:
Should I put the name of the method I'm testing in the Unit Test method's name/assert message?
Given that a method's name might change in time, is it a good idea to specify the name of the method whose return value I am asserting as a part of the Unit Test method's name? What about the message that will be output to the caller?

For example, I have a Foo object that has a Bar method. I would like to assert if Bar returns true in some specific conditions. I write such a Unit Test:

```<code>public void Bar_ReturnsTrue_Always()
{
    // the logic of the method goes here

    Assert.IsTrue(Foo.Bar(), "Return value of Bar was different then: true"
}
</code>```

It seems pretty ugly to me, because the name Bar may change in the future, for example to Blargh. If this happens, there is a possibility that the developer will forget to change relevant information in one or both places where it's necessary (method's name and the message). On the other hand, how is the caller supposed to know what is being tested if such information isn't publicly present? I can't think of a good enough solution to this. Any ideas?

答:
It's not generally needed. As @Telastyn says, if the test case fails, then it will become quickly and readily apparent what method failed.

The real need is to have the purpose of your test easily understood by those that

are adding, reviewing, or modifying tests after you (even if that person is also you), and

are reviewing the code and searching for causes if/when the test fails.

It's not bad practice, per se, to name the method in either the  test case/function, or in the error message. If it's easy to do and feels appropriate--as it does in your example--feel free. If the test is "Bar() should return true" then Bar_Always_True is reasonable. On the other hand, if your method is AddInt and you're testing A + B == B + A, Addition_Is_Commutative might make more sense than a test case name that insists on including AddInt in the name. This "state your intention rather than your method name" principle becomes ever more important as test cases become more complex, potentially involving more than one method.


问:
Which things instantly ring alarm bells when looking at code?
I attended a software craftsmanship event a couple of weeks ago and one of the comments made was "I'm sure we all recognize bad code when we see it" and everyone nodded sagely without further discussion.

This sort of thing always worries me as there's that truism that everyone thinks they're an above average driver. Although I think I can recognize bad code I'd love to learn more about what other people consider to be code smells as it's rarely discussed in detail on people's blogs and only in a handful of books. In particular I think it'd be interesting to hear about anything that's a code smell in one language but not another.

I'll start off with an easy one:

Code in source control that has a high proportion of commented out
  code - why is it there? was it meant
  to be deleted? is it a half finished
  piece of work? maybe it shouldn't have
  been commented out and was only done
  when someone was testing something
  out? Personally I find this sort of
  thing really annoying even if it's just the odd line here and there, but when you see large blocks interspersed with the rest of the code it's totally unacceptable. It's
  also usually an indication that the rest of
  the code is likely to be of dubious
  quality as well.

答:
Disgruntled comments demonstrating lack of restraint:

//I CAN'T GET THIS F^#*&^ING PIECE OF S$^* TO COMPILE ON M$VC
```

Either they're ill-tempered or they're not experienced enough to have learned that setbacks are inevitable in programming.

I don't want to work with people like that.

Body:
Disgruntled comments demonstrating lack of restraint:

//I CAN'T GET THIS F^#*&^ING PIECE OF S$^* TO COMPILE ON M$VC

Either they're ill-tempered or they're not experienced enough to have learned that setbacks are inevitable in programming.

I don't want to work with people like that.


问:
A good generic type system
It's commonly accepted that Java generics failed in some important ways. The combination of wildcards and bounds led to some seriously unreadable code.

However, when I look at other languages, I really can't seem to find a generic type system that programmers are happy with.

If we take the following as design goals of a such a type system:

Always produces easy-to-read type declarations

Easy to learn (no need to brush up on covariance, contravariance, etc.)

maximizes the number of compile-time errors

Is there any language that got it right? If I google, the only thing I see is complaints about how the type system sucks in language X. Is this kind of complexity inherent in generic typing? Should we just give up on trying to verify type safety 100% at compile time?

My main question is which is the language that "got it right" the best with respect to these three goals. I realize that that's subjective, but so far I can't even find one language where not all it's programmers agree that the generic type system is a mess.

Addendum: as noted, the combination of subtyping/inheritance and generics is what creates the complexity, so I'm really looking for a language that combines both and avoids the explosion of complexity.

答:
The use of subtypes creates a lot of complications when doing generic programming.  If you insist on using a language with subtypes, you have to accept there's a certain inherent complexity in generic programming that comes along with it.  Some languages do it better than others, but you can only take it so far.

Contrast that with Haskell's generics, for example.  They are simple enough that if you use type inference, you can write a correct generic function by accident.    In fact, if you specify a single type, the compiler often says to itself, "Well, I was going to make this generic, but you asked me to make it only for ints, so whatever."

Admittedly, people use Haskell's type system in some startlingly complex ways, making it the bane of every newbie, but the underlying type system itself is elegant and much admired.

Title: A good generic type system


问:
Relative encapsulation design
Let's say I am doing a 2D application with the following design:

There is the Level object that manages the world, and there are world objects which are entities inside the Level object.

A world object has a location and velocity, as well as size and a texture. However, a world object only exposes get properties. The set properties are private (or protected) and are only available to inherited classes.

But of course, Level is responsible for these world objects, and must somehow be able to manipulate at least some of its private setters. But as of now, Level has no access, meaning world objects must change its private setters to public (violating encapsulation).

How to tackle this problem? Should I just make everything public?

Currently what I'm doing is having a inner class inside game object that does the set work. So when Level needs to update an objects location it goes something like this:

```<code>void ChangeObject(GameObject targetObject, int newX, int newY){
 // targetObject.SetX and targetObject.SetY cannot be set directly
 var setter = new GameObject.Setter(targetObject);
 setter.SetX(newX);
 setter.SetY(newY);
}
</code>```

This code feels like overkill, but it doesn't feel right to have everything public so that anything can change an objects location for example.

答:
How about using interfaces?

```<code>public interface IImmutableWorld
{
    // only get methods
}

public interface IMutableWorld : IImmutableWorld
{
    // add set methods
}

public class World : IMutableWorld
{
    // implementation for both get and set methods.
}
</code>```

You don't need to  directly talk with World class, you talk with the interfaces.

For example, Level will talk with IMutableWorld and can use its set methods.
Other classes will talk to IImmutableWorld, so they don't have access to set methods.

If you are still worry about that someone can create a World instance and directly manipulate it, you can use Factory.

```<code>public class WorldFactory
{
    IImmutableWorld createImmutableWorld()
    {
        // return World instance
    }

    IMutableWorld createMutableWorld()
    {
        // return World instance
    }
}
</code>```

Make World as an inner class of WorldFacotry, now, other classes don't know the existing of World. It forces them to deal with the interfaces.

Title: Relative encapsulation design

Body:
How about using interfaces?

public interface IImmutableWorld
{
    // only get methods
}

public interface IMutableWorld : IImmutableWorld
{
    // add set methods
}

public class World : IMutableWorld
{
    // implementation for both get and set methods.
}

You don't need to  directly talk with World class, you talk with the interfaces.

For example, Level will talk with IMutableWorld and can use its set methods.
Other classes will talk to IImmutableWorld, so they don't have access to set methods.

If you are still worry about that someone can create a World instance and directly manipulate it, you can use Factory.

public class WorldFactory
{
    IImmutableWorld createImmutableWorld()
    {
        // return World instance
    }

    IMutableWorld createMutableWorld()
    {
        // return World instance
    }
}

Make World as an inner class of WorldFacotry, now, other classes don't know the existing of World. It forces them to deal with the interfaces.


答:
No, you do not need to add messages to most assertions. Writing unit tests as you suggest would be needlessly tedious.  Presumably the Assert.IsTrue method will throw an exception saying something like "Expected true, got false".  The ensuing stack trace will pinpoint the cause of the failure.

N.B. In general, as a programmer, you should not be spending time writing obvious and repetitive code.  If you are, then it is likely you misunderstand the library you are using, or else there is some library that will simplify the work.  If you feel that your work could be done by a trained monkey, something is wrong.

Title: Should I put the name of the method I'm testing in the Unit Test method's name/assert message?

Body:
Given that a method's name might change in time, is it a good idea to specify the name of the method whose return value I am asserting as a part of the Unit Test method's name? What about the message that will be output to the caller?

For example, I have a Foo object that has a Bar method. I would like to assert if Bar returns true in some specific conditions. I write such a Unit Test:

```<code>public void Bar_ReturnsTrue_Always()
{
    // the logic of the method goes here

    Assert.IsTrue(Foo.Bar(), "Return value of Bar was different then: true"
}
</code>```

It seems pretty ugly to me, because the name Bar may change in the future, for example to Blargh. If this happens, there is a possibility that the developer will forget to change relevant information in one or both places where it's necessary (method's name and the message). On the other hand, how is the caller supposed to know what is being tested if such information isn't publicly present? I can't think of a good enough solution to this. Any ideas?


问:
Algorithm for tiling a surface with no adjacent tiles
I am looking for an algorithm that does as follows:

Given a 2D grid of X,Y and a number of tiles T, places a tile in each cell of the grid such that the surrounding tiles are not the same.

This should also ideally be capable of providing a random seed to randomize the output.

I understand that for not all values of X, Y and T this is possible, but is there an existing algorithm that will do what I'm looking for? I'm currently using a naive hand-rolled implementation that doesn't always provide the best results.

Is something like a constraint solver what I need?

答: Randomly distribute the most numerous tile so that there are no adjacencies.  Then randomly distribute the next most numerous tile, and so on.  That should work well unless the two most numerous tiles cover almost the entire rectangle.</p>


问:
Programming language with pattern matching in trees
I'd like to prototype a computer algebra system. An equation would be represented by a tree and rules would be defined - similarly to mathematical axioms - by specifying a pattern (in the tree) and a restructuring rule for the matched part of the tree.

Can you suggest a programming language I could experiment with to test this approach (ideally not too experimental language)? Basically it should support high level data structures like lists (or actually trees) and make it easy to match the tree against a pattern and also replace part of a tree by a substitute. So it's about high level data structure pattern matching and easy modification of that.

EDIT: Of course I could take any programming language to write the program in the end, but I'm looking specifically for something which makes it easy to do first idea prototyping. I don't mind learning a new language (for fun).

答:
The kind of tree pattern matching you need is not provided out-of-the-box by any of the programming languages mentioned before. For example, if you want to try to factorize a sum of many terms each consisting of an arbitrary number of factors, your patterns need to be non-linear (to find the common factors) and allow segment assignment (to preserve everything else). Although widely available in string pattern matching, these features are strangely absent in most tree pattern matching implementations.

You can look at Tom (http://tom.loria.fr/wiki/index.php5/Main_Page), Egison (http://www.egison.org/) and at my pet-language Bracmat. (Search for that one on GitHub, I'm out of links as I am new at stackexchange). Bracmat is far beyond the experimental stage. Although I use it professionally mostly for natural language processing, it started as a small computer algebra system back in 1988.

You can find Egison and Bracmat examples on rosettacode.


问:
Implementing a tricky REST API with ASP.NET Web API
I'm trying to build a RESTful API using ASP.NET Web API for a game, and here are the methods I have so far:

```<code>/games GET
/games/:id GET
/games POST
/games PUT
/games DELETE
/users GET
/users/:id GET
/users/:id/games GET  (fetch user's games)
/users POST
/users PUT
/users DELETE
</code>```

I have two questions:

Where would I place the /users/:id/games method? I have two controllers (GamesController.cs and UsersController.cs).  The resource I'm requesting is games, so should it go in the GamesController and pass the userid as a parameter, and I would just map it to the /users/:id/game route?

Though I have a method that returns a bunch of games (/games GET), I actually wouldn't be using that at least initially. I will instead be displaying only 1 game at a time to the user, and this game will be a "popular/hot" game where there is a lot of activity and the user can also take some action (there are other games where the user cannot do any action and has to wait for action from the opponent). I can have a method called GetHotGame() that will determine which game to show to the user, when the user clicks "Next", but what I'm wondering is what the REST method should be?

Could I just use the /games/:id endpoint and pass in "hot" as the id and use the GetHotGame method to decide which game to return to the user? Or should I be using the /games endpoint and pass in "hot" as a querystring and implement a sort of paging where the page count is just one? Or, should I have a separate endpoint altogether, something like games/hot or /hotgame?

答:
First, an alternative to consider...

After many years of designing and implementing web services (and inheriting some rather sub-par implementations as well), I've reached a conclusion that some others have as well: Avoid nested resource paths.

Matthew Beale's Suggested REST API Practices article explains the reasoning behind this. (Look in the First-class Models section.)

But if you insist...

If you have to (or prefer to) use nested resource paths, I would suggest grouping methods based on what type of resource they return. So /users/:id/games would be implemented in GamesController. My reasoning here is that it maintains a more consistent correlation between API classes and DAL classes, which helps avoid guesswork later on, and reduces the number of inter-class dependencies.

I think your querystring suggestion is the cleanest, basically for the same reasons as #1 (it returns a game, so it should be under the /games resource, and implemented in GamesController). Something like /games?keyword=hot&limit=1 resembles the pattern of successful, intuitive API approaches I've seen used elsewhere.

OwnerDisplayName: Prabhu


问:
How to perform deferred tasks in backend
Actually the problem is very common. Let me describe this by example.

Imagine you have a web service where users register and pay for some gold status. There is expiration date. The question is how to remove the gold status in time?

I see at least two solutions:

Write a daemon that checks user statuses and current time and perform some actions

Use cron as a deamon and do the same

But I believe there are other approaches. By the way the language the system is written is Python but I don't think this really matters.

答:
I believe there are two basic approaches:

check the current status every time it's necessary

have a process run at some regular interval to do the checking

The problem with the first method is it can get resource intensive, while the problem with the second is that there may be a window where the user shouldn't have the "gold status" but does.

For the second option whether you use cron or a custom deamon or a custom timed method in the program itself really makes no difference.


问:
Percentage or Pixel for layouts?

What will you use for a webpage layout? Percentage or pixels?

When should one use one over the
other?

答:
I use relative / proportionate sizes whenever possible. I find it makes it much easier to make changes to layouts later. Also, using a size relative to a parent element means a change to the parent easily trickles down.

Traditionally, using relative sizes also allowed pages to look correct in various resolutions and was especially beneficial for browser zooming or minimum font sizes. But modern browsers now handle resizing extremely well with pixel-specific layouts, even enlarging images as necessary.  So it's become less important to use relative sizes.

Title: Percentage or Pixel for layouts?


答:
Assuming you're using a database to store account information, filtering a search on "account_expiry>=get_date()" on the database (i.e. in SQL) is a negligible operation.

If you're not using a database for account information, your approach would vary based on what you're using.

To answer your titled question, how do you run a deferred task on a backend in python, look at Celery

Title: How to perform deferred tasks in backend

Body:
Actually the problem is very common. Let me describe this by example.

Imagine you have a web service where users register and pay for some gold status. There is expiration date. The question is how to remove the gold status in time?

I see at least two solutions:

Write a daemon that checks user statuses and current time and perform some actions

Use cron as a deamon and do the same

But I believe there are other approaches. By the way the language the system is written is Python but I don't think this really matters.


答:
There was quite a bit of research into combining generics with subtyping going on about 20 years ago.  The Thor programming language developed by Barbara Liskov's research group at MIT had a notion of "where" clauses that let you specify the requirements of the type you are parameterizing over.  (This is similar to what C++ is trying to do with Concepts.)

The paper describing Thor's generics and how they interact with Thor's subtypes is:
Day, M; Gruber, R; Liskov, B; Myers, AC: Subtypes vs. where clauses: constraining parametric polymorphism, ACM Conf on Obj-Oriented Prog, Sys, Lang and Apps, (OOPSLA-10):156-158, 1995.

I believe they, in turn, built on work that was done on Emerald during the late 1980s.  (I haven't read that work, but the reference is: Black, A; Hutchinson, N; Jul, E; Levy, H; Carter, L: Distribution and Abstract Types in Emerald, _IEEE T. Software Eng., 13(1):65-76, 1987.

Both Thor and Emerald were "academic languages" so they probably didn't get enough usage for people to really understand whether where clauses (concepts) really solves any real problems.  It is interesting to read Bjarne Stroustrup's article on why the first try at Concepts in C++ failed:  Stroustrup, B: The C++0x "Remove Concepts" Decision, Dr Dobbs, July 22, 2009.  (Further info on Stroustrup's home page.)

Another direction that people seem to be trying is something called traits.  For example Mozilla's Rust programming language uses traits.  As I understand it (which may be completely wrong), declaring that a class satisfies a trait is very much like saying that a class implements an interface, but you are saying "behaves like a" rather than "is a".  It seems that Apple's new Swift programming languages is using a similar concept of protocols to specify constraints on the parameters to generics.

Title: A good generic type system

Body:
It's commonly accepted that Java generics failed in some important ways. The combination of wildcards and bounds led to some seriously unreadable code.

However, when I look at other languages, I really can't seem to find a generic type system that programmers are happy with.

If we take the following as design goals of a such a type system:

Always produces easy-to-read type declarations

Easy to learn (no need to brush up on covariance, contravariance, etc.)

maximizes the number of compile-time errors

Is there any language that got it right? If I google, the only thing I see is complaints about how the type system sucks in language X. Is this kind of complexity inherent in generic typing? Should we just give up on trying to verify type safety 100% at compile time?

My main question is which is the language that "got it right" the best with respect to these three goals. I realize that that's subjective, but so far I can't even find one language where not all it's programmers agree that the generic type system is a mess.

Addendum: as noted, the combination of subtyping/inheritance and generics is what creates the complexity, so I'm really looking for a language that combines both and avoids the explosion of complexity.