问:
Config files for database-level business rules
In my application, I have a lot of SQL queries that have business logic embedded in them. For example, in searches I 'hide' results that are low ranked, less than -5 'community rating' because those results contain spam, inaccuracies, etc and have been flagged by the community.

In my SQL query, it might look like:

```<code>SELECT
    ...
    ...
WHERE community_rating > -5
</code>```

Here, I'm embedding business logic right into the query. What if we change our minds later about the threshold for hiding results? I have 4 queries right now that use this magic number, and more might be coming.

My gut says to pull these numbers out into a 'database config file', because the numbers are reused a lot and can be changed, but I'm tempted to say no because it adds a lot of confusion as you add more $-type variables like:

```<code>SELECT
    ...
    ...
WHERE community_rating > $5
</code>```

And I would have an array of values to pass to the query like:

```<code>[..., ..., ..., ..., DB_CONFIG.HIDE_RESULTS_AT_RATING]
</code>```

I imagine that it would get even sloppier and hard to understand over time, but that's probably inexperience talking.

Should one pull database-level business logic out to a configuration file?

Edit: This is the backend to a web service. This isn't a parameter that a user who is doing a search can change. In all queries, results are excluded at this threshold, and the threshold is decided by me. There are multiple search functions, all of which use this threshold.

答:
Config files should almost be the last places to put business rules or parameters. Config files should in general used only for administrative functions - things that DB admin or IT admin would control - certainly not the business logic.

One of the key reasons why config files for business logic is bad is because typically business rules not only change in values but they evolve from simple to complex. They can grow from being a list of attributes to become a tree of policies and then a lot of procedural code will get added to process them in support scripts which becomes badly maintained.

Another aspect to remember is that when you take $5 - do you expect to change while the server is running? It does depend on your exact implementation, but how often do you want to keep loading and parsing config files? and if that policy value changes, how do you communicate that policy needs to be reloaded?

A much better place to keep parameters is DB itself! You can have one of the CONFIG_TABLE where each attribute (column in DB table) is one specific parameter. It can be simple one table or it can get nested with multiple tables. You can have different policy profiles - which are just different rows of this table.

If through some other interface of the application, the parameters can even be changed if required and the very next query that will fire will automatically incorporate it.


问:
How did JavaScript become popular?
In ancient history, Brendan Eich had a language design, and in today's world, JavaScript is a popular language implemented and used in many different places.

What caused the language to become popular? Was it the C-like syntax familiar to previous programmers? Did Netscape have enough control of the market to force it to be used? Or is there some deeper reason that JavaScript is popular and other languages are not?

Particularly, if you had to make a language as popular as JavaScript, what initial conditions would you need to recreate its growth in popularity?

答: Javascript is popular as a hack to overcome the shortcomings of HTML markup for making webpages appear like designers want them to appear. Without Javascript all webpages would look like this - HTTP 1.1. Barely a step-up from the gopher protocol.</p>

ContentLicense: CC BY-SA 2.5

Title: How did JavaScript become popular?


问:
How can I split a repository that contains many projects which share the same build system?
I've been working on the past years on a research compiler suite, which builds several executables and libraries. It has a build system (namely bootstrapper) that looks into the ./src/bin directory searching for tools to build, and on ./src/lib, ./src/rtl and ./src/std for libraries, managing the dependencies (only internal dependencies!). Works pretty much like a single makefile for multiple tools (like GCC does). Because of this, they share the same codebase. I've been using a single git repository so far.

Since most tools and libraries are self-contained, I'd like to split the repository into several modules, since most tools don't depend on each other (there are no cyclical dependencies at all, only a couple of hierarchical ones!).

For example, I'd have a core module with the very basic system, which would look something like this:

```<code>./README
./src/bootstrapper.krc
./src/bin/cpp.c
./src/bin/cc.c
./src/lib/cpp/...
./src/lib/cc/...
./src/lib/foo/...
./src/lib/bar/...
</code>```

Which contains the builder, and that is self-contained; it should generate cpp, cc, and the libcpp, libcc, libfoo and libbar libraries.

I'd like then to have, for example, a ruby module separated someway, that would look something like:

```<code>./src/bin/rbc.c
./src/lib/rbc/...
./src/std/ruby/...
</code>```

Which would build rbc, librbc and libstdruby... and then a python module like:

```<code>./src/bin/pyc.c
./src/lib/pyc/...
./src/std/python/...
</code>```

Which would build pyc, libpyc, and libstdpython.

Though both the ruby and python hypotetical modules would depend on the core module, they have no dependency at all on each other (and this is why I'm thinking about splitting my current repository).

Which way could I achieve this? I thought about using different git branches for each module (but I would require several hooks to automatically rebase everything based on their dependencies, like having multiple copies of the core module and keeping them up to date), multiple git repositories (same problem), and git submodules won't help because I'd need a per-file-basis because of the build system I have...

(Though I prefer git, because I'd like to publish it on GitHub, I don't mind switching to another SCM.)

All tools (bin/example) depend on the same ./include/bin/main.h (which would be part of the core module) that has a lot of macros... each folder on ./src/ actually has a corresponding ./include/ folder too (e.g., ./include/std/ruby/...).

Here's a pic of somewhat what I described above, as it is currently:

答:
The requirements

Following points are important to be considered when you are thinking of spliting the repository.

Each new split has it's own trunk now.
Each product cann't just be another branch in this case, because now each of these products will have their own versions (tags), their own dev branches and hence they all must have their own trunks respectively.

Maintain history
This is perhaps the most important thing when splitting the repo. We shouldn't loose history of things interacted in past. For example you can take the complete export out of the source and create four fresh repos. But that will all loose history. So each of the part of the product repo should have it's history when we now use it from it's independent repo.

Open working branches
If there are feature branches or support branches out there, and if we want to shut shops, we will have to wind up all and put it back to trunk. However, for any reasonably sized project this is hard to materialize. Rather, the branches with same history and snapshots should be available in the new repo so that work can resume where it got suspended not require to restart!

But the solution can be simple:

First step is to clone each repo with a different name. The procedure for each repo type is listed below. Basically with four clones now you have four repos, each having the same identical structure (trunk/tags/branches), identical history and identical set of branches.

Now, from the primary trunk you can simply delete all source codes which doesn't require in the corresponding repo. For example in one repo delete all ruby files and keep only C files. where as do the reverse in the other repo. So now you will have one repo with libary produced from C files and another which has ruby files.

Merge this change to all subordinate branches to reflect deletion from there as well.

Modify the common files such as Makefile etc. which will now have the same structure.

Optionally you might want to "move" files to re-organize the structure.

Tag the new release with new number series 2.0 (if it was 1.x before).

Following this, all your history will remain available to each of the 4 product repos. And hence, critically, you will be able to go back to the snapshot which worked togather.

Repo specific stuff

SVN For SVN this is extremely simple. Simply copy paste the main folder where the repo is hosted. The one that was generated with svnadmin --create command (not the working copy). See the SVN book Ch 5 for more details. Once you clone it, it has everything that other repo has.

Git repos are decentralize by default. So everytime you do git-clone there itself you are actually cloning the repos. However, in order to be identified with different products you have 2 other options. A. Forking and B. Mirroring. Refer to this page for duplicating without mirroring. One more reference is this SO question.  Forking is another option. Refer to this page for the basics. However forking is not exactly same as cloning/mirroring. I would prefer mirroring.

ContentLicense: CC BY-SA 3.0


问:
Is there a name for this pattern?
A while loop can be written as follows in C# (and many other languages):

```<code>int someValue;
int someTerminatingValue;

while ((someValue = GetSomeValue()) != someTerminatingValue)
{
    // Do something interesting
}
</code>```

Is there a name for this pattern of assigning the value inside the while loop's expression?

NB
I'm not asking if it is a good idea or a bad idea, just if there's a name for this pattern.  Whether it's good or bad, people will see it so they need to know what it is.  If there isn't a name for it then that's fine, I'm just asking if there is one.

答:
Idiom

At this scale, reoccurring motifs are called idioms rather than design patterns.  The design patterns work on a larger scale than just a single line of code or a single loop.

Clever code

This would also qualify as clever code anti-pattern.  Clever code is not advisable, because it will be harder to read for your teammates and for yourself 6 moths later.

Better alternatives

Loop initialization, loop "propulsion", loop exit conditions are separated.

    int someValue;
    int someTerminatingValue;

    for (someValue = GetSomeValue();         // initialize the loop variable
         someValue = GetSomeValue();         // move the loop onward
         someValue != someTerminatingValue)  // exit condition
    {
        // Do something interesting
    }
```

<p>But this is still <em>clever code</em>.  McConnell call this "<em>a <code>while</code> loop abusively crammed into a <code>for</code> loop header</em>" (see Code Complete 2, p.374).  he also proposes a better alternative.</p>

```    someValue = GetSomeValue();                 // initialize the loop variable
    while (someValue != someTerminatingValue)   // exit condition
    {
        // Do something interesting
        someValue = GetSomeValue();             // move the loop onward
    }
```

Related:

How to train yourself to avoid writing “clever” code?

My own distaste for clever code comes from the book Code Complete 2 by McConnell.

At this point, I'm legally obligated to turn your attention to the following illustration:

  (source)

Title: Is there a name for this pattern?

Body:
Idiom

At this scale, reoccurring motifs are called idioms rather than design patterns.  The design patterns work on a larger scale than just a single line of code or a single loop.

Clever code

This would also qualify as clever code anti-pattern.  Clever code is not advisable, because it will be harder to read for your teammates and for yourself 6 moths later.

Better alternatives

Loop initialization, loop "propulsion", loop exit conditions are separated.

    int someValue;
    int someTerminatingValue;

    for (someValue = GetSomeValue();         // initialize the loop variable
         someValue = GetSomeValue();         // move the loop onward
         someValue != someTerminatingValue)  // exit condition
    {
        // Do something interesting
    }

But this is still clever code.  McConnell call this "a while loop abusively crammed into a for loop header" (see Code Complete 2, p.374).  he also proposes a better alternative.

    someValue = GetSomeValue();                 // initialize the loop variable
    while (someValue != someTerminatingValue)   // exit condition
    {
        // Do something interesting
        someValue = GetSomeValue();             // move the loop onward
    }

Related:

How to train yourself to avoid writing “clever” code?

My own distaste for clever code comes from the book Code Complete 2 by McConnell.

At this point, I'm legally obligated to turn your attention to the following illustration:

  (source)


问:
Why can't I refer to an interface inside of generic brackets in a variable declaration?
I tried to write the following:

```<code>public class AdjacencyList<Vertex> {

    Map<Vertex, Set<Edge<Vertex>>> adj = new HashMap<Vertex, HashSet<Edge<Vertex>>>();
}
</code>```

But I get the error:

```<code>Type mismatch: cannot convert from HashMap<Vertex,HashSet<Edge<Vertex>>> to Map<Vertex,Set<Edge<Vertex>>>
</code>```

Eclipse wants me to change the line to:

```<code>Map<Vertex, HashSet<Edge<Vertex>>> adj = new HashMap<Vertex, HashSet<Edge<Vertex>>>();
</code>```

(Note it's specifying the type of Set on the left.

I'm trying to get into the habit of specifying interfaces instead of exact types. Why is it not letting me in this case?

答:
Make what you're instantiating concrete (HashMap), but keep the generic type abstract. Something like:

```<code>Map<Vertex, Set<Edge<Vertex>>> adj = new HashMap<Vertex, Set<Edge<Vertex>>>();

adj.put(new Vertex(), new HashSet<Edge<Vertex>>());
</code>```

Note that this will allow other types of Set to be used as values in the Map, which may or may not be what you intend. If you only want HashSets in the Map, then Eclipse's suggestion would be the way to go.

Body:
Make what you're instantiating concrete (HashMap), but keep the generic type abstract. Something like:

Map<Vertex, Set<Edge<Vertex>>> adj = new HashMap<Vertex, Set<Edge<Vertex>>>();

adj.put(new Vertex(), new HashSet<Edge<Vertex>>());

Note that this will allow other types of Set to be used as values in the Map, which may or may not be what you intend. If you only want HashSets in the Map, then Eclipse's suggestion would be the way to go.


答:
I believe that unless specifically specified, generics in Java are invariant, meaning that (to simplify), a List<string> does not inherit from List<Object>, even though String does inherit Object. Consider that a List<Object> has an add(Object o) method, which, if it was inherited by List<String>, be used to add non-Strings to the list and break the very type safety that generics are here to provide us. Similarly, a Map<Vertex,Set<...>> isn't the base class of a Map<Vertex, HashSet<...>>, even though Set is of HashSet.

Try reading this article on Covariance and Contravariance in Java, which explains this issue in general terms, and shows how to use Generic Bounds to extend the possible generic arguments of a type:

Unbounded wildcards allow assignment with any type parameter:

```<code>List<?> list = new ArrayList<Clazz>();
</code>```

Bounded wildcards affect assignment like you might expect:

```<code>List<? extends Clazz> list = new ArrayList<SubClazz>();
List<? super Clazz> list2 = new ArrayList<Object>();
</code>```

Title: Why can't I refer to an interface inside of generic brackets in a variable declaration?

Body:
I tried to write the following:

```<code>public class AdjacencyList<Vertex> {

    Map<Vertex, Set<Edge<Vertex>>> adj = new HashMap<Vertex, HashSet<Edge<Vertex>>>();
}
</code>```

But I get the error:

```<code>Type mismatch: cannot convert from HashMap<Vertex,HashSet<Edge<Vertex>>> to Map<Vertex,Set<Edge<Vertex>>>
</code>```

Eclipse wants me to change the line to:

```<code>Map<Vertex, HashSet<Edge<Vertex>>> adj = new HashMap<Vertex, HashSet<Edge<Vertex>>>();
</code>```

(Note it's specifying the type of Set on the left.

I'm trying to get into the habit of specifying interfaces instead of exact types. Why is it not letting me in this case?

Body:
I believe that unless specifically specified, generics in Java are invariant, meaning that (to simplify), a List<string> does not inherit from List<Object>, even though String does inherit Object. Consider that a List<Object> has an add(Object o) method, which, if it was inherited by List<String>, be used to add non-Strings to the list and break the very type safety that generics are here to provide us. Similarly, a Map<Vertex,Set<...>> isn't the base class of a Map<Vertex, HashSet<...>>, even though Set is of HashSet.

Try reading this article on Covariance and Contravariance in Java, which explains this issue in general terms, and shows how to use Generic Bounds to extend the possible generic arguments of a type:

Unbounded wildcards allow assignment with any type parameter:

List<?> list = new ArrayList<Clazz>();

Bounded wildcards affect assignment like you might expect:

List<? extends Clazz> list = new ArrayList<SubClazz>();
List<? super Clazz> list2 = new ArrayList<Object>();


问:
Modular programming practices
As I start to code more and more, for example in C++, I tend to also want to learn more about the accepted standards for code.

I'm trying to code a chess engine right now, but I'm unsure how to treat each 'module' of the program (which is separated into different files).

For example, it makes sense to make a class for bitboards as bitboard.h and bitboard.cpp, as this might be required later on. But, it doesn't make sense to have a class for the move generator, because I won't ever need more than one move generator.

But I still want to abide by the principle of least privilege, and not give users access to more functions than necessary. But, I'm not sure if you can do this without a class? I've looked at namespace but I'm not sure how it'd apply in this case.

How do professional programmers handle this sort of thing? I've looked at the source for the Stockfish open source chess engine, and it has both header files and cpp files, but the header files simply seem to have a whole bunch of variables.

答:
The Principle of Least Privilege is about security, not software engineering and should not be confused with Encapsulation.  They are two very different things.

The point of the Principle of Least Privilege is to give a user (or application) the bare minimum of permissions it needs.  So user A may get a different set of permissions than user B.  This is to make it hard for potentially malicious users to gain access to potentially dangerous features as it requires that they have explicit permission.

Encapsulation is about making it clear about what parts of your class are meant for external user and what parts are meant to be ignored by the caller.  The purpose here is not about malicious users, but rather, about making sure users don't accidentally write code that depends on things that may change in the future.  It also pushes class authors to create clear interfaces.

Inherent in the Principle of Least Privilege is that different users have different permissions.  There is no notion of that in all in Object Orient software.  All users of your classes have the same access.  Also implicit in the Principle of Least Privilege is that you are forcing users into a restricted subset.  By contrast, Encapsulation can be easily broken in many Object Oriented languages.  (In some, like Python, encapsulation is entirely handled with coding standards.)

If you try to design classes with an eye to restricting users to a minimum (as with the Principle of Least Privilege) you are likely going to end up with classes that are limited and hard to use.  Instead, you should look at it from the perspective of "what are the users going to want to do with this class".  The public interface is everything you can think of that users will want to do.  Then make everything else private.  That's Encapsulation.

In essence, when designing classes, you want to operate with an eye to giving users the most privilege you can safely give them.

Title: Modular programming practices


问:
Why the recent shift to removing/omitting semicolons from Javascript?
It seems to be fashionable recently to omit semicolons from Javascript. There was a blog post a few years ago emphasising that in Javascript, semicolons are optional and the gist of the post seemed to be that you shouldn't bother with them because they're unnecessary. The post, widely cited, doesn't give any compelling reasons not to use them, just that leaving them out has few side-effects.

Even GitHub has jumped on the no-semicolon bandwagon, requiring their omission in any internally-developed code, and a recent commit to the zepto.js project by its maintainer has removed all semicolons from the codebase. His chief justifications were:

it's a matter of preference for his team;

less typing

Are there other good reasons to leave them out?

Frankly I can see no reason to omit them, and certainly no reason to go back over code to erase them. It also goes against (years of) recommended practice, which I don't really buy the "cargo cult" argument for. So, why all the recent semicolon-hate? Is there a shortage looming? Or is this just the latest Javascript fad?

答:
There’s no such thing as information overload, only bad design.

— Edward Tufte

It's a general rule in graphic design to leave out unnecessary elements and ornamentation to reduce noise.

Fewer visual elements on the screen means less work for our brains to parse the actual useful information.

```<code>let foo = 1
</code>```

vs.

```<code>let /* variable */ foo = 1; // EOL
</code>```

An exaggerated example of course, but it illustrates the general principle: Additional visual elements should be added if and only if they serve a purpose. So, do semicolons serve a purpose?

The historical reasons to use semicolons in JavaScript were:

Maintain similarity to C / Java

Avoid compatibility issues with poorly written browsers and tools

Helping humans and machines detect code errors

Automatic Semicolon Insertion carries a performance penalty

The compatibility issues are pretty much a non-issue today. Modern linters can detect any code errors just as well without semicolons. Similarity with C/Java/PHP can still be a consideration (see the accepted answer by Pat), but just because other languages contain superfluous syntax elements does not mean we should keep them in JavaScript, especially since many other languages (Coffeescript, Python, Ruby, Scala, Lua) do not require them.

I did a quick test to see if there was a performance penalty in V8. This is Io.js parsing a 41 MB JavaScript file (Lodash repeated 100 times) with semicolons and then with semicolons removed:

```<code>$ time node lodashx100.js
node lodashx100.js  2.34s user 1.30s system 99% cpu 3.664 total
$ time node lodashx100s.js
node lodashx100s.js  2.34s user 1.15s system 99% cpu 3.521 total
</code>```

Everyone has to decide their own preferred coding style for their projects, but I no longer see any tangible benefit in using semicolons, so to reduce visual noise, I've stopped.

Body:
There’s no such thing as information overload, only bad design.

— Edward Tufte

It's a general rule in graphic design to leave out unnecessary elements and ornamentation to reduce noise.

Fewer visual elements on the screen means less work for our brains to parse the actual useful information.

let foo = 1

vs.

let /* variable */ foo = 1; // EOL

An exaggerated example of course, but it illustrates the general principle: Additional visual elements should be added if and only if they serve a purpose. So, do semicolons serve a purpose?

The historical reasons to use semicolons in JavaScript were:

Maintain similarity to C / Java

Avoid compatibility issues with poorly written browsers and tools

Helping humans and machines detect code errors

Automatic Semicolon Insertion carries a performance penalty

The compatibility issues are pretty much a non-issue today. Modern linters can detect any code errors just as well without semicolons. Similarity with C/Java/PHP can still be a consideration (see the accepted answer by Pat), but just because other languages contain superfluous syntax elements does not mean we should keep them in JavaScript, especially since many other languages (Coffeescript, Python, Ruby, Scala, Lua) do not require them.

I did a quick test to see if there was a performance penalty in V8. This is Io.js parsing a 41 MB JavaScript file (Lodash repeated 100 times) with semicolons and then with semicolons removed:

$ time node lodashx100.js
node lodashx100.js  2.34s user 1.30s system 99% cpu 3.664 total
$ time node lodashx100s.js
node lodashx100s.js  2.34s user 1.15s system 99% cpu 3.521 total

Everyone has to decide their own preferred coding style for their projects, but I no longer see any tangible benefit in using semicolons, so to reduce visual noise, I've stopped.


问:
What false ideas are there that puts people off using threads?
Implementing threading in a program is hard, yes, however why is it that some people will not implement them even when there is an obvious need for it.

An example: Program has to load a dataset from a database, the thing to do would be to make the connection and get the data from the database in a worker thread and then load it into the GUI, leaving the GUI thread responsive for the user.

But no, I've talked to people whom seem to think that threads are evil and bad and whatnot and one should avoid them at all costs.  I've even heard that some class instructor advised against to use of threads and therefore did not want cover their use. WHAT???

With the hardware going into multi-core, I think that we need to understand threads better and not be afraid to use them. I find it a fascinating subject personally.

So what are things you've heard about threading that are false?

答:
If you don't want to write tests for your code, then don't use threads.

Threads are not for the typical 'copy and paste' programmer who does not understand underlying fundamentals of OS and computer architecture. Since 90% of programmers are only familiar with Java, these really are not the people who should be using threads. Java makes threads "easy" but I've seen a lot of programmers who just think that if they used synchronized structures their code will work in threads ....  uhm no.

That being said, everyone needs to start somewhere, just don't make your first threading project upgrading your companies production backend server.


问:
How can my genetic algorithm accept an arbitrary number of bases of any type, without accepting a List?

Background:

I'm writing a genetic algorithm to be used to control the weights of a neural net.

To specify the bases ("bits" of the code) of the "DNA", I'm allowing the caller to pass in a List<T> of all the possible bases. When I need to mutate a base or generate a random sequence, it will be based on this passed List.

So what's the problem?

I didn't realize this until now, but the neural net may require a massive List of possible weights (possibly thousands of different bases; our DNA has 4). Obviously, passing in a List that actually contains every possible base would be very inefficient; it could potentially be huge.

My "solution" was to implement a Range class that implements List that can represent all the possible bases by only storing 3 numbers (assuming they follow a regular pattern). My attempt is on CR here: Range Code Review.

It kind of solves the problem, but has its own problems:

It barely implements List; half of the required methods throw an UnsupportedOperationException, since most of the operations don't make sense for a Range.

Since Java doesn't seem to have a usable Number interface that allows for math, I'm using the most "general" number type I could think of; a Double. Anyone using the Range will need to and from Double if they're using another type.

The container is subject to floating-point errors since the whole "container" relies heavily on math to get elements.

My question:

I need to be able to allow the user of the genetic algorithm to specify the bases that they want it to use. The bases could be of any type, and there could be any number of possible bases.

How can I allow them to specify all the possible bases without using a potentially inefficient like storing every possible base explicitly in a list?

答:
Make an interface for the features you need for bases, or use an already existing interface.

Just need to generate new random bases?  Make an interface to do that

```<code>interface BaseGenerator<T> {
    T randomBase();
}
</code>```

or use an already existing interface, like Supplier<T>.

```<code>Chromosome<T> mutate(Chromosome<T> old, Supplier<T> randomBaseGenerator) {
    [...]
}
</code>```

Body:
Make an interface for the features you need for bases, or use an already existing interface.

Just need to generate new random bases?  Make an interface to do that

interface BaseGenerator<T> {
    T randomBase();
}

or use an already existing interface, like Supplier<T>.

Chromosome<T> mutate(Chromosome<T> old, Supplier<T> randomBaseGenerator) {
    [...]
}


答:
There is no name for this specific idiom.

And it's a good idea™ to write idiomatic code, instead of trying to dumb it down further or writing code which is too clever by half.

Especially if any alternatives are long-winded, tedious, repetitive or otherwise bad.

Title: Is there a name for this pattern?

Body:
A while loop can be written as follows in C# (and many other languages):

```<code>int someValue;
int someTerminatingValue;

while ((someValue = GetSomeValue()) != someTerminatingValue)
{
    // Do something interesting
}
</code>```

Is there a name for this pattern of assigning the value inside the while loop's expression?

NB
I'm not asking if it is a good idea or a bad idea, just if there's a name for this pattern.  Whether it's good or bad, people will see it so they need to know what it is.  If there isn't a name for it then that's fine, I'm just asking if there is one.


问:
Where should business logic go in a layered architecture?
First of all, i'm not talking about validation in the sense of the nullability or length of a field like in this and this questions where we can use isValid() methods in business classes or an external Validator. However, my question is related to validate or not in business classes.
I'm using a layered architecture style with services consuming the datasource layer and interacting with the domain model.

Simplyfing the domain requirements, suppose I have Movies and Reviews, and Users can make only one Review per Movie.
So, a second Review is a valid object but the business rules should not allow the review to be completed.

So, i could do:

```<code>ReviewService >> addReview(review,movie)
  loggedUser = getLoggedUser()
  review = reviewRepository.searchReviewFrom(loggedUser,movie)
  if (review == null)
    reviewRepository.save(review)
  else
    // some mechanism to inform the error, it could be NotificationPattern
</code>```

Or:

```<code>Movie >> addReview(review)
   for r in this.reviews
     if r.user = review.user
       throw ReviewAlreadyUploaded
   // if no expcetion is thrown
   this.reviews.add(review)
</code>```

I think this oneReviewPerUser validation is a pure business rule, and should go in the business classes, in this case the Movie class. Thus the business rules are contained whitin the domain and no scattered between the layers.
However, if the lists of Reviews of the Movies are big in almost every case, this option implies query and instantiate a big number of Review object and iterate over all elements.

So assume that I choose option 1, I have to assure that every client that wants to create a review for a Movie must use the Service, because it may break the business constraint of 1 review per user if, for example, use directly the ReviewRepository.
This starts to sound like a layer of Services with all the business logic and an AnemicModel with Domain Classes being bags of attributes for carry data to and from the database.

Where is the line that separates the business logic that should be on Services from the one that should be on Domain Classes.

答:
In a DDD (Domain Driven Design) application using a conventional layered architecture, business logic goes into the domain layer. Now, please note this layer does not only contain the domain entities (Movie, Review), but also domain services (like a ReviewService class) and repositories. So, ReviewService is a business class as well.

Your concern about every client having to use the appropriate business method (addReview) is not realistic. There is just no practical way to avoid a poorly written client class from violating business rules, if the developers don't stick to the rules of the chosen architecture. For example, if Movie has a getReviews() method (or a reviews property) which exposes a mutable collection of reviews, client code can always add an arbitrary review. And even if it's immutable, client code can always create the invalid Review in the database by directly using a repository.

In my opinion, it's best to have only relatively simple business methods in domain entities, and usually only for read-only operations. More complex business logic is best assigned to cohesive domain service classes. Otherwise, your entity classes will quickly become too big and complex. So, for example, a business operation that adds a movie review subject to business validation rules would be best put in a ReviewMaintenance domain service class, or even a ReviewCreation class if the "add review" operation is sufficiently complex.


问:
How can I transition to a job using the Microsoft stack?
I graduated from university with a computer science degree (BSc), having done some C, C++, Java, Python, and Oracle along the way. I did some freelancing while I was at university and carried this into a full time job when I graduated, and I've been working full time for a year now.

PHP isn't really what I want to do, and I think it's limiting my opportunities the longer I stay along this path. It's not a language I like to use on a daily basis, and I would like to work in a larger organization, where it doesn't seem PHP has much use.

I want to stay in web development, and there seems to be plenty of jobs for the Microsoft stack: C#, SQL Server, and ASP.NET MVC. But beyond a half semester writing common-line C++ in Visual Studio, I have no experience with Microsoft technology.

Where do I start to make the transition to landing a job in a Microsoft shop? Are there any specific certifications I should be focusing on, or university courses I should be taking? What are employers or recruiters looking for?

What can I do besides creating a pet project in my spare time?

答:
My advice: find a job as a C# developer. You don't have to have the exact skillset listed in a job ad to get a job: if you show that you're a capable developer you should be able to land a job on the assumption you'll pick up the language.

I'm talking from experience here. My background is mostly Lotus Notes and Oracle PL/SQL, with bits of .NET, Java and Adobe Flex. I decided I wanted to focus on .NET, so I went and interviewed for .NET jobs. I hadn't done any .NET in 3+ years, but now I'm up to my neck in MVC, WCF and lambdas :-)

Basically: don't under-value your existing skills, and don't be afraid to learn on the job. Really, there's no substitute for real-world dev experience.

Edit: I'm also in Aus. There are opportunities if you go after them.


问:
My coworker commits and pushes without testing
When my coworker thinks that there is no need for a test on his PC, he makes changes, commits and then pushes. Then he tests on the production server and realizes that he made a mistake. It happens once in a week. Now I see that he made 3 commits and and pushes with deployment to the production server within 5 minutes.

I told him few times that this is not the way how good work is done. I don't want to be rude to him again and he is in the same status with me in the company and he has worked more than me here.

I want this behavior to be punished in some way or make it unpleasant as much as possible.

Before I started, the company was deploying using antique methods, such as FTP, and there was no version control.

I forced them/us to use Git, Bitbucket, Dploy.io, and HipChat. The deployment is not automatic, someone has to login to dply.io and press the deploy button.

Now, how can I force them to not test on the production server? Something like HipChat bot can sense that there is repeated edits on the same line and send a notice to the programmer.

答:
Now, how can I force them...

Instead of forcing your colleagues, try making them see things from your perspective. This will make things much easier for everyone. Which leads me into...

I want this behavior to be punished in some way or make it unpleasant
  as much as possible.

Why is it a pain for you with problems on the live server, but not for this guy? Do you know something that he doesn't? What can you do to make him see things the way you do?

If you succeed with this, you will bring out the best in him and he will find solutions to the problem you never thought of.

In general, try to work together with people to solve problems rather than forcing them into processes that don't understand.


问:
Is the use of a constant as a parameter of an Unit Test mocked dependency's method wrong?
We have a Unit Test Case where we want to assert that after a login operation, the SUT is able to call a method on one of it's dependencies. This dependency is a NavigationManager and the expectation is that it calls NavigationManager.NavigateTo(string).

Up to this point, we are mocking the NavigationManager to isolate the SUT. This is our test method:

```<code>var calledNavigatedToMethod = false;
nmMock.Setup(nm => nm.NavigateTo(NavigableScreens.MyNextScreen)).Callback(() => calledNavigatedToMethod = true);

SUT.Login();

Assert.IsTrue(calledNavigatedToMethod);
</code>```

As you can see, NavigableScreens.MyNextScreen is a constant, which make us think this is not a dependency, ergo it shouldn't be injected/mocked. We are merely testing that when SUT.Login()  is called, its dependency calls a method with said constant.

Our confusion is that, by the time we were writing the unit test, NavigableScreens.MyNextScreen wasn't yet defined, which made the test dependable on it's existence, and made us think that for that reason it should be injected/mocked.

A proposed argument is that since it is a dependency of the SUT, it MUST exist, which means using this constant in the Test Case is perfectly fine, as it is the exact same thing as calling NavigationManager.NavigateToMyNextScreen() in the way that if the method doesn't exist by the time the test is written, we'd have the same issue, so it MUST exist.

The question would be, is the use of this constant in the test case wrong, making it a non-unit test?

答:
One perspective is that you always need a justification to mock, rather than a justification to use the real dependency.

Mocked tests are, simply put, worse than real tests;

they test less

require more maintenance

are harder to write

produce both false positives and false negatives

have results that are more difficult to interpret

run slower (may vary depending on environment, but they generally do everything in a highly dynamic way that beats most optimisers)

Sometimes those trade-offs are worth it; the alternatives are slower, less reliable, or flat-out impossible. But, clearly, none of those apply in the case of a simple string constant. So here you can safely say there is no justification for mocking that dependency rather than using the real thing.

The corollary is the fact that you are even considering that as an option in that cut-and-dried case reveals that you are very likely overusing mocks. Try going through your test suite and think

What would happen if I replaced this usage of a mock with the real thing?

Would it perhaps run faster, detect more issues, give a better description of failures?

Would it be more refactorable, shorter, more reliable, provide better design guidance?

If you find a lot of cases where the other way of writing the test is better, in the above sense, then that's a strong argument they should be written that way.


问:
Application requires specific PHP version, but code to check if version is adequate cannot run if version is not adequate (chicken and egg problem)
A framework I'm writing (for learning) requires a specific PHP version to run, so I'm implementing a "PHP version check" to ensure the running PHP version is the minimum required for the framework.

Basic setup

htaccess redirects everything to index.php (front controller);

index.php loads bootstrap.php (nothing else);

bootstrap.php loads the core components (error display setting; error logging; user settings; then routes the requested URI);

Problem

If the version check code or anything loaded before it requires a PHP version higher than the one running, the check itself and anything before it will fail.

Crude option

Loading the version check code first would work, but the framework has logical structure, with classes in specific places called as needed with SPL and DI. And for this to work it would have to be a basic conditional in index.php (front controller), but I'm trying to avoid this because:

index.php is no place for such code

It will have no access to other framework functionality, and output
wouldn't be through framework template but a raw message:
exit('invalid PHP version');

The required PHP version (e.g. "50400") is "config" data, and
should live in core/config/. Updating/managing the required
version is not ideal in index.php

Additionally, the version check code itself has a PHP version requirement.

e.g. The check uses PHP_VERSION_ID to get the current running PHP version, which requires PHP 5.2.7.

I could use another method, but really then I'm piling all sorts of code into index.php, and it's not supposed to be like that.

So the code being first to load in index.php and being a conditional is making me cringe, as it should be a nice class calling on Core config (etc) and it doesn't belong like this in front controller as a cheap conditional.

But, maybe I have no choice.

For example, first code in index.php (so first code to run before anything else):

```<code>if (!defined('PHP_VERSION_ID') || (PHP_VERSION_ID < 50400)) {
  exit ('Insufficient PHP Version');
}
</code>```

I really cannot see any way around doing it like this, as with classes (etc) the framework needs a certain PHP version to even get to a class to check the version, and if the version is too low it'll error and even the version check class won't run.

It's the "chicken and the egg" problem.

Question

I'm looking for a solution on how to resolve this, in terms of a better software architecture and design approach.

Or, am I stuck as I think I am because having functionality run before the version check means a potential application error?

Or..

Am I trying to resolve something which does not need to be resolved?

And instead just need to state "This framework needs PHP v X.X.X, running it on lower version will bring problems".

答:
Starting with the last question, documenting the framework requirements is a must, but having the version check will be useful for those foolish enough not to read the documentation.

Having the minimum version as a configurable option doesn't make complete sense, as the minimum version is an intrinsic property of the code itself, not something external to the code that might vary from site to site. It's in the same category as the framework's version number, license, and main website (though these are all extrinsic properties). If you move the minimum version from configuration to package metadata, the problem becomes much easier.

Since the version check is part of initializing the framework, it makes sense to add it to the "bootstrap.php" initializing script, either inline or by calling some function or method with sanity checks. The latter would be a good choice if other requirements, such as for non-core extensions, exist or are likely to crop up.

Another sensible design is to add requirements checks to the installation procedure, if there is one. This is both an optimization (there's little-to-no need to check requirements with every page request) and makes conceptual sense, as installation is global initialization. This assumes that either the server configuration regarding the framework requirements won't change, or that any changes that get made won't affect the requirements (e.g. version requirements are only for minimal versions and no component will get downgraded), which are fairly reasonable assumptions (until PHP-next happens to come around). If you don't want these assumptions, you could add a server fingerprinting module based on the requirements. If the fingerprint changes, the server has changed and the requirements checks are re-run. The fingerprint check could be done on a per-request basis for all pages or only admin pages. Of course, the fingerprint calculation & check may be more expensive than the requirements check, so it may offer no advantage.

That the requirements check could be handled during installation or per-request initialization is good support for the argument that the checks themselves should be in a separate module, rather than inline.

The remaining issue is how to handle version check failure according to best practices. Since bootstrap.php shouldn't be concerned with displaying anything, it should only detect the version. Displaying an error message should be left to some framework component. To avoid another dependency cycle, you could design a component with minimum requirements that handles fatal errors (such as requirements failures, DB failures and the like) that's loaded by the bootstrap first-thing. This could be part of the controller, if it has (or can be made to have) minimal requirements.


问:
audio file processing in C++
I thought of the following project that I want to pursue:

I want to create a C++ program, that can play audiofiles and visualize the amplitudes of individual frequency bands in real time (e.g. with bars).

I did some search on google, and I found that SDL provides libraries that might do the trick. First I read about the format in which an audio file is saved (more specific uncompressed .wav files, as they seem to be the easiest to read). However, even though I now know how I can get the data of the file, I don't know what it tells me. I mean, how many bytes do I have to read to get one sample, how is the sample saved (I think it's not a direct representation of the frequency space), and so I really have no idea how to work with it. As a direct consequence, I neither know how to play the files.
Then I found SDL, and figured it should be able to extract the information that I need. Looking through the SDL wiki I was not able to find out how I have to proceed, though.

I have done some basic C++ programming in the past, I think I'm on a high enough level to do this on the programming side. I have, however, now worked with binary files so far. Also I have a strong maths background, the maths involved are no problem at all.

The ultimate goal would probably be to do the frequency analysis of all audio output or input, but I read that this depends heavily on the operating system used. Also, applying filters in real time would be a nice thing to do, but this should be rather advanced. Hence just playing an audio file and visualizing would be the first goal.

So to sum up, I think my question is the following:

What does the data in an audio file tell me? How can I get it to a state such that I can do a frequency analysis? How can this be done in real time, while playing the audio file? Is SDL a good choice for this, or is there a better way without taking away all the work (I wouldn't like to just use a program that does everything as I need it, I want to do something of my own!)?

Any ideas and inputs are much appreciated!

PS: I'm not sure I'm on the right stackexchange here, but I really couldn't find out where else this would fit.

答:
What does the data in an audio file tell me?

The header tells you the sampling rate, the data format (compressed or raw, integer or float, how many bits per sample), number of channels (mono, stereo or more channels). The actual data describes the amplitude of the signal as a function of time.

How can I get it to a state such that I can do a frequency analysis? How can this be done in real time, while playing the audio file?

Usually you launch an audio i/o background thread which repeatedly calls back your processing function when a new buffer of input audio is available (a few millisecs). In that function you process the audio and may call another function of the audio library to add a buffer to the audio output queue.

You can also update your own data structures, like the FFT of the last x millisecs. You can then mark the FFT graphics window 'dirty' to trigger a redraw on the UI thread.

Is SDL a good choice for this, or is there a better way without taking away all the work

I would recommend JUCE since it contains all what you need, from platform-independent audio input to UI with graphics. There's a demo application which demonstrates all the features and also serves as a code sample collection.

Title: audio file processing in C++


问:
When writing a math library, will operator overloading maintain OOP?
I want to make a fairly complicated mathematical library for a personal project and then have a visualization/GUI to go along with it to demonstrate the maths - nothing hardcore like topology but just show the outcome and have some small animations to demonstrate.

The library will involve matrix operations and I'd like it to be completely object-oriented. I was thinking of going with C++ or C# because of the operator overloading feature.

It will be great to just go:

```<code>C = A + B * (C + E);
</code>```

rather than

```<code>C = A.add(B.multiply(C.add(E)));
</code>```

That's what it would look like in Java. Are there any other consequences to operator overloading other than possibly being confusing?

It seems like it will be a hassle to integrate a nice GUI to a C++ library.

答:
OO is not about syntax. Just because you use object.function() vs function(object), that doesn't mean you are now "doing OO."

OO is about sending messages to objects to inform them about events, without knowing or caring how they will react to those events.

Vector math is not OO in nature and it would be a mistake to try to force it into an OO context.

In short, operator overloading will not "maintain OO" but maintaining OO is not a worthy goal when writing a math library.

[Edit]
Before someone asks something like "what about C++'s vector class, isn't that OO?"

No C++'s vector class, and classes like it, are not OO. They are a form of modular programming. Just wrapping your data up in a package and giving it a name is not what OO is about.


问:
How many views and controllers do I need?
I did one AngularJs app which was rather complex, with multiple nested tabs, which had multiple nested views & controllers, needed ng-router, and was quite tricky for me to implement, as browser based coding is not my usual thing.

Now I have been asked to code something for a friend. He was to have a column of buttons down the left sized and when a button is clicked the corresponding contents should be shown on the page.

Conceptually, this seems the same as the previous project (although it is not yet clear whether there will be any nesting).

I could just have a single view, with a single controller and several
s which I can ng-hide and ng-show, but something makes me think that I ought to use multiple views & controllers, although I am not certain.

How should I implement it, and why?

答: As the previous answer states, separation of concerns is a good idea. In your context, this basically means grouping related code into separate controllers, rather than grouping based on the design pattern that they are all controller operations. This means that if your application needs to be refactored or parts reused in some way, that you won't have to go through a painful extraction process. It also means that people who come after you to maintain the code don't have to understand a monolithic controller.</p>


答: You are leaving out the possibility of restricting the input in the database.  If there can indeed only be one review of a particular movie by a particular user, that should be a database constraint.  If you do that, then your concern is how to handle a failed attempt to insert a second review -- how does that get reported to the user.</p>

Title: Where should business logic go in a layered architecture?

Body:
First of all, i'm not talking about validation in the sense of the nullability or length of a field like in this and this questions where we can use isValid() methods in business classes or an external Validator. However, my question is related to validate or not in business classes.
I'm using a layered architecture style with services consuming the datasource layer and interacting with the domain model.

Simplyfing the domain requirements, suppose I have Movies and Reviews, and Users can make only one Review per Movie.
So, a second Review is a valid object but the business rules should not allow the review to be completed.

So, i could do:

```<code>ReviewService >> addReview(review,movie)
  loggedUser = getLoggedUser()
  review = reviewRepository.searchReviewFrom(loggedUser,movie)
  if (review == null)
    reviewRepository.save(review)
  else
    // some mechanism to inform the error, it could be NotificationPattern
</code>```

Or:

```<code>Movie >> addReview(review)
   for r in this.reviews
     if r.user = review.user
       throw ReviewAlreadyUploaded
   // if no expcetion is thrown
   this.reviews.add(review)
</code>```

I think this oneReviewPerUser validation is a pure business rule, and should go in the business classes, in this case the Movie class. Thus the business rules are contained whitin the domain and no scattered between the layers.
However, if the lists of Reviews of the Movies are big in almost every case, this option implies query and instantiate a big number of Review object and iterate over all elements.

So assume that I choose option 1, I have to assure that every client that wants to create a review for a Movie must use the Service, because it may break the business constraint of 1 review per user if, for example, use directly the ReviewRepository.
This starts to sound like a layer of Services with all the business logic and an AnemicModel with Domain Classes being bags of attributes for carry data to and from the database.

Where is the line that separates the business logic that should be on Services from the one that should be on Domain Classes.


问:
The correct way of declaring & instantiating variables ( Javascript )
I have seen other peoples code and each person has a different way of declaring variables. And I have been told by quite a few people that declaring variables in the Global Scope is wrong.

My question is why is it wrong and what is the correct way of declaring variables while writing any software, application or system.

Thanks in advance.

答: On problem with globally scoped variables is that it can make the understanding of who needs to use that variable or modify it more difficult. It also means that as code grows, there can be collisions in usage of the variable - not simply having the same name for what should be two variables, but separate usages of the same variable in different program flows.</p>


答:
You should integrate a Continuous Integration + Peer Review process in the company. Bitbucket makes it easy.

And +1 to the dev server suggested by other users.

Don't be rude with him, it will only hurt your work relationship.

Title: My coworker commits and pushes without testing

Body:
When my coworker thinks that there is no need for a test on his PC, he makes changes, commits and then pushes. Then he tests on the production server and realizes that he made a mistake. It happens once in a week. Now I see that he made 3 commits and and pushes with deployment to the production server within 5 minutes.

I told him few times that this is not the way how good work is done. I don't want to be rude to him again and he is in the same status with me in the company and he has worked more than me here.

I want this behavior to be punished in some way or make it unpleasant as much as possible.

Before I started, the company was deploying using antique methods, such as FTP, and there was no version control.

I forced them/us to use Git, Bitbucket, Dploy.io, and HipChat. The deployment is not automatic, someone has to login to dply.io and press the deploy button.

Now, how can I force them to not test on the production server? Something like HipChat bot can sense that there is repeated edits on the same line and send a notice to the programmer.


问:
Accessing internal API via Internal DMZ
I have an API that for firewall reasons can't sit on an internal DMZ and has to reside on the internal network. It was suggested that I build a 'shell' API that basically has all the same endpoints but just passes data back and forth between the APIs and Web App.

So is creating another API to sit in the internal DMZ so I can pass messages between the DMZ web app and the Internal Web API the best way to achieve this? Or more to the point: what is the standard way to forward HTTP requests from the DMZ to Internal via an Internal DMZ?

Would an ideal way be to set up ARR on the internal DMZ to send to the internal API?

答:
In my experience, using a reverse proxy like that provided by nginx was the easiest approach as it involved little more than forwarding relevant external requests through the firewall.

https://www.nginx.com/resources/admin-guide/reverse-proxy/

The problem with a shell or facade, as some call it, is the constant need to update in two code bases and on at least two servers as the code evolves. Making one API work well and securing it will be an easier task and reduce maintenance complexity. With nginx, you can limit the URL paths that will be proxied.

Title: Accessing internal API via Internal DMZ


问:
Is there any programming language(s) which has mathematical number types?
I may not have worded the title correctly. Is there any programming language(s) which deals with natural mathematical number types rather than the typical data types we see like Int32, Int64, Float, Double etc?

By natural number types I mean the likes of

natural (1, 2, 3 ...)

whole (0, 1, 2, 3 ...)

integer (-1, 0, 1, 2, 3 ...)

rational (-1, 0, 1, 1.25, 2, 3, 3.5 ...)

real (-1, 0, 1, 1.25, 2, 3, pi, 3.5 ...)

complex (-1, 0, 1, 1.25, 2, 3, pi, 3.5, i, 2i, 1 + 2i ...)

Or may be bit more practical and useful set of types, like

whole (0, 1, 2, 3 ...)

integer (-1, 0, 1, 2, 3 ...)

real (-1, 0, 1, 1.25, 2, 3, 3.5 ...)

complex (-1, 0, 1, 1.25, 2, 3, pi, 3.5, i, 2i, 1 + 2i ...)

so that if I write:

whole w = 1 // compiles

integer i = 1.2 // doesnt compile

real r = 1.2 //compiles

complex c = 1 + i //compiles

w = i //doesnt compile

i = w //compiles

r = i //compiles

c = r //compiles

I know I can achieve this in most programming languages using uint32, int32, decimal etc types but I'm looking forward to a language that doesn't appear that technical about numeric types.

Few points:

Looking for programming languages which names the numeric types from a mathematical perspective and not computer.

I know size always matter in programming, but let's assume size is not an issue for now. Or may be it is configurable and I could set the size to be as that ofuint64, int64 etc. This is more than ever needed.

I am not after math libraries which has types defined like real, complex etc. I want those types to be treated as first class by compiler/language itself so that static error checking is done.

Asking this just out of curiosity when I was thinking of programming languages for educational purposes for non-programmer friend.

答: There are Computer algebra systems which usually support correct number representations necessary for any given computation they do.</p>


问:
Feature Toggling for apps (for a/b testing)
I have a published app (Android/iOS) and I'd like to instrument the next version so that I can remotely enable/disable or adjust features, through a web interface. This could facilitate a/b testing for example.

I'm struggling with this because I don't know what this concept is called (remote feature control?, feature flagging?), so it's hard for me to search for solutions. I'm hoping there are services out there that provide a web interface for controlling simple key-value pairs for my app on the fly, possibly allowing for cohorts. I've searched through the docs for crittercism, localytics, google docs and haven't found anything.

At runtime my app would rely on that service's sdk code to query the server-set value of such a parameter and act accordingly. For example, the app might use the value 500 milliseconds for an animation based on a key called ANIMATION_DURATION.

Any advice on terminology or examples of such services would be much appreciated. Thanks.

As I'm writing this, I just found a company called Airwatch. They call their solution "Enterprise Mobility Management", so maybe that's one example.

答: If you are doing such testing, you will need a way to get the result data back to you. Feature toggling services won't necessarily provide such two-way communication. It seems as though you will need a two-way communication channel, and probably some kind of registration or log-in, such as by having a http server and requiring some frequency of communication from the app. (not necessarily constant connection, but frequent enough for your desire to change settings and retrieve test data.)


答:
You clearly understand various possible process and technical solutions. The issue is how to manage the coworker.

This is essentially a change management exercise.

Firstly, I'd have a quiet word with the founder to make sure he/she is on board with your point of view. If there is a production outage, I would expect that the founder would be highly concerned about that and desire change.

Secondly, you work in a small team and it's likely worth trying to get the whole team engaged in process improvement.

Setup regular (for example weekly) process retrospectives. Have the whole team:

Identify problems

Volunteer ideas for improving work practices

Engage in implementing those practices

It should follow naturally that the whole team then also helps ensure compliance with the improved practices.


问:
Determining game item prices based off of player trades/in-game economy
I've been working on a game the past few months and I'm finally starting to approach issues regarding the in-game economy. The game is sort of like an MMORTS, players create their own nations and they have cities all over the world map. I want players to be able to trade resources between their cities and other players' cities. For the sake of this example, let's say the cities are trading oil. One city might be right next to a few oil deposits, so they're going to sell to other cities that don't have any oil deposits next to them.

Instead of the game having a fixed price for oil, I want the price of one unit of oil in the game to reflect the current supply and demand of it in game. How can I go about doing this within the virtual economy of my game?

My first thought was to take the average price payed for oil between trades among players; however, how do I protect from friends working together to continuously trade oil at higher prices between each other to artificially inflate the prices for their gain?

Note: I have little to no knowledge on how an economy works in-depth, so I hope this question isn't too silly.

答:
Whilst setting prices based on trade values works (the stock market works this way for example) it is (or should be) self-regulating by having a very large number of traders involved in the setting of the price. So a few players cannot rig the market because they would be a small factor in trading. However, this still cannot prevent abuses caused by very large players trading or by a lot of traders all deciding to trade (eg someone with a lot of money makes a trade, that will affect the price disproportionately, similarly see tulip bubbles for examples of how prices were set irrationally by many traders)

So for a game, you need to put brakes on these, just to ensure stability in the game that would not come from the usual routes in real life.

Perhaps the easiest way is to introduce a large number of NPC players who trade on a moving (ie historical) average. Then PCs cannot manipulate the market as their trades are simply lost in the mass of other trades. Unfortunately this would also prevent the kind of price fluctuation you want. You'll have to tweak the number of NPCs to find the right balance.

The other aspect is supply and demand, you can have prices set according to the quantity of some resource. If a banana costs me $1 today, and tomorrow someone finds a new supply of bananas doubling the number present in the universe, the price of a banana will (theoretically) drop overnight to 50c. You can use the same mechanism (which won't be as extreme) to regulate prices. (obviously the opposite holds true too). If you also introduce a localisation effect, where supply is greater or lesser in various areas, you create trading routes - ie my island that makes bananas has  lots of them, so price is low, whereas the city that has none, the price is high. As more of the bananas are moved from island to city, the price rises in one and drops in the other, finding a balance.

So set an arbitrary price for each resource, allow NPC movement of goods from low-price areas to high-price areas, introduce consumptions and production of these resources and let the game stabilise itself. Then the players, and random effects (eg natural disasters, increase and decrease in production, NPC attacks on trade routes, etc) will de-stabilise the prices all by themselves.

Its important to handle quantity here, rare items will hold their value regardless of where they are and won't be affected by economies unless you want to get advanced and set prices through the supply of money - that introduces inflation which will destabilise things further and require an equal continual influx of currency to keep the economy moving. This isn't such a bad thing as it means nobody can sit on their wealth and expect it to retain its value, so they have to keep working.


问:
How did JavaScript become popular?
In ancient history, Brendan Eich had a language design, and in today's world, JavaScript is a popular language implemented and used in many different places.

What caused the language to become popular? Was it the C-like syntax familiar to previous programmers? Did Netscape have enough control of the market to force it to be used? Or is there some deeper reason that JavaScript is popular and other languages are not?

Particularly, if you had to make a language as popular as JavaScript, what initial conditions would you need to recreate its growth in popularity?

答:
I really think it has to do with its C-like syntax. According to Wikipedia Javascript appeared in '95. At that time C was at an all time high and Java was the next-and-coming language. I think the syntax was really appealing (for that time) and its name association with the next big language, Java, gave it an edge.

It allowed an easy cross over at that time for C programmers to adapt to a dynamic language.

```<code>Programming Language    Dec 2010    Dec 2005    Dec 1995        Dec 1985
Java                    1           1           -               -
C                       2           2           1               1
</code>```

Tiobe Index

If I was to recreate the success of Javascript I would look at problems plaguing modern programmers and give them a solution with a familiar syntax.

IMO parallel programming is the next big problem programmers are facing. I think functional-languages really do a great job at overcoming that obstacle. If I was to create the next Javascript I would create a functional-language with a common platform. In addition I think it would need to be flexible enough to be a scirpting language but powerful enough to be a statically typed language, with a great framework.

Although not everyone may agree, under those conditions, I think F# may have a lot of merit in the future.

Title: How did JavaScript become popular?

Body:
I really think it has to do with its C-like syntax. According to Wikipedia Javascript appeared in '95. At that time C was at an all time high and Java was the next-and-coming language. I think the syntax was really appealing (for that time) and its name association with the next big language, Java, gave it an edge.

It allowed an easy cross over at that time for C programmers to adapt to a dynamic language.

Programming Language    Dec 2010    Dec 2005    Dec 1995        Dec 1985
Java                    1           1           -               -
C                       2           2           1               1

Tiobe Index

If I was to recreate the success of Javascript I would look at problems plaguing modern programmers and give them a solution with a familiar syntax.

IMO parallel programming is the next big problem programmers are facing. I think functional-languages really do a great job at overcoming that obstacle. If I was to create the next Javascript I would create a functional-language with a common platform. In addition I think it would need to be flexible enough to be a scirpting language but powerful enough to be a statically typed language, with a great framework.

Although not everyone may agree, under those conditions, I think F# may have a lot of merit in the future.


问:
Do objects in OOP have to represent an entity?
Does an object have to represent an entity?

By an entity I mean something like a Product, Motor, a ParkingLot etc, a physical, or even a clear-cut non-physical conceptual object -- something that is well defined, with some core data clearly belonging to the object, and some functions/methods that clearly operate on the core data.

For example, I can have an object of a Demon, an entity in itself, an imaginary one perhaps and not physical but an entity nevertheless

Can an object be just a collection of methods, a common set of procedures that tie in with a common goal?

Example:  can a class be called MotorOperations or MotorActions, where there is no entity, but methods inside the class do things like

getMotorDataFromHTMLForm()

getMotorManufacturers()

selectMotorFromUserRequirements($requirements)

canMotorCanHandleOperatingConditions($conditions)

computePowerConsumptionForMotor($id)

A class is typically defined as data central to the object + operations on data.  So for a Motor there may be some motor variables relating to motor specifications, and there can be operations that combine those data to produce something.

In my case it is more like I have a class with operations on data + data that is passed through the class, there is no data centric to "Motor Operations", other than temporary pass-through-the-class data.

Question

Can classes represent entity-less objects?
If not, why they are bad/incomplete/non-OOP-centric?  Are there ways they need to be changed/improved conceptually to be in line with OOP?

答:
An object is a collection of methods and data that have high cohesion. They belong in a class because they are highly interrelated and state is retained.

This is true whether you use big up front design and attempt to model everything, or emergent design where you iterate and evolve the object into whatever fits the needs of the system at the time.

If you have no reason to retain state, you probably don't have any reason to instantiate an object which means there is probably no reason to have a class. Unless, the language your using doesn't have the ability to define a namespace other than using class. In which using class should be fine because it would be idiomatic.

I can't think of any negative aspects to using classes in this way other than the typical. Your inviting unnecessary cost and complexity by having to instantiate a "namespace". Anyone supporting this code will wonder where the data is costing additional cognitive load (most likely a one time cost per person). It's an unusual usage without any additional value.


问:
Hiding query strings logically?
I feel uncomfortable when using query string parameters as:

http://xyz.com/default.aspx?carId=1129&country=uk&uniqueId=98745DVF4563VVf1259

I would rather use something that should not make sense to anyone who is trying to make some sense from the URL:

?a=1129&b=uk&c=98745DVF4563VVf1259

(after all this query sting info is for my use only)

Firstly is this a good thing to do? (I mean to hide logic of you query string)

If it is, then is there a way, that internally developers can use carId, country and uniqueId in code, but externally the url uses a, b and c respectively?

So if someone goes to

?a=1129&b=uk&c=98745DVF4563VVf1259

when I do Request.QueryString["carId"]

I should get 1129.

Can this be done?

答:
Well, actually you can hide query strings easily in MVC Asp.net without obfuscating.

The general idea is to create at least two pathways to the url with the query string. In the pathway(s) you want people to be able to access, create an intermediate method that redirects to the action where you want to return your view. The 2nd pathway will access that action I mentioned before directly. In the intermediate method, you tell a database to increase the value of has this page been accessed before to 1.

You might have to think about the next part for a couple of hours before getting why it works 99% of the time. At the end of the intermediate method, set the value back to 0! In the action that returns a view, make it so that the view you want to return can only be returned if the value is set to 0! However, before the view is returned, set the value to 1!

While, this method is not 100% secure. I think it is the only implementation that uses only basics and very little code. Obsfucating doesn't made query string urls inaccessible. It just makes it harder for people to access the website.

Title: Hiding query strings logically?


问:
What strategy to follow while matching sql server datatypes in C# Code First approach while using Entity Framework
While matching SQL Server datatypes with C# Code First Approach in Entity Framework, what are specific points that we should keep in mind so that our C# datatype should match exactly our SQL Server datatype?

Specifically, while we have to match SQL Server datatype to C# datatype, let's say for particular datatype  hierarchyid, which exists in SQL Server but not in C#, how can we make it possible?

答:
EF should handle the mapping of most datatypes. If you're using something that isn't handled you should be able to customize the mapping. Easiest would be to exclude mapping for unknown types, and save your object in a flattened way either in or related to the entity.
Downside is that querying could be more work and you need to provide something to convert your object when reading and writing, but you're doing that maybe already when converting to viewmodels.</p>


答:
I for one think people thought Javascript had to do something with Java.

(Like nowadays everything starts with an "i" )

Marketing/publicity strategy does play a significant role.

Title: How did JavaScript become popular?

Body:
In ancient history, Brendan Eich had a language design, and in today's world, JavaScript is a popular language implemented and used in many different places.

What caused the language to become popular? Was it the C-like syntax familiar to previous programmers? Did Netscape have enough control of the market to force it to be used? Or is there some deeper reason that JavaScript is popular and other languages are not?

Particularly, if you had to make a language as popular as JavaScript, what initial conditions would you need to recreate its growth in popularity?


答: One of the problems of using global variables is that it can lead to conflicts when you use them with other modules that also uses the same variable names and are also declared global in those modules.  Say you have a Javascript file call it main.js and in that file are codes where there are global variables A, B and C.  Then, your colleague who is also working in the same project as you do creates another Javascript file called main2.js and he too for the sake of example made use of variables A, B, and C yet those variables are for a different purpose in your project.  Now, since your application requires both of your modules, you load them up.  When, the application is run there are chances that your program will crash due to conflicts of the variables during runtime.  The Javascript file that was loaded last will supercede the ones that were loaded first. This is one of reasons why global variables are rarely used.  Hope this answer helps...</p>

Title: The correct way of declaring & instantiating variables ( Javascript )

Body:
I have seen other peoples code and each person has a different way of declaring variables. And I have been told by quite a few people that declaring variables in the Global Scope is wrong.

My question is why is it wrong and what is the correct way of declaring variables while writing any software, application or system.

Thanks in advance.


问:
Rust-style error handling in C++
I've been reading some articles on how Rust does error handling using the Result<T, E> type and to me it seems like a hybrid best-of-both-worlds (exceptions and return codes) solution which can be very useful. I think it would especially be handy for APIs where you don't really know on beforehand if certain errors are exceptional and should throw, or that they are merely an indication of something going wrong in an 'expected' way. Returning Result allows moving that decision to the users of the API in a not too intrusive way. So I'm now debating whether or not to introduce this in a C++ project. The result class could be implemented roughly like this:

```<code>template< class T, class E = std::exception >
class result
{
public:
  //constructors etc

  operator bool() const
  {
    return !!res;
  }

  T& operator * ( )
  {
    if( !res )
    {
      assert( ex );
      throw *ex;
    }
    return *res;
  }

  const E& exception() const
  {
    assert( ex );
    return *ex;
  }

private:
  std::optional< T > res;
  std::optional< E > ex;
};
</code>```

So whene there is a function

```<code>result< int > Read();
</code>```

callers can use either 'error-code' style:

```<code>const auto result = Read();
if( !result )
{
  log.debug() << "failed read" << result.exception();
  return false; //or again return a Result
}
doSomething( *result );
</code>```

or 'exception' style:

```<code>try
{
  doSomething( *Read() );
}
catch( const std::Exception& e )
{
  //do what's needed
}
</code>```

or decide they don't know how to handle exceptions from Read and let their caller in turn deal with it

```<code>doSomething( *Read() ); //throws if !result
</code>```

Does this seem like a good idea in general, and are there similar principles used in existing C++ code? Or are there serious disadvantages I'm not seeing at the moment? Like is it too complicated towards the users because there are too many options or maybe because it is not a typical system used in C++?

答:
Well, it could conceivably be useful. If the function shouldn't have used exceptions anyway.

But your type is all wrong:

You have to allocate the exception dynamically (or at least allow for it being allocated dynamically) to allow for returning a sub-type.

Avoid stacking mutually exclusive optionals on top of each other, that just wastes space. And stack-space is actually somewhat valuable. Take a look at Boost.Variant.

If you do correct #2, you might be able to do a small-exception-optimization for #1 and thus avoid dynamic allocation most of the time.

Title: Rust-style error handling in C++


问:
Relationship between objects
I got the models Post and Category. A Post is assigned to a Category. A Category has many Posts. They should be stored in a database. I implemented the following classes for it:

Models/Post.php:

```<code>class Post {
    /**
     * Title of the post.
     *
     * @var string
     */
    public $title;

    /**
     * The category that is assigned to the post.
     *
     * @var Category
     */
    public $category;

    public function __construct($title, Category $category) {
        $this->title = $title;
        $this->category = $category;
    }
}
</code>```

Models/Category.php:

```<code>class Category {
    /**
     * Name of the category.
     *
     * @var string
     */
    public $name;

    /**
     * Posts that are assigned to this category.
     *
     * @var Post[]
     */
    public $posts;

    public function __construct($name, array $posts) {
        $this->name = $name;
        $this->posts = $posts;
    }
}
</code>```

When I want to display a post, I will fetch it via an ID from a database. But what about the category? When I want to get the name of the category (to display it in the meta informations below the post) I have to fetch all posts that belongs to this category.

So my questions is: Is it better to store the IDs of the posts in Category::$posts instead the entire objects?

答:
If I have understood your question correctly I cannot see the problem. With posts and categories are stored separately in the database the relationship between them should be stored inside a junction table. Then when you fetch a post by its ID you can lookup the corresponding category inside the junction table. An example:

Categories table columns:

id

name

description

Posts table columns:

id

title

contents

Junction table columns

category_id

post_id

Both columns inside the junction table are foreign keys of their respective table columns. So lets say you fetch post with an ID of 123. You then lookup the database row in the junction table where the column post_id equals 123. You now have the specific category ID and can now fetch only its specific details.

I hope this can help you, happy coding!

Title: Relationship between objects


问:
How to work with fail reason
Imagine that I have a method like User::validate($data), and mostly the developer expects only that is returns a boolean (true mean "ok, validated with success"). But, in some specific cases, he need check why validation failed. What is the best way to check that?

I thought in following ways:

Use an argument like User::validate($data, $throwsException = false) that when true, will throws an exception if it fail -- instead of returns false;

Always throws an exception. So the developer need care about in catch exceptions of this method -- I personally don't like that;

Instead of returns a boolean, returns a string or const (like FAIL_INVALID_NAME), but uses true as success -- or another const, like SUCCESS;

Create an additional method like User::validateWithException($data) that, if it fails, throws an exception instead of return false;

Create an additional method like User::validateReason($data) that will returns a string with the validation result -- like fail:invalid-name or success;

Create an additional method like User::getLastError() that will returns a string or const with last error ocurred on class User, like after the validation method;

答:
A few of your cases above suggest throwing an exception when a validation fails.  This is typically not recommended as exceptions should be reserved for exceptional cases (e.g., service not available, timeouts, etc) and not normal program flow.  Also, exceptions are typically expensive operations.

Validations are expected to fail when the conditions are not met and should return values indicating this.

Per your question on what this should look like, one option would be to update your input and output to objects with a few properties.  Perhaps something like:

ValidationRequest

$Data

$StopOnFirstFailure

Other validation behavior controlling properties

ValidationResponse

$Success

$FailureReasons

Take a look at one of the many validation frameworks out there and you'll see how these patterns are used.

Title: How to work with fail reason


问:
Is the question "What is the using statement" a bad question to ask an interviewee?
We're looking to hire a new junior C# developer.
We're not looking for guru's or anything, so my boss asked me to write down a few questions and answers of varying difficulty to assess their skills.

My first question was "What does the using statement do".

So far after 2 interviews (both fresh out of college I think) both answered "used for including a namespace". After telling them not to confuse it with the using directive neither could explain what it does.

To me this seemed a fairly easy question for someone who has worked with C#. Am I wrong and is it a bad/confusing question?

答: It's not a bad/confusing question; it's basic language knowledge that's important for proper resource management.  You've just found a few green interviewees who never learned about it in college.</p>


问:
Nested functions; allow or not?
Having programmed a whole lot in python, using nested functions is a good way to not clutter the namespace with small helper functions that are only used once.

Now I'm programming in go, and upon writing some code that I immediately wanted to refactor into an inner function, I found that go does not allow nested function declarations. I immediately changed the function to an anonymous function and saved it in a variable, and called it as a normal function. However, this seems to go against the language design since the normal function declaration syntax cannot be used inside another function.

Is there a good reason to not allow, or to deter use of nested function declarations?

答:
Go's primary design goal is to be simple to learn and simple to use even for sub-mediocre programmers, so if you want to write idiomatic Go the anti-pattern you should avoid the most is the "Clever Code" anti-pattern.

As for a good reason to not allow nested functions even though you allow anonymous functions - one of the differences between Python and Go is that Python doesn't need a main function. You can just write:

```<code>def foo():
    print('hi')

foo()
</code>```

and the Python interpreter would start reading from top to bottom. When it reaches def foo(): it will create a function, and when it reaches foo() it'll run that function. The interpreter is always in the same mode(that's, at least, the abstraction) - the read-and-evaluate mode. It acts the same whether it's inside or outside a function, so it's easy for it to support copying all that code to inside a function - it'll just add another frame to it's callstack and other than that do the exact same thing.

Go is a different story. When you write

```<code>func foo() {
    fmt.Println("hi")
}

func main() {
    foo()
}
</code>```

The compiler reads the top level in declarative mode, and creates the functions, but the body of the functions it reads in imperative mode. In declarative mode it can create functions and in imperative mode it can run statements. Allowing nested functions will require adding function declaration functionality to imperative mode.

So why, one might ask, not add that functionality to imperative mode? The main reason is handling closures:

```<code>func main() {
    txt := "hi"
    foo := func() {
        fmt.Println(txt)
    }
    foo()
}
</code>```

Writing something like this means that foo is not a regular function - it needs access to txt, which resides in main's stack frame, so it needs a context pointer that'll point to that frame. If main is called again another foo will be created with a different context pointer.

This makes nested functions essentially different from regular functions, which is a reason against having nested functions. Python doesn't have this problems, because all it's functions are closures - they are all "nested".

Title: Nested functions; allow or not?

Body:
Go's primary design goal is to be simple to learn and simple to use even for sub-mediocre programmers, so if you want to write idiomatic Go the anti-pattern you should avoid the most is the "Clever Code" anti-pattern.

As for a good reason to not allow nested functions even though you allow anonymous functions - one of the differences between Python and Go is that Python doesn't need a main function. You can just write:

def foo():
    print('hi')

foo()

and the Python interpreter would start reading from top to bottom. When it reaches def foo(): it will create a function, and when it reaches foo() it'll run that function. The interpreter is always in the same mode(that's, at least, the abstraction) - the read-and-evaluate mode. It acts the same whether it's inside or outside a function, so it's easy for it to support copying all that code to inside a function - it'll just add another frame to it's callstack and other than that do the exact same thing.

Go is a different story. When you write

func foo() {
    fmt.Println("hi")
}

func main() {
    foo()
}

The compiler reads the top level in declarative mode, and creates the functions, but the body of the functions it reads in imperative mode. In declarative mode it can create functions and in imperative mode it can run statements. Allowing nested functions will require adding function declaration functionality to imperative mode.

So why, one might ask, not add that functionality to imperative mode? The main reason is handling closures:

func main() {
    txt := "hi"
    foo := func() {
        fmt.Println(txt)
    }
    foo()
}

Writing something like this means that foo is not a regular function - it needs access to txt, which resides in main's stack frame, so it needs a context pointer that'll point to that frame. If main is called again another foo will be created with a different context pointer.

This makes nested functions essentially different from regular functions, which is a reason against having nested functions. Python doesn't have this problems, because all it's functions are closures - they are all "nested".

ContentLicense: CC BY-SA 4.0


答:
There are major differences between throwing exceptions and returning error objects, in particular,

exceptions create many new code-flow paths which are not explicitly visible in the source code,

callers have no idea what kinds of errors they can expect,

they propagate automatically, and

they make the code much less verbose and easier to read and write.

Rust tries to get the best of both worlds by banning exceptions (this eliminates the first two points) and by having the try! macro (this deals with automatic propagation and verbosity).

Your solution deals with the first two points only and there is no straightforward way to have the latter two. Your * operator is not an equivalent of try!. The equivalent of

```<code>x = try!(foo());
</code>```

is simply not possible to do in C++ (without language extensions).

That said, feel free to use your class, though as @Deduplicator points out, your Result class can only hold exception objects of dynamic type std::exception, which is probably not what you intended. The easiest way to accomplish what you want is to use std::exception_ptr to hold the exception object.

Or, better yet, just use exceptions -- that's what the language was designed for after all.

Title: Rust-style error handling in C++

Body:
I've been reading some articles on how Rust does error handling using the Result<T, E> type and to me it seems like a hybrid best-of-both-worlds (exceptions and return codes) solution which can be very useful. I think it would especially be handy for APIs where you don't really know on beforehand if certain errors are exceptional and should throw, or that they are merely an indication of something going wrong in an 'expected' way. Returning Result allows moving that decision to the users of the API in a not too intrusive way. So I'm now debating whether or not to introduce this in a C++ project. The result class could be implemented roughly like this:

```<code>template< class T, class E = std::exception >
class result
{
public:
  //constructors etc

  operator bool() const
  {
    return !!res;
  }

  T& operator * ( )
  {
    if( !res )
    {
      assert( ex );
      throw *ex;
    }
    return *res;
  }

  const E& exception() const
  {
    assert( ex );
    return *ex;
  }

private:
  std::optional< T > res;
  std::optional< E > ex;
};
</code>```

So whene there is a function

```<code>result< int > Read();
</code>```

callers can use either 'error-code' style:

```<code>const auto result = Read();
if( !result )
{
  log.debug() << "failed read" << result.exception();
  return false; //or again return a Result
}
doSomething( *result );
</code>```

or 'exception' style:

```<code>try
{
  doSomething( *Read() );
}
catch( const std::Exception& e )
{
  //do what's needed
}
</code>```

or decide they don't know how to handle exceptions from Read and let their caller in turn deal with it

```<code>doSomething( *Read() ); //throws if !result
</code>```

Does this seem like a good idea in general, and are there similar principles used in existing C++ code? Or are there serious disadvantages I'm not seeing at the moment? Like is it too complicated towards the users because there are too many options or maybe because it is not a typical system used in C++?

Body:
There are major differences between throwing exceptions and returning error objects, in particular,

exceptions create many new code-flow paths which are not explicitly visible in the source code,

callers have no idea what kinds of errors they can expect,

they propagate automatically, and

they make the code much less verbose and easier to read and write.

Rust tries to get the best of both worlds by banning exceptions (this eliminates the first two points) and by having the try! macro (this deals with automatic propagation and verbosity).

Your solution deals with the first two points only and there is no straightforward way to have the latter two. Your * operator is not an equivalent of try!. The equivalent of

x = try!(foo());

is simply not possible to do in C++ (without language extensions).

That said, feel free to use your class, though as @Deduplicator points out, your Result class can only hold exception objects of dynamic type std::exception, which is probably not what you intended. The easiest way to accomplish what you want is to use std::exception_ptr to hold the exception object.

Or, better yet, just use exceptions -- that's what the language was designed for after all.


问:
Why do new programmers seem to ignore compiler error messages/runtime exception messages?
I think we’ve all seen this. Beginners ask questions on Stack Overflow that follow the basic outline...

I’m trying to do (very vague description of the goal) but it doesn’t work/I get an error/exception. Please help!

Isn’t it bizarre that so many of them seem to consider it unnecessary to paste the error message?

I wonder what the psychology of this is. What is it about error messages that makes people initially assume that they are useless and not worth paying any attention to?

The answer I’m looking for is not “they don’t understand the error message”. That doesn’t explain why they wouldn’t consider telling anyone else who might understand it.

答:
I don't think it's only newbies.  I have co-workers with years of experience who seem to only look at the line number when they get a compiler error, then try to figure out the rest themselves (often by trying voodoo like "let's add parenthesis" or "let's break this up into two statements").

My suspiscion is that this comes from not really having a deep understanding of the rules of the language, so that the generally dense description of the error doesn't have much meaning.   expression must be a modifiable lvalue seems like pretty useless information if you really don't know what an lvalue is.