问:
Is it bad to use Unicode characters in variable names?
I recently tried to implement a ranking algorithm, AllegSkill, to Python 3.

Here's what the maths looks like:

No, really.

This is then what I wrote:

```<code>t = (µw-µl)/c  # those are used in
e = ε/c        # multiple places.
σw_new = (σw**2 * (1 - (σw**2)/(c**2)*Wwin(t, e)) + γ**2)**.5
</code>```

I actually thought it is unfortunate of Python 3 to not accept √ or ² as variable names.

```<code>>>> √ = lambda x: x**.5
  File "<stdin>", line 1
    √ = lambda x: x**.5
      ^
SyntaxError: invalid character in identifier
</code>```

Am I out of my mind? Should I have resorted for a ASCII only version? Why? Wouldn't an ASCII only version of the above be harder to validate for equivalence with the formulas?

Mind you, I understand some Unicode glyphs look very much like each other and some like     ▄ (or is that ▗▖ ) or ╦  just can't make any sense in written code. However, this is hardly the case for Maths or arrow glyphs.

Per request, the ASCII only version would be something along the lines of:

```<code>winner_sigma_new = ( winner_sigma ** 2 *
                    ( 1 -
                     ( winner_sigma ** 2 -
                       general_uncertainty ** 2
                     ) * Wwin(t,e)
                    ) + dynamics ** 2
                   )**.5
</code>```

...per each step of the algorithm.

答:
I posted the same kind of question on StackOverflow

I definitely think that it worth using unicode in heavy math-related problems, because it makes it possible to read the formula directly, which is impossible with plain ASCII.

Imagine a debugging session: of course you can always hand-write the formula the code is supposed to compute to see if its correct. But ninety percent of the time, you won't bother and the bug can stay hidden for a long, looong time. And no one is ever willing to look at this abstruse 7-line, plain ASCII formula.
Of course, using unicode isn't as good as a tex-rendered formula, but it is way better.

The alternative of using long descriptive names is not viable because in math, if the identifier is not short, the formula will look even more complicated (why do you think people, around the XVIII century, began to replace "plus" by "+" and "minus" by "-" ?).

Personnally, I would also use some subscripts and superscripts (I just copy-paste them from this page).
For instance: (had python allowed √ as an identifier)

```<code>√ = math.sqrt #function alias
c² = c**2
σʷ² = σʷ**2
γ² = γ**2
σ′ʷ = √(σʷ² * (1 - (σʷ²/c²)*Wʷⁱⁿ(t, e)) + γ²)
</code>```

Where I used superscripts because there is no subscript equivalent in unicode.
(Unfortunately, the unicode subscript character set is very limited. I hope that one day, subscripting in unicode will be considered as diacritics, i.e. a combination of one char for subscript, and another char for the subscripted letter)

One last thing, I think this conversation about using non-ASCII character is primarily biased, because many programmers never deal with "formula intensive mathematical notations". So they think that this question is not that important, because they never experienced a significant portion of code that would require the use of non-ASCII identifiers.
If you are one of them (and I was until recently), consider this: suppose that the letter "a" is not part of ASCII. Then you will have a pretty good idea of the problem of having none of greek letters, subscripts, superscripts when computing non-trivial math formulas.

Body:
I posted the same kind of question on StackOverflow

I definitely think that it worth using unicode in heavy math-related problems, because it makes it possible to read the formula directly, which is impossible with plain ASCII.

Imagine a debugging session: of course you can always hand-write the formula the code is supposed to compute to see if its correct. But ninety percent of the time, you won't bother and the bug can stay hidden for a long, looong time. And no one is ever willing to look at this abstruse 7-line, plain ASCII formula.
Of course, using unicode isn't as good as a tex-rendered formula, but it is way better.

The alternative of using long descriptive names is not viable because in math, if the identifier is not short, the formula will look even more complicated (why do you think people, around the XVIII century, began to replace "plus" by "+" and "minus" by "-" ?).

Personnally, I would also use some subscripts and superscripts (I just copy-paste them from this page).
For instance: (had python allowed √ as an identifier)

√ = math.sqrt #function alias
c² = c**2
σʷ² = σʷ**2
γ² = γ**2
σ′ʷ = √(σʷ² * (1 - (σʷ²/c²)*Wʷⁱⁿ(t, e)) + γ²)

Where I used superscripts because there is no subscript equivalent in unicode.
(Unfortunately, the unicode subscript character set is very limited. I hope that one day, subscripting in unicode will be considered as diacritics, i.e. a combination of one char for subscript, and another char for the subscripted letter)

One last thing, I think this conversation about using non-ASCII character is primarily biased, because many programmers never deal with "formula intensive mathematical notations". So they think that this question is not that important, because they never experienced a significant portion of code that would require the use of non-ASCII identifiers.
If you are one of them (and I was until recently), consider this: suppose that the letter "a" is not part of ASCII. Then you will have a pretty good idea of the problem of having none of greek letters, subscripts, superscripts when computing non-trivial math formulas.


问:
Does it make sense to have a separate init function?
I'm created an opaque type and I have two options for its management.

The first looks like this:

```<code>type_t *a = type_init();
int err;

err = type_do(a, "foo", "bar", FLAGBIT1|FLAGBIT2, NULL);
if (!err) {
    type_print_result(a);
    ...
}

type_free(a);
</code>```

The second is:

```<code>type_t *a;
int err;

err = type_do(&a, "foo", "bar", FLAGBIT1|FLAGBIT2, NULL);
if (!err) {
    type_print_result(a);
    ...
}

type_free(a);
</code>```

type_do is the function that calculates the results we could work on. As you may underastand in the second case the initialization happens within type_do, that's why I have to pass the address of a. It is absolutely necessary to call type_do before doing anything else with type_t. Is there any reason to have a separate init function?

答:
As a rule, I design the API so that the fewest possible things can go wrong. That means:

Only one init function so that there are no in-between states.

It must be safe to call the destruction function even if the init function fails, i.e. if (ptr == NULL) return; even if no other function has NULL checks or if NULL checks in other functions are fatal.

Ensure that the error can't be ignored, either by warn_unused_result (with appropriate -Werror settings) or make the error an argument (and return the result).

ContentLicense: CC BY-SA 3.0


问:
What is the extent of programming language localization dialects?
Apple's scripting language AppleScript was designed with localization in mind; allowing the language to be represented in multiple dialects resembling languages from around the world.
In this way, using lexing and parsing tables, programs could be written in a style similar to that of the developer's mothertongue (or otherwise).
Although English is the only supported dialect at the time, Apple originally implemented additional dialects in French and Japanese.
Furthermore, a 'professional' dialect resembling Java was considered.

The benefits of localization of this type was considered to be that programs written in a certain language may be translated to the dialect of another, in order to aid developers co-operating internationally.
However, the method was deemed too complex due to complex conjugation and other issues when implementing dialects of certain languages other than English.

I have not heard of any other programming language adhering to localization schemes such as this, and I'm interested to hear the history of programming language dialect localization.
The only similar implementation I've found is that of Microsoft Excel, which may - apparently - be authored using nouns and verbs of multiple languages depending on user region.

My question is: what other languages, if any, implement a similar paradigm for programming language internationalization?

For those of you interested, Cook authored a great article on the development of AppleScript in the third HOPL-conference on the history of programming languages.

答:
Localization and internationalization facilities exist for applications, often as library functions (e.g. Posix gettext).

In the 1960s and 1970s several programming languages appeared in France with French keywords, e.g. PAF and LSE.

However, it makes much less sense to localize the source code of programs and scripts (e.g. by changing keywords of programming languages like if to si in French....) because the meaning of a program is also conveyed by the identifier names and the comments.

Automatic and reliable (and faithful) translations of such names and comments is IMHO beyond the state of the art.

And I believe it would be simpler to have the machine program itself, i.e. synthetize its own code,  instead of translating programs to be humanly understandable by other cultures. Look at Artificial General Intelligence and e.g. J.Pitrat's blog.

In practice, developers of software to be worked on by some international team (e.g. free software projects) should agree on some human language (often some form of English) and on some coding conventions or coding styles.

Some language don't have keywords (e.g. APL or even PL/1 where the same name IF can have both a role of keyword and a role of identifier, so that IF IF=THEN THEN; is a valid but cryptic PL/1 statement), but they do have identifiers and developers do give meaningful names in identifiers for their own culture. Translating these automatically is not realistic.

Some very few publications mention using natural language processing techniques on comments and identifiers in static program analysis of source code. (I am interested in additional references)

BTW,  look into COBOL; I believe it was designed with the naive claim that source code would become readable by non-programmers.

Some French teachers did taught programming in C by defining macros like

```<code>// French equivalent of some C keywords
#define si if
#define sinon else
#define faire do
#define tantque while
#define pour for
</code>```

but this became out of fashion. Now most teachers in France on programming requires some basic fluency in English.

(I am interested if today, in Chinese or Arabic universities, some equivalent is done)

Body:
Localization and internationalization facilities exist for applications, often as library functions (e.g. Posix gettext).

In the 1960s and 1970s several programming languages appeared in France with French keywords, e.g. PAF and LSE.

However, it makes much less sense to localize the source code of programs and scripts (e.g. by changing keywords of programming languages like if to si in French....) because the meaning of a program is also conveyed by the identifier names and the comments.

Automatic and reliable (and faithful) translations of such names and comments is IMHO beyond the state of the art.

And I believe it would be simpler to have the machine program itself, i.e. synthetize its own code,  instead of translating programs to be humanly understandable by other cultures. Look at Artificial General Intelligence and e.g. J.Pitrat's blog.

In practice, developers of software to be worked on by some international team (e.g. free software projects) should agree on some human language (often some form of English) and on some coding conventions or coding styles.

Some language don't have keywords (e.g. APL or even PL/1 where the same name IF can have both a role of keyword and a role of identifier, so that IF IF=THEN THEN; is a valid but cryptic PL/1 statement), but they do have identifiers and developers do give meaningful names in identifiers for their own culture. Translating these automatically is not realistic.

Some very few publications mention using natural language processing techniques on comments and identifiers in static program analysis of source code. (I am interested in additional references)

BTW,  look into COBOL; I believe it was designed with the naive claim that source code would become readable by non-programmers.

Some French teachers did taught programming in C by defining macros like

// French equivalent of some C keywords
#define si if
#define sinon else
#define faire do
#define tantque while
#define pour for

but this became out of fashion. Now most teachers in France on programming requires some basic fluency in English.

(I am interested if today, in Chinese or Arabic universities, some equivalent is done)


问:
how to upgrade software
I am a beginner in computer programming with C/C++.  I have previous experience in programming for the web.  There is some confusion that I am having with the software development process in desktop applications.

Web applications are easy to upgrade because it is basically a bunch of source files, but I have a question about desktop applications.  The major thing I notice about desktop applications is that they are released in different versions.  This requires the user to go through the uninstall/re-install process in order to obtain a newer version of the software.

In C/C++ software for various platforms, how would a programmer implement an "upgrade" option that would allow a user to update an already installed application without having to go back to a website.  How hard is it to upgrade an executable file on platforms like Windows and Linux.  I understand that the process may be different for different platforms.

Say, for example, I have a desktop application (version 1) that the user has already downloaded and installed onto their own PC.  After a while, I make some changes to the software and make improvements that the user would want applied to their software.  The user has made customizations to the software, but would like to upgrade to version 2 without having to re-customize their application all over again.  Originally, I thought that an "upgrade" feature would replace certain parts of an executable file, but is that really what you would have to do?

My main question is:  How exactly would someone go about accomplishing this "upgrade" process?  Is it possible?

答:
You are probably using customized in a wrong way. The desktop application (coded in C++, and distributed as a packaged binary executable) has not been customized, but user configured.

Customizing a desktop application means that some developer (internal to -or subcontractor of- the company where that application is used) has gotten, studied, and improved the desktop application's source code. This is uncommon and very costly.

You should ensure that the user configuration (e.g. preferences) are compatible from one version to the next (perhaps by having a functionality to transform that configuration).

Some (rare) applications indeed can be "customized" thru plugins (on Linux the application would dlopen(3) some shared object at runtime, during startup). If your application can have plugins, the plugins need to be written by a professional programmer (not by the random user), and you should have carefully designed and documented a good plugin interface. If you change that interface old plugins won't work with newer versions of your software.

Other applications embed a scripting language interpreter (like e.g. Lua or Guile). This is a very strong design decision and you should decide that before even starting coding your application.

Upgrading a software while it is still running is a research subject (and is never done for desktop applications). Read about persistence, continuation, calll stack, software package...

Notably on Linux, study the source code of some free software applications. It will teach you a lot.

Title: how to upgrade software


问:
c++ coding practice class vs. "free" functions
I am currently writing my first bigger project in c++. Its basic linear algebra. I am aware that boost libraries and others exist, but for various reasons I need to write my own. Purpose of the library is to perform certain vector operations (adding, substraction, etc. ...) for statistical data analysation. So ease of use of the functions has to be taken into consideration.

I started to write a class:

```<code>typedef std::vector<double> vec;
typedef std::vector<std::vector<double> > mat;

class Vector{
public:
    Vector(){}
    Vector(vec){}
    ~Vector(){}

    //functions to act on the vectors
    vec add(double){...}
    //many more...

private:
    vec v
};
</code>```

I soon realised that for simple vector arithmetic the class had some inconveniences: the missing assignment operators came to haunt me rather quickly.

Since I do not have long term coding experiences I want to know whether a "simple" file that contains all the necessary functions like:

```<code> from Vector.h:

 typedef std::vector<double> vec;
 typedef std::vector<std::vector<double> > mat;

 vec add(vec v, double d){...};
 ...
</code>```

is a proper solution for this kind of problem or if it is preferable to consider the class solution?

答:
When you want to represent distinct concepts, you should create separate types. Yes, this may come with some boilerplate for operator overloading, but having distinct types may offer significant advantages down the line.

std::vector is a generic dynamic array, not a mathematical vector (despite borrowing its name). So yes, you should create a separate type.

Whether the operations you want are then implemented as members or as free functions is a separate design decision. I recommend reading Effective C++.


答:
My question is: what other languages, if any, implement a similar paradigm for programming language internationalization?

Fortunately, as far as I know, there are none. I fervently hope it stays that way.

Localisation of anything important in a language or an API or any of the various defined symbols and strings that programs depend on, every time I've run across it, is an unmitigated disaster. We recently ran across the situation where software could not be installed on a Spanish version of Windows because the system-defined group usually called "Everyone" is called "Todos" in Spanish. We routinely have problems with simple things like date formats in the USA and the decimal separator in Germany. These are problems no-one needs to have embedded in their source code.

Lest it be said that I am seeking unfair advantages for English, in practice I think the opposite is true. Developers in languages other than English can typically use a wide range of defined names drawn from their own language with no fear of confusion with the reserved words and API symbols provided by the system environment. I see this as a plus.

Title: What is the extent of programming language localization dialects?

Body:
Apple's scripting language AppleScript was designed with localization in mind; allowing the language to be represented in multiple dialects resembling languages from around the world.
In this way, using lexing and parsing tables, programs could be written in a style similar to that of the developer's mothertongue (or otherwise).
Although English is the only supported dialect at the time, Apple originally implemented additional dialects in French and Japanese.
Furthermore, a 'professional' dialect resembling Java was considered.

The benefits of localization of this type was considered to be that programs written in a certain language may be translated to the dialect of another, in order to aid developers co-operating internationally.
However, the method was deemed too complex due to complex conjugation and other issues when implementing dialects of certain languages other than English.

I have not heard of any other programming language adhering to localization schemes such as this, and I'm interested to hear the history of programming language dialect localization.
The only similar implementation I've found is that of Microsoft Excel, which may - apparently - be authored using nouns and verbs of multiple languages depending on user region.

My question is: what other languages, if any, implement a similar paradigm for programming language internationalization?

For those of you interested, Cook authored a great article on the development of AppleScript in the third HOPL-conference on the history of programming languages.


答:
I prefer to view this situation as one requiring a Factory. The convention for a factory is that it always returns a valid object, or perhaps raises an exception if it really cannot. The code then looks like this.

```<code>type_t a = type_factory("foo", "bar", FLAGBIT1|FLAGBIT2, NULL);
if (!a.valid) {
    type_print_result(a);
    ...
}
type_free(a);
</code>```

or

```<code>if (!type_is_ok(a)) { ... }
</code>```

This idiom works better in OO languages, but is perfectly usable here too.

@glampert makes the excellent point that a factory guarantees a safe default in case there is a reason a new object cannot be created. It also makes it easier to mock the object for testing purposes.

Title: Does it make sense to have a separate init function?

Body:
I'm created an opaque type and I have two options for its management.

The first looks like this:

```<code>type_t *a = type_init();
int err;

err = type_do(a, "foo", "bar", FLAGBIT1|FLAGBIT2, NULL);
if (!err) {
    type_print_result(a);
    ...
}

type_free(a);
</code>```

The second is:

```<code>type_t *a;
int err;

err = type_do(&a, "foo", "bar", FLAGBIT1|FLAGBIT2, NULL);
if (!err) {
    type_print_result(a);
    ...
}

type_free(a);
</code>```

type_do is the function that calculates the results we could work on. As you may underastand in the second case the initialization happens within type_do, that's why I have to pass the address of a. It is absolutely necessary to call type_do before doing anything else with type_t. Is there any reason to have a separate init function?

Body:
I prefer to view this situation as one requiring a Factory. The convention for a factory is that it always returns a valid object, or perhaps raises an exception if it really cannot. The code then looks like this.

type_t a = type_factory("foo", "bar", FLAGBIT1|FLAGBIT2, NULL);
if (!a.valid) {
    type_print_result(a);
    ...
}
type_free(a);

or

if (!type_is_ok(a)) { ... }

This idiom works better in OO languages, but is perfectly usable here too.

@glampert makes the excellent point that a factory guarantees a safe default in case there is a reason a new object cannot be created. It also makes it easier to mock the object for testing purposes.


问:
How are the tiles in WORDAMENT organized?
I'm trying to create a word game, just like WORDAMENT, in my spare time. In order to present a new round, I need to create a board with 16 letters organized in a 4*4 grid. Currently, I'm generating the grid randomly. But it has some obvious problems. So my main purpose is to organize those 16 letters in such a way that maximum number of words can be formed out of connected tiles. How shall the letters be organized ?  I think this comes down to the probability of occurrence of letters in the English language. How can I use the letter frequency table, to organize my tiles? Any relevant pointers/suggestions/articles are appreciated. Thanks.</p>

答:
There are two things you need to do: (1) start with plausible heuristics (2) test the generated grid.

Some plausible heuristics would include (for example):

Match frequency of letters in English: ETAOIN SHRDLU etc etc. See here.

Maintain vowel balance (about 40%).

No more than 1 or 2 rare letters (ZJQX) and no Q without U.

Other heuristics related to the specific rules of the game, such as centre/edge or adjacencies.

Then test solve the grid. Write a program to count the words using a suitable dictionary (it's not that hard) and rate the grid according to the score you get: Novice, Regular, Expert, Impossible.

This kind of strategy applies to lots of games, not just this one.

Test solving also:
1. Lets you discard grids that are just too hard, or easy, or have too many or too few short or long words.
1. Lets players choose according to the level of difficulty they prefer.
1. Could allow you to tweak a grid by moving or swapping letters to achieve a result.

None of these things can be achieved by heuristics.


问:
Should this interpretation happen in the Controller or the Model?
Imagine an application where the user is allowed to create his/her own musical scales. The user selects notes from a list, arranges them to a group and presses a button to create the scale.

In an MVC structure, upon pressing the button, the View would tell the controller "the user wants to create a new scale, here are the names of the notes" (passing an array of strings).

These names need to be interpreted into the matching Note objects, before they are composed into a new Scale.

The question is, should this interpretation happen in the Controller, before passing a Notes array to the Model where the Scale creation will take place? Or should the Controller just pass the array of strings (representing the names of the notes) along to the Model, where the Model will interpret the names to Notes and compose the Notes to a Scale?

What would be more conceptually correct, according to the idea of MVC?

答:
Interpretations like the one from a string representing a note to a note object is the very reason for a controller, and therefore should be placed there.

The underlying idea behind the Model-View-Control pattern is to maintain a domain model free of system details. This separation of concerns allows the model to focus on the domain only and let surrounding components connect the model with the rest of the system.
The responsibility of the view is to translate the model into a visual representation, and the responsibility of the controller is to translate user (or system) input into the language of the domain.


问:
How to work with large aggregate roots?
I'm learning DDD and yet I have more questions than answers.

Let's consider a model of a directory containing enormous number of files.

Here is how I see it:

Directory is an Aggregate root.

This entity should have the validation logic of checking file name uniqueness when it is added or just renamed. And File entity contains the 'SetName' logic, notifying Directory via Domain Event about name changes.

But how should Directory then work?

It is not always possible to load all files into memory. Should in this case Files repository have adhoc logic for checking name uniqueness? I suppose it is a viable decision.

However, what if some files have been already added or renamed withing current not yet commited transaction? (nothing prohibits that. Transaction boundaries are set externally in relation to business logic). Probably repository should take into account both in-memory and persisted states (merging these states can be nontrivial task.)

So, when aggregate root with all its children fits in memory - everything is fine.
And as soon as you can not materialize all entities there are troubles.

I'd like to know what are the approaches for such situations.
May be there is no problem at all and it is just because of my misunderstanding of the subject.

答:
My answer is biased with Vaughn Vernon's Implementing Domain Driven Design great book (a must read)

1. Favor small aggregates.

If I'm to model your domain, I would model a Directory as an aggregate and File as another aggregate.

2. Reference aggregates by ids.

Therefore Directory will have a collection of FileId value objects.

3. Use factories to create aggregates.

For a simple case a factory method may be enough Directory.addFile(FileName fileName). However, for more complex cases I would use a domain factory.

The domain factory could validate that the fileName is unique using a FileRepository and a UniquefileNameValidator infrastructure service.

Why model File as a separate aggregate?

Because Directories aren't made of Files. a File is associated with a certain Directory. Also, think of a directory that has thousands of files. Loading all these objects into memory each time a directory is fetched is a performance killer.

Model your aggregates according to your use cases. If you know that there will never be more than 2-3 files in a directory then you can model them all as a single aggregate, but in my experience business rules change all the time and it pays if your model was flexible enough to accommodate the changes.

Obligatory read Effective Aggregate Design by Vaughn Vernon

Title: How to work with large aggregate roots?


问:
Domain model associations that do not required the behaviour of the associated object. How to model?
I've been struggling with this question for a while.

I'm specifically thinking within the object orientated domain model.

Let's say I have two entities. A supplier and a customer. There is a relationship that a supplier can have many customers, and a customer (in this case) can only have one supplier.

The issue I have is that neither object needs any behaviour of the other object i.e. the supplier object does not need to use any behaviour of the customer object and visa versa.

There is however still an association between them. The reason is that the problem domain requires that all a suppliers customers are destroyed if the supplier is destroyed. We also need to be able to retrieve a collection of all customers associated with a supplier.

How is this managed in the OO domain model? Who is responsible for the association?

Some may say that there should be a getCustomers() method on the supplier object and this is where the association lies. I don't really like this as it makes it difficult to close the supplier class (violation of Open Closed Principle). Every time we create a new type of class which has an association to a supplier, we have to add a get method to the supplier.

One thing I think could be used to model the association are repositories (from Eric Evens Domain Driven Design book). I guess it would be the Repository that then cares about this relationship? We could call selectCustomersFor(supplier_id) etc

Edit

The only reason I can see for having the association is for object retrieval criteria or object destruction (i.e. if user is destroyed, all customers will be destroyed). To me, it is not the responsibility of either object to retrieve or destroy itself. You could argue that the supplier should retrieve/destroy a customer, but this surely violates the Single Responsibility rule, and could also lead to Open Closed violation.

Why would we then bother to add the responsibility of association to an object thats doesn't use it? Its useless to the object. The association isn't useless though, I just feel something else should be responsible for it.

答:
Q:Why objects reference each other?

A:To make the model consistent and valid.

Let's try to model your domain. Supplier is an aggregate. Customer is an aggregate. Suppliers are created and managed in their bounded context. In this context I can create/update/delete/enable/disable suppliers.

Customers are managed in their bounded context. Any customer must be associated to a certain supplier. Why you ask? coz that's what the domain experts told us. So whenever a customer is created I'll pass it a supplierId value object.

But Suppliers and Customers don't need anything from each other?
Actually they do. Each of them need to be valid and consistent in the system. A Customer must be associated with a certain Supplier to be a valid customer.

When you need to delete a Supplier you will delete it in its bounded context then send a domain event to the Customer's bounded context with the supplier's id. You will retrieve all suppliers associated to that supplier and delete them.

Remember the one aggregate per transaction rule.

In case you modeled everything as a single bounded context then in your application service start transaction, fetch the supplier from its repository, delete it, fetch the associated customers from their repository, delete them then commit the transaction.

This might be quick and dirty, but it may suffice your needs.


问:
Why do some languages round to the nearest EVEN integer?
Programming languages like Scheme (R5RS) and Python (see this Question) round towards the nearest even integer when value is exactly between the surrounding integers.

What is the reasoning behind this?

Is there a mathematical idea that makes following calculations easier to reason about?

(R5RS references the IEEE floating point standard as source of this behaviour.)

答:
It's called banker's rounding.  The idea is to minimize the cumulative error from many rounding operations.

Lets say you always rounded .5 down.  Think of all those little interest payments, the bank pocketing half a cent each time...

Lets say you always rounded .5 up.  Accounting is going to scream because you're paying out more interest than you should.


答:
Given your description, the only reason I can see for a separate initialization function is to allow for the possibility that, sometime in the future, it will no longer be absolutely necessary to call type_do(type_t*, ...) before doing anything else with a type_t.

In any case, you should document that type_init() or type_do() returns an object that the caller should free by calling type_free() when it's no longer needed.


问:
Is it okay to use exceptions as tools to "catch" errors early?
I use exceptions to catch problems early. For example:

```<code>public int getAverageAge(Person p1, Person p2){
    if(p1 == null || p2 == null)
        throw new IllegalArgumentException("One or more of input persons is null").
    return (p1.getAge() + p2.getAge()) / 2;
}
</code>```

My program should never pass null in this function. I never intend it to. However as we all know, unintended stuff happens in programming.

Throwing an exception if this problem occurs, allows me to spot and fix it, before it causes more problems in other places in the program. The exception stops the program and tells me "bad stuff happened here, fix it". Instead of this null moving around the program causing problems elsewhere.

Now, you're right, in this case the null would simply cause a NullPointerException right away, so it might not be the best example.

But consider a method such as this one for example:

```<code>public void registerPerson(Person person){
    persons.add(person);
    notifyRegisterObservers(person); // sends the person object to all kinds of objects.
}
</code>```

In this case, a null as the parameter would be passed around the program, and might cause errors much later, which will be hard to trace back to their origin.

Changing the function like so:

```<code>public void registerPerson(Person person){
    if(person == null) throw new IllegalArgumentException("Input person is null.");
    persons.add(person);
    notifyRegisterObservers(person); // sends the person object to all kinds of objects.
}
</code>```

Allows me to spot the problem much before it causes weird errors in other places.

Also, a null reference as a parameter is only an example. It could be many kinds of problems, from invalid arguments to anything else. It's always better to spot them early.

So my question is simply: is this good practice? Is my use of exceptions as problem-preventing tools good? Is this a legitimate application of exceptions or is it problematic?

答: Yes, "fail early" is a very good principle, and this is simply one possible way of implementing it. And in methods that have to return a specific value, there isn't really very much else you can do to fail deliberately - it's either throwing exceptions, or triggering assertions. Exceptions are supposed to signal 'exceptional' conditions, and detecting a programming error certainly is exceptional.


答:
Not in the examples you give.

As you say, throwing explicitly isn't gaining you much when you're going to get an exception shortly thereafter. Many will argue that having the explicit exception with a good message is better, though I don't agree. In pre-released scenarios, the stack trace is good enough. In post-release scenarios, the call site often can provide better messages than inside the function.

The second form is providing too much info to the function. That function shouldn't necessarily know that the other functions will throw on null input. Even if they do throw on null input now, it becomes very troublesome to refactor should that stop being the case since the null check is spread throughout the code.

But in general, you should throw early once you determine that something has gone wrong (while respecting DRY). These though are maybe not great examples of that.

Title: Is it okay to use exceptions as tools to "catch" errors early?

Body:
I use exceptions to catch problems early. For example:

```<code>public int getAverageAge(Person p1, Person p2){
    if(p1 == null || p2 == null)
        throw new IllegalArgumentException("One or more of input persons is null").
    return (p1.getAge() + p2.getAge()) / 2;
}
</code>```

My program should never pass null in this function. I never intend it to. However as we all know, unintended stuff happens in programming.

Throwing an exception if this problem occurs, allows me to spot and fix it, before it causes more problems in other places in the program. The exception stops the program and tells me "bad stuff happened here, fix it". Instead of this null moving around the program causing problems elsewhere.

Now, you're right, in this case the null would simply cause a NullPointerException right away, so it might not be the best example.

But consider a method such as this one for example:

```<code>public void registerPerson(Person person){
    persons.add(person);
    notifyRegisterObservers(person); // sends the person object to all kinds of objects.
}
</code>```

In this case, a null as the parameter would be passed around the program, and might cause errors much later, which will be hard to trace back to their origin.

Changing the function like so:

```<code>public void registerPerson(Person person){
    if(person == null) throw new IllegalArgumentException("Input person is null.");
    persons.add(person);
    notifyRegisterObservers(person); // sends the person object to all kinds of objects.
}
</code>```

Allows me to spot the problem much before it causes weird errors in other places.

Also, a null reference as a parameter is only an example. It could be many kinds of problems, from invalid arguments to anything else. It's always better to spot them early.

So my question is simply: is this good practice? Is my use of exceptions as problem-preventing tools good? Is this a legitimate application of exceptions or is it problematic?


问:
When should you call yourself a senior developer?

Possible Duplicate:

  Whats the difference between Entry Level/Jr/Sr developers?

I'm curious what senior developer means because apparently the definition doesn't mean what I thought it would. I keep seeing these teens at 22-23 years old who call themselves senior X developer or senior Y developer. To me, a senior must have 10 years or so experience in programming to call himself 'senior'. I've seen a lot of these teens here (hence the question). Am I wrong? Why?

答:
Sometimes I look at other professions and wonder why software programming doesn't standardize itself. There would be no use for this question because there would be an accepted standard to obtaining certain levels. Then I come to the realization, "Who died and left them king?"

We all know that experience, education, certifications, and titles are for everyone else to get a very basic glimpse of a programmers ability. You either know what you're doing or you don't. You can either smell your own kind or you can't.

ContentLicense: CC BY-SA 2.5


答:
The concept behind std::vectoris not the one of a mathematical vector, but the one of a dynamically sizable array.

Adding arithmetic operation to it, makes those operation available to whatever code in your development may use std::vector to do other things than linear algebra operations.

For this reason, if you need a mathematical vector, you had better to define a new independent type.

Of course nothing can stop you from using std::vector inside it to hold values.

Whether if operations should be members or free function applied to that type ... it is more a matter of taste than anything: a.add(b) and add(a,b) have exactly the same semantic power.
I personally prefer the second, since it puts both a and b at the same level, or even operator+(a,b) (so that you can write a+b)

When implementing matrix, however, think a while before implementing them as vector of vectors for various reasons:

if vectors are implemented a "dynamically sizable" a vetor of vector will have all rows independently sizable and stored each other separately with all the structure (usually three pointers) to track them. For small matrices an vectors (like 4 components 3d-projective space) its more overhed than data.

A dynamic vector of dynamic vectors privileges the access by rows (or by columns) , but a matrix must be able to invert their role easily (thing to the Cij = Aik*Bkj matrix product)

Matricies are themselves "vector spaces" against + - and scalar * and /.

It is much better to think to matrices as independent types, implemented a s a plain vector, externally accessed with two indices, but whose basic operations are implemented in term of their inner vector.

I will probably come to something like this:

```<code>template<class T>
class vect
{
    std::vector<T> m;
public:
    explcit vect(size_t n) :m(n) {}
    size_t size() const { return n; }
    T& operator[] (size_t i) { return m(i); }
    const T& operator[] (size_t i) const { return m[i]; }
};

template<class T>
vect<T> operator+(const vect<T>& a, const vect<T>& b)
{
    vect<T> z(a.size());
    for(size_t i=0; i<a.size(); ++i)
        z[i] = a[i]+b[i];
    return z;
}

template<class T>
class matrix
{
    vect<T> m;
    size_t R;
public:
    matrix(size_t r, size_t c) :m(r*c), R(r) {}
    matrix(const vect<T>& s, size_t r) :m(s), R(r) {}

    const vect<T>& as_vect() const { return m; }
    size_t rows() const { return R; }
    size_t cols() const { return m.size()/R; }

    T& operator()(size_t r, size_t c) { return m[r*cols()+c]; }
    const T& operator()(size_t r, size_t c) const { return m[r*cols()+c]; }
};

template<class T>
matrix<T> operator+(const matrix<T>& a, const matrix<T>& b)
{ return matrix<T>(a.as_vect()+b.as_vect(),a.rows()); }
</code>```

The same can be done for both matrix and vect about operator-, and the unary + and -, as well as for operator*(vect<T>, T) and operator*(matrix<T>, T) (product by scalar) and the commutative counterparts operator*(T, vect<T>) and operator*(T, matrix<T>).

It has then to be implemented operator* int the matrix*matrix, matrix*vect, vect*matrix variants.

There are other more sophisticated techniques to avoid the repetition of loops and the local variables inside the functions (like constructing via lambdas, and the vector proxies forming template expressions to be use to get vector slices as matrix transposed views and so on... but may be go too far for what you are just doing)

Title: c++ coding practice class vs. "free" functions

Body:
I am currently writing my first bigger project in c++. Its basic linear algebra. I am aware that boost libraries and others exist, but for various reasons I need to write my own. Purpose of the library is to perform certain vector operations (adding, substraction, etc. ...) for statistical data analysation. So ease of use of the functions has to be taken into consideration.

I started to write a class:

```<code>typedef std::vector<double> vec;
typedef std::vector<std::vector<double> > mat;

class Vector{
public:
    Vector(){}
    Vector(vec){}
    ~Vector(){}

    //functions to act on the vectors
    vec add(double){...}
    //many more...

private:
    vec v
};
</code>```

I soon realised that for simple vector arithmetic the class had some inconveniences: the missing assignment operators came to haunt me rather quickly.

Since I do not have long term coding experiences I want to know whether a "simple" file that contains all the necessary functions like:

```<code> from Vector.h:

 typedef std::vector<double> vec;
 typedef std::vector<std::vector<double> > mat;

 vec add(vec v, double d){...};
 ...
</code>```

is a proper solution for this kind of problem or if it is preferable to consider the class solution?

Body:
The concept behind std::vectoris not the one of a mathematical vector, but the one of a dynamically sizable array.

Adding arithmetic operation to it, makes those operation available to whatever code in your development may use std::vector to do other things than linear algebra operations.

For this reason, if you need a mathematical vector, you had better to define a new independent type.

Of course nothing can stop you from using std::vector inside it to hold values.

Whether if operations should be members or free function applied to that type ... it is more a matter of taste than anything: a.add(b) and add(a,b) have exactly the same semantic power.
I personally prefer the second, since it puts both a and b at the same level, or even operator+(a,b) (so that you can write a+b)

When implementing matrix, however, think a while before implementing them as vector of vectors for various reasons:

if vectors are implemented a "dynamically sizable" a vetor of vector will have all rows independently sizable and stored each other separately with all the structure (usually three pointers) to track them. For small matrices an vectors (like 4 components 3d-projective space) its more overhed than data.

A dynamic vector of dynamic vectors privileges the access by rows (or by columns) , but a matrix must be able to invert their role easily (thing to the Cij = Aik*Bkj matrix product)

Matricies are themselves "vector spaces" against + - and scalar * and /.

It is much better to think to matrices as independent types, implemented a s a plain vector, externally accessed with two indices, but whose basic operations are implemented in term of their inner vector.

I will probably come to something like this:

template<class T>
class vect
{
    std::vector<T> m;
public:
    explcit vect(size_t n) :m(n) {}
    size_t size() const { return n; }
    T& operator[] (size_t i) { return m(i); }
    const T& operator[] (size_t i) const { return m[i]; }
};

template<class T>
vect<T> operator+(const vect<T>& a, const vect<T>& b)
{
    vect<T> z(a.size());
    for(size_t i=0; i<a.size(); ++i)
        z[i] = a[i]+b[i];
    return z;
}

template<class T>
class matrix
{
    vect<T> m;
    size_t R;
public:
    matrix(size_t r, size_t c) :m(r*c), R(r) {}
    matrix(const vect<T>& s, size_t r) :m(s), R(r) {}

    const vect<T>& as_vect() const { return m; }
    size_t rows() const { return R; }
    size_t cols() const { return m.size()/R; }

    T& operator()(size_t r, size_t c) { return m[r*cols()+c]; }
    const T& operator()(size_t r, size_t c) const { return m[r*cols()+c]; }
};

template<class T>
matrix<T> operator+(const matrix<T>& a, const matrix<T>& b)
{ return matrix<T>(a.as_vect()+b.as_vect(),a.rows()); }

The same can be done for both matrix and vect about operator-, and the unary + and -, as well as for operator*(vect<T>, T) and operator*(matrix<T>, T) (product by scalar) and the commutative counterparts operator*(T, vect<T>) and operator*(T, matrix<T>).

It has then to be implemented operator* int the matrix*matrix, matrix*vect, vect*matrix variants.

There are other more sophisticated techniques to avoid the repetition of loops and the local variables inside the functions (like constructing via lambdas, and the vector proxies forming template expressions to be use to get vector slices as matrix transposed views and so on... but may be go too far for what you are just doing)


答:
As far as I know different programmers prefer one solution or the other.

The first solution is usually preferred because it is more concise, in particular, you do not have to check the same condition again and again in different functions.

I find the second solution, e.g.

```<code>public void registerPerson(Person person){
    if(person == null) throw new IllegalArgumentException("Input person is null.");
    persons.add(person);
    notifyRegisterObservers(person); // sends the person object to all kinds of objects.
}
</code>```

more solid, because

It catches the error as soon as possible, i.e. when registerPerson() is called, not when a null pointer exception is thrown somewhere down the call stack. Debugging becomes much easier: we all know how far an invalid value can travel through the code before it manifests itself as a bug.

It decreases coupling between functions: registerPerson() does not make any assumptions about which other functions will end up using the person argument and how they will use it: the decision that null is an error is taken and implemented locally.

So, especially if the code is rather complex, I tend to prefer this second approach.

Body:
As far as I know different programmers prefer one solution or the other.

The first solution is usually preferred because it is more concise, in particular, you do not have to check the same condition again and again in different functions.

I find the second solution, e.g.

public void registerPerson(Person person){
    if(person == null) throw new IllegalArgumentException("Input person is null.");
    persons.add(person);
    notifyRegisterObservers(person); // sends the person object to all kinds of objects.
}

more solid, because

It catches the error as soon as possible, i.e. when registerPerson() is called, not when a null pointer exception is thrown somewhere down the call stack. Debugging becomes much easier: we all know how far an invalid value can travel through the code before it manifests itself as a bug.

It decreases coupling between functions: registerPerson() does not make any assumptions about which other functions will end up using the person argument and how they will use it: the decision that null is an error is taken and implemented locally.

So, especially if the code is rather complex, I tend to prefer this second approach.


答:
In your example function, I would prefer you did no checks and just allow the NullReferenceException to happen.

For one, it makes no sense to be passing a null there anyway, so I'll figure out the problem immediately based on the throwing of a NullReferenceException.

Two, is that if every function is throwing slightly different exceptions based on what kind of obviously wrong inputs have been provided, then pretty soon you've got functions that might throw 18 different types of exceptions, and pretty soon you find yourself saying that's too much work to deal with, and just suppressing all exceptions anyway.

There's nothing you can really do to help the situation of a design-time error in your function, so just let the failure happen without changing it.


问:
How to split a Service class in two but still use them like one?
I've got a class:

AuthenticationService

findLoggedInUser()

Checks session if User is logged in. If not, check client persistent user login cookie and log in.

loginUser($email, $pw, $remember = false)

Log User in, and if $remember is true create persistent login cookie for User and a record for it in the database.

logoutUser()

Removes User from the session, and any User persistent login cookie from the client and corresponding record in the database.

And I figured that I should separate this class into two different classes; one that handles the session part and one for the cookie part. So I would pretty much end up with two classes with more or less the same methods, but taking care of a different responsibility.

What would be the best way to combine those together, as if I would have a single AuthenticationService class?

答:
Think about the level of abstraction.

A developer who uses AuthenticationService class doesn't care if, under the hood, the class is using cookies, session, database or some magical parameters within an URI. It makes sense to have both findLoggedInUser() and loginUser() in the same class.

The class itself, on the other hand, relies on a lower abstraction: it may know whether it should use cookies or session, but doesn't care about the actual underlying mechanism (such as how sessions are handled: all that matters is to be able to get and set session variables).

This means that you can keep AuthenticationService and create two additional classes:

classAuthenticationCookieHandler

void CreateCookie(User user)

UserId FindUser()

classSession

bool IsAuthenticated()

User FindCurrentUser()

void AssignUser(User user)

void Reset()


问:
Is it possible to create an arch that allows for an app to be downloaded and installed at the same time?
In theory, if I wanted to have a developer write some sort of computer architecture/OS, could I have him/her add the capability to download + install something at the same time. I'm thinking like something where the file is shredded into pieces, and as parts are being downloaded (the user'd see it as one file), other parts are being installed.

Any ideas? This question is coming from a non-developer, so please be lenient.

答:
Yes, you could have software deployed in a model where "download" and "install" are synonyms.  This is all possible because one of the most important things for a non-programmer to realize about software.

A file is a file is a file.

From a system standpoint, there is no real difference between "SinghApp.exe" and "SinghApp.docx".  One has an extension that says it can be ran as a program, while other has an extension that says it can be opened as a Microsoft Word Document... but that's just a name, and the OS itself doesn't care one wit about the contents of either file.

When you distribute software as an installer, you're really distributing a small program written to place certain files in certain locations on the file system, along with performing some small system calls for file association and other tasks.  For programs that depend on the internet to function, it's not uncommon for the "installer" to download most of its bulk during the installation process.

It's not too hard to come up with examples -- MMORPG's do this as a matter of course, and I've seen similar behavior in web browsers from Mozilla or Google and the last Java installer I bothered with.  Even Microsoft got into the game; the new subscription version of office actually had new system calls written for its distribution, which is why you can't use Office 365 on Vista.

Of course, just because you can do something doesn't mean that you should.

If you're talking about an internal application to be used by your employees on systems you control, this soft of thing can make administration modestly easier.

Conversely, if you're thinking of doing this for software you'll release into the wild, a stub installer should be clearly labeled as such, and a separate download would be appropriate.  Not every user is going to want you knowing each computer they install the software on, and others won't like the thought of being dependent on your servers for their internal installation process.


问:
Database Handler and SQL injection prevention
I've written a database model class in PHP and have written a controller class that specifically validates the data before sending it to db. I'm getting criticism that I should handle the data in database model class rather than controller class.

I wanted to write a generic db class which can be used anywhere for CRUD operations. Now can you guys please help me out in sorting this out? Whether I should validate the data in db model class or in db controller class?

答:
Your database validations should happen in your model.  Assuming you are not using a framework you can write a generic wrapper class with your CRUD operations and protect against SQL injection etc. here.  Data validation can occur within your wrapper and more specific validation (e.g. like Rails like validates_presence_of) on data can occur in models that subclass your wrapper.  A pseudo example below should get you kicked off, however, note it is always much better to use a framework (even a micro-framework with ORM) for such tasks as most of this stuff is baked in so it is just a matter of learning the framework itself. </p>

```<code><?php
class DataWrapper
{
    function __construct()
    {
        // connect to database here
    }

    function create($object)
    {
        // do create stuff here
    }

    function read($object)
    {
        // do read stuff here
    }
    ...
}

class Car extends DataWrapper
{
    private $table = 'cars';

    // can do specific validation here
}
?>
</code>```

Body:
Your database validations should happen in your model.  Assuming you are not using a framework you can write a generic wrapper class with your CRUD operations and protect against SQL injection etc. here.  Data validation can occur within your wrapper and more specific validation (e.g. like Rails like validates_presence_of) on data can occur in models that subclass your wrapper.  A pseudo example below should get you kicked off, however, note it is always much better to use a framework (even a micro-framework with ORM) for such tasks as most of this stuff is baked in so it is just a matter of learning the framework itself.

<?php
class DataWrapper
{
    function __construct()
    {
        // connect to database here
    }

    function create($object)
    {
        // do create stuff here
    }

    function read($object)
    {
        // do read stuff here
    }
    ...
}

class Car extends DataWrapper
{
    private $table = 'cars';

    // can do specific validation here
}
?>


答:
Failing as soon as possible is great when debugging an application. I remember a particular segmentation fault in a legacy C++ program : the place where the bug was detected had nothing to do with the place where it was introduced (the null pointer was happily moved from one place to another in memory before it finally caused a problem). Stack traces cannot help you in those cases.

So yes, defensive programming is a really effective approach to detect and fix bugs quickly.
On the other hand, it can be overdone, especially with null references.

In your specific case, for example: if any of the reference is null, the NullReferenceException will be thrown at the next statement, when trying to get the age of one person. You don't really need to check things by yourself here: let the underlying system catch those errors and throw exceptions, that's why they exist.

For more realistic example, you can use assert statements, which :

Are shorter to write and read:

```<code>    assert p1 : "p1 is null";
    assert p2 : "p2 is null";
</code>```

Are specifically designed for your approach. In a world where you have both assertions and exceptions, you can distinguish them as follows:

Assertions are for programming errors ("/* this should never happen */"),

Exceptions are for corner cases (exceptional but probable situations)

Thus, exposing your assumptions about the inputs and/or state of your application with assertions let the next developper understand a little more the purpose of your code.

A static analyzer (e.g. the compiler) might be happier too.

Finally, assertions can be removed from the deployed application using a single switch. But generally speaking, don't expect to improve efficiency with that: assertions checks at runtime are negligible.

Body:
Failing as soon as possible is great when debugging an application. I remember a particular segmentation fault in a legacy C++ program : the place where the bug was detected had nothing to do with the place where it was introduced (the null pointer was happily moved from one place to another in memory before it finally caused a problem). Stack traces cannot help you in those cases.

So yes, defensive programming is a really effective approach to detect and fix bugs quickly.
On the other hand, it can be overdone, especially with null references.

In your specific case, for example: if any of the reference is null, the NullReferenceException will be thrown at the next statement, when trying to get the age of one person. You don't really need to check things by yourself here: let the underlying system catch those errors and throw exceptions, that's why they exist.

For more realistic example, you can use assert statements, which :

Are shorter to write and read:

    assert p1 : "p1 is null";
    assert p2 : "p2 is null";

Are specifically designed for your approach. In a world where you have both assertions and exceptions, you can distinguish them as follows:

Assertions are for programming errors ("/* this should never happen */"),

Exceptions are for corner cases (exceptional but probable situations)

Thus, exposing your assumptions about the inputs and/or state of your application with assertions let the next developper understand a little more the purpose of your code.

A static analyzer (e.g. the compiler) might be happier too.

Finally, assertions can be removed from the deployed application using a single switch. But generally speaking, don't expect to improve efficiency with that: assertions checks at runtime are negligible.


问:
How to design RESTful URI to get all unread messages?
I'm developing an ASP.NET MVC Web Api 2 with .NET Framework 4.5.1 and C#.

I have these entities in database:

Users, which are members of groups.

Groups.

Messages. Users can sent messages to a groups.

I have this route:

```<code>config.Routes.MapHttpRoute(
    name: "GroupMessagesApiRoute",
    routeTemplate: "api/groups/{groupId}/messages/{messageId}",
    defaults: new
    {
        controller = "GroupMessages",
        messageId = RouteParameter.Optional
    }
);
</code>```

With this route I can get all group's messages and one message, with {messageId}, sent to {goupId}.

But now I want to get all messages with an ID greater than {messageId}. How can I do that?

I've thought to create another route like this one:

```<code>config.Routes.MapHttpRoute(
    name: "GroupMessagesApiRoute",
    routeTemplate: "api/groups/{groupId}/messages/{messageId}/unread",
    defaults: new
    {
        controller = "GroupUnreadMessages"
    }
);
</code>```

I will need another controller, `GroupUnreadMessages, to get all unread messages. But I don't know if this is the better approach.

答:
For the greater than certain id query, probably clearest way is to use query strings. Something like

```<code>api/groups/{groupId}/messages?id=gt:50
</code>```

The "gt:50" is just an idea, it is easy to parse but it can be anything you like (there is no > symbol in query strings, it is key value so you need to add your own operators if you want complex queries.

Your "messages" resource should return a sub-set of messages if it gets a query string, where as without the query string you get back all messages.

For all unread messages you could add another query string such as

```<code>api/groups/{groupId}/messages?status=unread
</code>```

or you could make it part of the hierarchy.

```<code>api/groups/{groupId}/messages/unread
</code>```

Depends on what makes sense for your resource hierarchy.

Body:
For the greater than certain id query, probably clearest way is to use query strings. Something like

api/groups/{groupId}/messages?id=gt:50

The "gt:50" is just an idea, it is easy to parse but it can be anything you like (there is no > symbol in query strings, it is key value so you need to add your own operators if you want complex queries.

Your "messages" resource should return a sub-set of messages if it gets a query string, where as without the query string you get back all messages.

For all unread messages you could add another query string such as

api/groups/{groupId}/messages?status=unread

or you could make it part of the hierarchy.

api/groups/{groupId}/messages/unread

Depends on what makes sense for your resource hierarchy.


答:
A while ago I constructed a test program for successive rounding, because it's basically a worst-case stress test for a rounding algorithm.

For each number from 0 to 9,999 it first rounds to the nearest 10, then to the nearest 100, then to the nearest 1000. (You could also think of this as 10,000 points in [0,1) being rounded to 3 places, then to 2, then to 1.) This set of numbers has a mean value of 4999.5.

If all three roundings are done using the method "round half up", then the results are as follows (first column is the rounding result, second column is how many numbers rounded to that result — i.e. it's a histogram).

```<code>0     445
1000  1000
2000  1000
3000  1000
4000  1000
5000  1000
6000  1000
7000  1000
8000  1000
9000  1000
10000 555
</code>```

The result differs from a single "round half up" to the nearest thousand 550 times out of 10,000 and the average rounded value is 5055 (higher than the original average by 55.5).

If all three roundings are done by "round half down", then the results are:

```<code>0     556
1000  1000
2000  1000
3000  1000
4000  1000
5000  1000
6000  1000
7000  1000
8000  1000
9000  1000
10000 444
</code>```

The result differs from a single "round half down" to the nearest thousand 550 times out of 10,000 and the and the average rounded value is 4944 (too low by 55.5).

If all three roundings are done using "round half odd", the result is:

```<code>0     445
1000  1111
2000  889
3000  1111
4000  889
5000  1111
6000  889
7000  1111
8000  889
9000  1111
10000 444
</code>```

The result differs from a single "round half odd" to the nearest thousand 550 times out of 10,000 and the average rounded value is 4999.5 (correct).

Finally, if all three roundings are done using "round half even", the results are:

```<code>0     546
1000  909
2000  1091
3000  909
4000  1091
5000  909
6000  1091
7000  909
8000  1091
9000  909
10000 1091
</code>```

The result differs from a single "round half even" to the nearest thousand 450 times out of 10,000 and the average rounded value is 4999.5 (correct).

I think it's obvious that round half up and round half down bias the rounded values, so that the average of rounded values no longer has the same expectation as the average of the original values, and that "round half even" and "round half odd" remove the bias by treating 5 one way half the time and the other way the other half. Successive rounding multiplies the bias.

Round half even and round half odd introduce their own kind of bias to the distribution: a bias towards even and odd digits, respectively. In both cases, again, this bias is multiplied by successive rounding, but it's worse for round half odd. I think that the explanation in this case is simple: 5 is an odd number, so round half odd has more results ending in 5 than round half even — and therefore, more results that will have to be handled specially by the next rounding.

So anyway, of the four choices, only two are unbiased, and of the two unbiased choices, round half even gives the best-behaved distribution when subject to repeated rounding.

Title: Why do some languages round to the nearest EVEN integer?

Body:
Programming languages like Scheme (R5RS) and Python (see this Question) round towards the nearest even integer when value is exactly between the surrounding integers.

What is the reasoning behind this?

Is there a mathematical idea that makes following calculations easier to reason about?

(R5RS references the IEEE floating point standard as source of this behaviour.)

Body:
A while ago I constructed a test program for successive rounding, because it's basically a worst-case stress test for a rounding algorithm.

For each number from 0 to 9,999 it first rounds to the nearest 10, then to the nearest 100, then to the nearest 1000. (You could also think of this as 10,000 points in [0,1) being rounded to 3 places, then to 2, then to 1.) This set of numbers has a mean value of 4999.5.

If all three roundings are done using the method "round half up", then the results are as follows (first column is the rounding result, second column is how many numbers rounded to that result — i.e. it's a histogram).

0     445
1000  1000
2000  1000
3000  1000
4000  1000
5000  1000
6000  1000
7000  1000
8000  1000
9000  1000
10000 555

The result differs from a single "round half up" to the nearest thousand 550 times out of 10,000 and the average rounded value is 5055 (higher than the original average by 55.5).

If all three roundings are done by "round half down", then the results are:

0     556
1000  1000
2000  1000
3000  1000
4000  1000
5000  1000
6000  1000
7000  1000
8000  1000
9000  1000
10000 444

The result differs from a single "round half down" to the nearest thousand 550 times out of 10,000 and the and the average rounded value is 4944 (too low by 55.5).

If all three roundings are done using "round half odd", the result is:

0     445
1000  1111
2000  889
3000  1111
4000  889
5000  1111
6000  889
7000  1111
8000  889
9000  1111
10000 444

The result differs from a single "round half odd" to the nearest thousand 550 times out of 10,000 and the average rounded value is 4999.5 (correct).

Finally, if all three roundings are done using "round half even", the results are:

0     546
1000  909
2000  1091
3000  909
4000  1091
5000  909
6000  1091
7000  909
8000  1091
9000  909
10000 1091

The result differs from a single "round half even" to the nearest thousand 450 times out of 10,000 and the average rounded value is 4999.5 (correct).

I think it's obvious that round half up and round half down bias the rounded values, so that the average of rounded values no longer has the same expectation as the average of the original values, and that "round half even" and "round half odd" remove the bias by treating 5 one way half the time and the other way the other half. Successive rounding multiplies the bias.

Round half even and round half odd introduce their own kind of bias to the distribution: a bias towards even and odd digits, respectively. In both cases, again, this bias is multiplied by successive rounding, but it's worse for round half odd. I think that the explanation in this case is simple: 5 is an odd number, so round half odd has more results ending in 5 than round half even — and therefore, more results that will have to be handled specially by the next rounding.

So anyway, of the four choices, only two are unbiased, and of the two unbiased choices, round half even gives the best-behaved distribution when subject to repeated rounding.


问:
Do you use static keyword to declare single instance pattern?
I just come across this code and find it interesting to know whether you consider this as another single instance pattern?

```<code>public class Initiator
{
   private static String str;

   // there is many more private field here...

   private static String getMethod() { ... }

   // there is many more private getter here...

   static
   {
       // initialize all field here...
   }
}
</code>```

The programmer claim that by doing this I can ensure there is always one instance in the memory. Notice there is no setter method in the code as the programmer did the initialization work in static code block. And I never notice the static code block can be use in such a way.

答:
It's a valid usage, I tend to use the static block when the initialization may throw checked exceptions:</p>

```<code>private static final Cipher cipher;
static{
    try{
        cipher = Cipher.getInstance("AES");
        //initialization which may throw
    }catch(Exception e){
    throw new RuntimeException(e);//rethrow as unchecked if it fails -> will stop the program with visible stacktrace
    }
}
</code>```

Body:
It's a valid usage, I tend to use the static block when the initialization may throw checked exceptions:

private static final Cipher cipher;
static{
    try{
        cipher = Cipher.getInstance("AES");
        //initialization which may throw
    }catch(Exception e){
    throw new RuntimeException(e);//rethrow as unchecked if it fails -> will stop the program with visible stacktrace
    }
}


答:
In general, yes, it is a good idea to "fail early". However, in your specific example, the explicit IllegalArgumentException does not provide a significant improvement over a NullReferenceException - because both objects operated upon are delivered as arguments to the function already.

But lets look at a slightly different example.

```<code>class PersonCalculator {
    PersonCalculator(Person p) {
        if (p == null) throw new ArgumentNullException("p");
        _p = p;
    }

    void Calculate() {
        // Do something to p
    }
}
</code>```

If there was no argument checking in the constructor, you would get a NullReferenceException when calling Calculate.

But the broken piece of code was neither the Calculate function, nor the consumer of the Calculate function. The broken piece of code was the code that tries to construct the PersonCalculator with a null Person - so that is where we want the exception to occur.

If we remove that explicit argument check, you will have to figure out why a NullReferenceException occurred when the Calculate was called. And tracking down why the object was constructed with a null person can get tricky, especially if the code constructing the calculator is not close to the code that actually calls the Calculate function.

Body:
In general, yes, it is a good idea to "fail early". However, in your specific example, the explicit IllegalArgumentException does not provide a significant improvement over a NullReferenceException - because both objects operated upon are delivered as arguments to the function already.

But lets look at a slightly different example.

class PersonCalculator {
    PersonCalculator(Person p) {
        if (p == null) throw new ArgumentNullException("p");
        _p = p;
    }

    void Calculate() {
        // Do something to p
    }
}

If there was no argument checking in the constructor, you would get a NullReferenceException when calling Calculate.

But the broken piece of code was neither the Calculate function, nor the consumer of the Calculate function. The broken piece of code was the code that tries to construct the PersonCalculator with a null Person - so that is where we want the exception to occur.

If we remove that explicit argument check, you will have to figure out why a NullReferenceException occurred when the Calculate was called. And tracking down why the object was constructed with a null person can get tricky, especially if the code constructing the calculator is not close to the code that actually calls the Calculate function.


问:
How to mark code lines licensed on MIT?
When I am using some code licensed with the MIT license, but it's not in seperate files, is it OK mark it like this?

```<code>/* Here starts code licensed under the MIT License (../MIT.txt) */
// code
/* Here is the end of code licensed under the MIT License (../MIT.txt) */
</code>```

Where in ../MIT.txt file, it would contain the MIT License text and the original author's copyright notices.

Also, when most of code is MIT licensed and I'm only changing some sections of the functions can I mark those parts with the same method as above but with my own license? Yes, it's going to be a lot of kilobytes of comments.

答:
That's insane. DON'T DO THAT.

If you are working in some one else's code that has an MIT license, then your changes should have the MIT license. If you can't for some reason use the same license as the rest of the project, then you shouldn't be fooling with it. If you have an ethical or whatever disagreement with the licensing of a project, then DON'T WORK ON THAT PROJECT.

It is TOTALLY unreasonable for you to place a veritable copyright compliance minefield throughout each source file. It's NOT reasonable for you to expect users of the code to review every line of every source file in order to determine what the licensing of the thing is.

If you simply MUST do things differently, then pull your code out to separate files, so that someone evaluating the code for their use would have a CHANCE of knowing what license the code was under.

Also: If it came down to a courtroom, I'm unclear how your shenanigans would fare. An unobservant person could legitimately claim to have not noticed your bits being licensed differently, and an unscrupulous one could potentially use the confusion to do things you didn't intend.

Title: How to mark code lines licensed on MIT?


答:
If you wanted to do this (and you didn't care about the possible backlash) you should at the very least:

Add a license file, as you suggest.

Point out in the readme file very clearly that the code is licensed as "foo" (whatever the original license is) except where bracketed by "some special start string" and "some special end string" which is MIT licensed. These strings must be unique and never misspelled, so that users could conceivably remove them using a simple script if they don't want your code.

To avoid excessive backlash, you should probably also do this:

Provide the user with a link or script to get the code without your differently licensed changes.

Make sure the code works (or, at least, all tests pass) if your code is removed.

Put your code in separate files or wrap the original project (using for example a Git submodule) to guarantee that you're not modifying the original code.

The biggest issue with this is probably how your code would mesh with the rest of it. You can't modify even a single line of the original code and re-license it, so how are you going to do sane changes? For example, you can't statically link GPL code without changing your license to GPL. There are probably hosts of other issues with specific licenses, and you're very likely just creating problems for yourself and others. If you care about other users enough (assuming you're not selling the compiled project) to release your changes, why do you not care enough to use the original license?

A much simpler solution which has no guarantee of success is to calmly and reasonably explain to the original author(s) why you would like the software to use the MIT license, and whether they would be willing to dual license it.

Title: How to mark code lines licensed on MIT?

Body:
When I am using some code licensed with the MIT license, but it's not in seperate files, is it OK mark it like this?

```<code>/* Here starts code licensed under the MIT License (../MIT.txt) */
// code
/* Here is the end of code licensed under the MIT License (../MIT.txt) */
</code>```

Where in ../MIT.txt file, it would contain the MIT License text and the original author's copyright notices.

Also, when most of code is MIT licensed and I'm only changing some sections of the functions can I mark those parts with the same method as above but with my own license? Yes, it's going to be a lot of kilobytes of comments.


答:
When you use MIT-licensed code in a non-MIT-licensed project, simply marking the MIT-licensed parts of the source code is not a good strategy. The license allows you to do just about anything with the code – including sublicensing the code –, under this one restriction:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

Note that the MIT license should also be displayed to the end user of your software. Where you display your copyright to the user, you should also add something like

This program includes code from the FooBar library, used under the following license:

```<code>The "FooBar" library
Copyright (c) <year> <copyright holders>

<license body>
</code>```

In addition, you might want to explicitly mark the sections in the code that were taken from an MIT-licensed source. From my understanding, this is not required, but it would be ethical.

When you modify an MIT-licensed source, you should not mark your contributions with a separate license, because this requires an user of the source to follow both the original license and your license. Instead, choose one of the following options:

License your contributions under the same license as the rest of the code. You can edit the copyright notice to reflect that you contributed to the source, without marking what exactly you changed.

Re-license the MIT-licensed source under your license, in a manner permitted by the MIT license. See above.

Notes:

I'm a programmer, not a lawyer.

The term “MIT license” is fairly ambiguous. This answer assumes the Expat License, but is also applicable to the X11 License.

Title: How to mark code lines licensed on MIT?

Body:
When you use MIT-licensed code in a non-MIT-licensed project, simply marking the MIT-licensed parts of the source code is not a good strategy. The license allows you to do just about anything with the code – including sublicensing the code –, under this one restriction:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

Note that the MIT license should also be displayed to the end user of your software. Where you display your copyright to the user, you should also add something like

This program includes code from the FooBar library, used under the following license:

The "FooBar" library
Copyright (c) <year> <copyright holders>

<license body>

In addition, you might want to explicitly mark the sections in the code that were taken from an MIT-licensed source. From my understanding, this is not required, but it would be ethical.

When you modify an MIT-licensed source, you should not mark your contributions with a separate license, because this requires an user of the source to follow both the original license and your license. Instead, choose one of the following options:

License your contributions under the same license as the rest of the code. You can edit the copyright notice to reflect that you contributed to the source, without marking what exactly you changed.

Re-license the MIT-licensed source under your license, in a manner permitted by the MIT license. See above.

Notes:

I'm a programmer, not a lawyer.

The term “MIT license” is fairly ambiguous. This answer assumes the Expat License, but is also applicable to the X11 License.


问:
Looking for a certain datatype if it exists
I'm looking for the kind of a certain datatypes.

The main idea of this datatype is to describe a productionline containing several steps. Each step should be represented as a "vertex" containing an object of any type. Then for every "vertex" there are possible "subproductionlines" joining the line.

So it could look something like:

```<code>                  O   ->   O   ->   |                    #   subproductionline
                                    |                    #   joiningpoint
O   ->   O   ->   O   ->   O   ->   O   ->   O   ->   O  # main productionline
                                    |                    #   joiningpoint
         O   ->   O   ->   O   ->   |                    #   subproductionline
                           |                             #   joiningpoint
                  O   ->   |                             #subsubproductionline
</code>```

Does anyone of you know such a datatype?

If I were to code such a datatype... I see there two options of doing this:

A datatype as an Array (main productionline) containing Arrays (containing as first element the containing data of each vertex) and the rest of elements containing subproductionlines as recursive this datatype

or

A datatype as an Array containing the data stored in the vertex. Last element is either the element, where this subproductionline is joining, or a specific element representing the end of a main productionline, if it is one.

What do yout think is the better solution?

The programming language I think of using for is c / c++.

答:
Well, after long searching and going through my own studydocuments I ended up with LTS (labelled transition system) with two different transitions for example m(for main) and s(for sub)

so you have a set of nodes. and a set of transitions, which contain the information, if it is in the main production line or if it comes from a sub production line.


问:
Unit test database insert/remove and atomicity
I create my compact test database. This is a SDF file, embedded as a visual studio resource. When test suite starts this database is copied in %LOCALAPPDATA% so my test can use it.

The first method that I want to test is the getById method. Pretty simple.

```<code>var response = repo.GetById(IdToFind)
Assert.IsNotNull(response);
</code>```

Now suppose I want to test the Remove method. These are the steps that I figure out:

```<code>repo.Remove(objectToRemove)
var response = repo.GetById(objectToRemove.Id) // is this a right choice?
Assert.IsNull(response);
</code>```

this seems pretty clear to me, except for the GetById call. Does this step undermine test atomicity?

答:
Short answer - yes it does. If you test remove with something that involves getById and test getById with something that involves remove then both may fail simultaneously and you will not get any indication.

The straightforward solution is to just not use any other functions in the test. For example - by using plaintext queries - since you know your test DB structure and exactly what you expect. This will become a maintenance nightmare if you migrate DBs though.

Another is to have a set of basic methods that are tested using proper tests that don't invoke any other methods and just use an elaborate setup. It is then OK to use these tested methods in more complex tests of other functions. Usually these "basic" functions form a special class as well (and that's a plus, since anyone new to your environment will not know about this setup and testing mode for some but not other methods of a class).


问:
Business Logic vs Presentation/View Logic
I often question myself of where to put the logic that organize the data to a view that is not necessarily a business logic in a 3-layered architecture (DAO, Business, View).

I'll put an example to be clearer:

I have a UI in my aplication that shows pending tickets and answered tickets in two different tabs. To get the data from the database, I make a single query. Since there is no business logic, I'm returning the whole list to the Controller (View) and separating it in two lists to pass to the view template.

Should I be separating this in the business layer? Or is it correct to separate in the controller, since the logic is attached to that single UI?

答:
Consider T-SQL.  You can query a database using whatever where clauses make sense.

I see no reason that your database layer couldn't query based on criteria.  I would not construe simple filtering as mixing business logic and database logic.  If you gain a separation of concerns only to throw performance out the window, there's no win.


问:
Is there such a thing as API documentation management?
So I started thinking, what is the best practice for publishing generated documentation (e.g. Doxygen, NaturalDocs, etc.) in terms of infrastructure?

I would be generating it through continuous integration:

Should it be put in a regular web server?, or should I use something like Sharepoint or some other content publishing software?

Should the documentation be available for each build?, or just stable releases

Should I put a full copy of each documentation iteration?, or should I put  it in version control overwriting itself? (a repository separate to the project code, of course)

For some weird reason I find hard to think that I should just put it in a web enabled server, but this is how I see most do it:

http://docs.spring.io/spring/docs/

However, what happens when your company works on tenths if not hundreds of projects?, most documentation generation tools AFAIK just give you the final HTML output, but it is up to you to manage it.

So, what gives?, is there a better practice/solution than just putting it in the "doc server"?

答:
Another way to think of it is not as a "doc server", but that you're building a "Developer Portal" for your API consuming audience. This might include developers, but it could also include product managers, UI/UX folks, business analysts, etc.

Some things a Developer Portal might expose, beyond just raw documentation include:

Sample code

Sample apps

Wrappers / language-specific libraries

Tutorials

Support forums, ticketing, and other means of contacting the API producers

Stripe's /docs is an excellent example of exposing these kinds of resources along with the documentation: https://stripe.com/docs

Adding these things goes beyond just checking the box of providing docs, to doing the most you can to create a great experience for developers working with your APIs. Think of it as "usability", not in the UI sense, but it what it takes for someone to get up to speed and be successful with your APIs as a product.


问:
Does ODBC require any run-time software beyond an .exe file to run against MySQL and ORACLE SQL?
I'm writing a software [under Windows] in C++ which later needs to be able to connect to both MySQL and ORACLE SQL. Now the software needs to be as simple for the user as possible.

Now I'm considering using ODBC.

If I use ODBC, does the software later need any additional drivers, or only during development? When I have the .exe file, do I need any additional software to have it run on any computer or simply the executable?

答:
Most ODBC drivers do not rely on additional software to be installed. The ODBC driver installation adds all of the components it needs. Oracle, however, is different.

For Oracle, you will need the Oracle Client software to make the connection. You can find out more details on their page Oracle ODBC Driver. While the page doesn't explicitly state that you need the client software, the ODBC FAQ does mention that it needs SQL*Net application layer (which is a part of the Client software).

UPDATE

A friend reminded me that there are 3rd party Oracle drivers that do not require any Oracle code. The examples he gave me do cost money, whereas the drivers from Oracle do not. I'll put links to them in the comments.


问:
Data model for persisting queries to database
I have been asked to build what is essentially a query builder for a reporting application.

The variety of objects to query, potential modifiers, number of conditions, and so forth to be reported on have made me conclude that a query builder would be the best way to go about this task.

I am trying to decide the data model to back the storage of query parameters.

I have seen the models in this SO question as well as in this tutorial. But since it feels especially important to pick a good model up front, I would really appreciate any input.

EDIT: Here are some facts about the technology and requirements

I am working with C# and .NET Framework 4.5 (using ASP.NET MVC for presentation)

I am using Oracle Database 10g

I have Dapper and LinqToDB for Oracle available for data access

I would like to design a schema that can accommodate the following:

Allows for queries to be stored in terms of their constituent parts, where certain parts (like constraints/predicates) may be hard-coded as actual SQL or SQL snippets in the case of particularly complex logic that should be encapsulated

Allows for constraints to be formed in a "group", "constraint" format, where a query has a single root group, each group is equipped with AND/OR, constraints belong to groups, and groups can have subgroups

Minimizes need to explicitly define joins as part of query (so that they can be inferred by the subjects of constraints or minimally identified where necessary)

Can store the appropriate editor and source of editor values if appropriate for a given field

答:
The greatest complexity for query builders comes out of trying to handle the scope of ANDs an ORs.  If you can handle these elegantly, your model can be simpler.  I recommend having two sorts of predicates:

Your vanilla predicate: value1 operator value2.

Your compound predicated (or what we might call "implied parentheses").  The whole compound is tagged as using eitherAND or OR logic.  This reduces it to a simple list of predicates (unlimited in count) plus a single binary logic tag.

These two predicates offer a polymorphic interface (e.g. IEvaluate).  The first is evaluated normally and returns a boolean.  The latter is reduced (e.g. you fold over the list) also to a boolean.  This would be recursive since we might have nested compounds.

Using this model, at the highest level you will have either a single predicate or a single compound predicate.  Of course, the compound predicate may nest to any depth.  This is what your Knockout.js example already illustrates.

By doing away with the option of constructing a compound predicate that places any combination of ANDs and ORs between the various predicates, you simplify things quite a bit and lose nothing.  You are able to express whatever criteria is necessary.  This will entirely eliminate your concept of Lefts and Rights which I think is a good thing.


答:
If your database class is responsible for getting data into and out of your actual database, then it should take care of defending against SQL injection attacks or, if you're still building dynamic SQL, escaping character sequences that can be harmful (e.g. single quotes, line breaks (in some cases), etc.)

That way, everything outside of the database class can just with “pure” PHP types and doesn't have to worry about any of that.  The database class does the database class' job so that nothing else has to.

That said, it's an entirely different discussion as to whether or not the database class should be doing logical validation, say,

Is this a valid tire size for this particular car?

That's not a database issue; it's “business” logic and it really belongs elsewhere.

Title: Database Handler and SQL injection prevention

Body:
I've written a database model class in PHP and have written a controller class that specifically validates the data before sending it to db. I'm getting criticism that I should handle the data in database model class rather than controller class.

I wanted to write a generic db class which can be used anywhere for CRUD operations. Now can you guys please help me out in sorting this out? Whether I should validate the data in db model class or in db controller class?


答: In general, you can't test each method separately. At a minimum, each test will be testing both a constructor and the method you actually call. For methods that change the state, you are going to have to investigate the state afterwards. You can either have the test depend on implementation details by looking into the internal state of the object, or you can have your test depend on both pieces of functionality. Having your test depend on the details of internal state is much worse then testing too much functionality together.</p>

Title: Unit test database insert/remove and atomicity

Body:
I create my compact test database. This is a SDF file, embedded as a visual studio resource. When test suite starts this database is copied in %LOCALAPPDATA% so my test can use it.

The first method that I want to test is the getById method. Pretty simple.

```<code>var response = repo.GetById(IdToFind)
Assert.IsNotNull(response);
</code>```

Now suppose I want to test the Remove method. These are the steps that I figure out:

```<code>repo.Remove(objectToRemove)
var response = repo.GetById(objectToRemove.Id) // is this a right choice?
Assert.IsNull(response);
</code>```

this seems pretty clear to me, except for the GetById call. Does this step undermine test atomicity?