问:
How can I mock this architecture?
This is not a very general question, so it may not exactly be appropriate here, but I could sure use a suggestion if you have one:

I have an object containing a dictionary keyed off of an enum, something like this:

```<code>namespace Application
{
    public enum Material { H20, CO2, Na }
    public class Container
    {
        private Dictionary<Material, ChemicalComponent> dic;
        public Container(Dictionary<Material, ChemicalComponent> d)
        {
            dic = d;
        }
    }
}
</code>```

I now want to create a MockContainer and a MockMaterial, but I can't figure out how to make it all work together. The following code, for example, does not work (see comment):

```<code>using Application;
namespace UnitTesting
{
    public enum mockMaterial { mock1, mock2, mock3 }
    public class mockContainer : Container
    {
        public mockContainer(Dictionary<mockMaterial, ChemicalComponent> d)
            : base(d) // compiler error: the base constructor "has some invalid arguments"
        {
        }
    }
}
</code>```

Originally I had hoped to extend the Material enum inside the UnitTesting namespace; then I could just use the Container's Dictionary, but with different keys. But of course, that isn't legal in C#. Is there some non-kludgy way to overload or inject a Dictionary with the mock enum keys?

Update: One option is to change the dictionary definition to this:

```<code>private Dictionary<Enum, ChemicalComponent> dic;
</code>```

(i.e., change the key type to Enum throughout the code). This works (i.e., eliminates the compiler error), but this solution sacrifices clarity as well as type-safety. (It is no longer clear what the key is intended to be).

Update #2:
Several people have recommended that I create an interface for Container. But that misses the point. The container itself is not all that complex. But the ChemicalComponents that are stored in it are very complex. I need to mock those in my unit tests, but I don't know how to do that without extending the enum that serves as the key.

答:
I now want to create a MockContainer and a MockMaterial, but I can't figure out how to make it all work together.

Why?

I mean, the purpose of test objects (mocks, fakes, stubs, etc.) are to remove some dependency in your code so you can test while ignoring the dependency. Material is an enum. That's not some sort of dependency that is going to break your tests. Making some inglorious hack is more likely to break your tests (and your production code).

If you want a mock container (I'm assuming your container is more than being an alias to Dictionary<Material, ChemicalComponent>), then you should provide some interface to the container, and mock that.

And remember:

If the code is hard to test, it's probably hard to use (see, lack of interface making it inflexible for a different implementation).

The tests are there to serve you, not vice versa. Don't do things blindly because you should. Do them because they make your life easier.

Title: How can I mock this architecture?


答: Its not worthwhile to mock away an enum, you gain nothing by it.  You wouldn't mock away System.Int32 would you?  As far as mocking container, I'd create an interface and then you can mock the implementation of that interface.</p>

ContentLicense: CC BY-SA 3.0

Title: How can I mock this architecture?

Body:
This is not a very general question, so it may not exactly be appropriate here, but I could sure use a suggestion if you have one:

I have an object containing a dictionary keyed off of an enum, something like this:

```<code>namespace Application
{
    public enum Material { H20, CO2, Na }
    public class Container
    {
        private Dictionary<Material, ChemicalComponent> dic;
        public Container(Dictionary<Material, ChemicalComponent> d)
        {
            dic = d;
        }
    }
}
</code>```

I now want to create a MockContainer and a MockMaterial, but I can't figure out how to make it all work together. The following code, for example, does not work (see comment):

```<code>using Application;
namespace UnitTesting
{
    public enum mockMaterial { mock1, mock2, mock3 }
    public class mockContainer : Container
    {
        public mockContainer(Dictionary<mockMaterial, ChemicalComponent> d)
            : base(d) // compiler error: the base constructor "has some invalid arguments"
        {
        }
    }
}
</code>```

Originally I had hoped to extend the Material enum inside the UnitTesting namespace; then I could just use the Container's Dictionary, but with different keys. But of course, that isn't legal in C#. Is there some non-kludgy way to overload or inject a Dictionary with the mock enum keys?

Update: One option is to change the dictionary definition to this:

```<code>private Dictionary<Enum, ChemicalComponent> dic;
</code>```

(i.e., change the key type to Enum throughout the code). This works (i.e., eliminates the compiler error), but this solution sacrifices clarity as well as type-safety. (It is no longer clear what the key is intended to be).

Update #2:
Several people have recommended that I create an interface for Container. But that misses the point. The container itself is not all that complex. But the ChemicalComponents that are stored in it are very complex. I need to mock those in my unit tests, but I don't know how to do that without extending the enum that serves as the key.


问:
When to use packages or Repositories in Laravel?
I'm a Laravel (PHP) developer, and new with DI, Packages (workbench) and Repositories (Pattern).

I want to know about the best concept/methodology for a more flexible design; ie. the project can grow and become something very modular.

For example, after watching some Jeffrey Way videos in Laracasts I decide use that pattern:

app/

app/config

app/controllers

app/database

app/views

app/patrickmaciel (psr-4 in composer.json)

app/patrickmaciel/user (repositories, eloquent model, validation, etc)

app/patrickmaciel/group

app/patrickmaciel/post

app/patrickmaciel/billing

app/patrickmaciel/helpers

app/patrickmaciel/filters

But after watch more videos, and reading more about flexibility, I see developers using packages instead of this psr-4 alternative (composer.json):

```<code>"require": {
    "patrickmaciel/group",
    "patrickmaciel/user",
    "patrickmaciel/post",
    "patrickmaciel/billing",
    "patrickmaciel/helpers",
    "patrickmaciel/filters"
}
</code>```

So, what is better for more flexibility?

答:
The first solution you have proposed is an excellent solution, as it namespaces your code properly and means that your code is in the correct structure should you want to shared your code through a package manager (like packagist) later on.

If, at some point, you intend to share you code to other developers via something like packagist, you would do the nexessary work to package it and then others could import your code using the require block you've noted second. If the code does not need to be shared publicly then I don't think the second approach provides any benefits.


问:
Inverse property naming (ORM scenario)
I have a class that represents a process. In this process there are inputs boxes and output boxes.

```<code>public class Process
{
    public long ProcessId { get; set; }
    public virtual List<Box> InputBoxes { get; set; }
    public virtual List<Box> OutputBoxes { get; set; }
}
</code>```

As you know, naming things is one of the hardest things in programming, and in this scenario, I don't know what name I can give to the inverse property:

```<code>public class Box
{
    public long BoxId { get; set; }
    public virtual Process ProcessWhereBoxIsInput { get; set; }    /* ugly name */
    public virtual Process ProcessWhereBoxIsOutput { get; set; }   /* ugly name */
}
</code>```

What is the common way of naming things in scenarios like this?

答:
The rule I use quite often is to remove the plural and the subject from the original property name, then add "to". In your example, I would probably end up with:

```<code>public class Box
{
    public long BoxId { get; set; }
    public virtual Process InputTo { get; set; }    /* ugly name */
    public virtual Process OutputTo { get; set; }   /* ugly name */
}
</code>```

Depending how I plan to use the property (i.e. whether it makes sense grammatically), I might add the obverse entity name back on to the end.

```<code>public class Box
{
    public long BoxId { get; set; }
    public virtual Process InputToProcess { get; set; }    /* ugly name */
    public virtual Process OutputToProcess { get; set; }   /* ugly name */
}
</code>```

Title: Inverse property naming (ORM scenario)

Body:
The rule I use quite often is to remove the plural and the subject from the original property name, then add "to". In your example, I would probably end up with:

public class Box
{
    public long BoxId { get; set; }
    public virtual Process InputTo { get; set; }    /* ugly name */
    public virtual Process OutputTo { get; set; }   /* ugly name */
}

Depending how I plan to use the property (i.e. whether it makes sense grammatically), I might add the obverse entity name back on to the end.

public class Box
{
    public long BoxId { get; set; }
    public virtual Process InputToProcess { get; set; }    /* ugly name */
    public virtual Process OutputToProcess { get; set; }   /* ugly name */
}


问:
Which according to you are the top languages to watch out for in 2011 and beyond?
Which according to you are the top languages to watch out for in 2011 and beyond?

This article  talks about 9 languages to watch out for in 2011. What are your views and inputs on this?

答:
Language popularity contests are always suspect.

AFAIK, the TIOBE index is based on something like averaged search hits for "[name of language] programming" on various sites, which completely misses the point. By that criterion, an article titled "Blub programming sucks balls" is a vote for Blub and "Blub++ programming has driven me insane; I just killed my dog." is a vote for Blub++.

There are more important things than how popular a given language is.

According to me, Lisp (lets say Common Lisp, to be specific), Haskell and Erlang are probably going to be interesting in the next little while. Lisp because some of the concepts it was pushing back in the 70s are finally getting explored in the mainstream, Haskell because it's a highly expressive language with focus on performance (through its optimizing compiler), and Erlang because it was built for programming networks of machines rather than individual computers (which seems like it'll get more and more useful as time goes on). Other than Haskell, I doubt many would agree with this assessment.

If you're merely talking about popularity, keep your eye on Python, Go and the .NET languages (before the Oracle thing, I'd have said Java too, but many Java devs seem to be spooked enough to jump ship lately).

ContentLicense: CC BY-SA 2.5


问:
When writing object-oriented code, should I always be following a design pattern?
Is there a conceivable design pattern for any object-oriented program? I ask this because recently I saw an implementation of a Door class with a Lock. It was part of a test and the answer said that the code is following the Null Object pattern:

class Lock
{
public:
    virtual void close() = 0;
    virtual void open() = 0;
    virtual bool is_open() const = 0;
    virtual ~Lock() { }
};

class DummyLock
    : public Lock
{
private:
    DummyLock();
    DummyLock(const DummyLock&) = delete;
    DummyLock& operator=(const DummyLock&) = delete;

private:
    void close() { }
    void open() { }
    bool is_open() const { return true; }

public:
    static DummyLock m_instance;
};

class Door
{
public:
    Door() : m_lock(DummyLock::m_instance) { }
    Door(Lock &lock) : m_lock(lock) { }

public:
    Lock& get_lock() const { return m_lock; }

private:
    Lock &m_lock;
};
```

This made me think: This code follows a good design pattern even though the description is so simple (this class is designing a door class with a lock), so if I am writing more complex code, should there always be some design pattern that I am following?

答:
Patterns are common solutions to common problems. We are always following some  patterns, the patterns by GoF address the most recurring ones. That, to have a shared understanding and shared approach known to software engineers.

That said, my answer is no, but yes you are always following some pattern of your own. As the GoF rightly puts it-

One person's Pattern is another person's primitive building block.

Great quote.


问:
Data Sync between Android apps in LAN
I am looking at developing an app which has quite an extensive database. This app will be installed on multiple devices in a LAN and all users can update the data and other users will  see the data as it is synced.

We can use the network subscribe and poll feature in android to find available services but I was wondering how best to sync. We could log swap, CRUD etc via a Restful API. But i was wondering if there is another way.

Especially when new devices join the LAN and need a brand new database update.

Thoughts? Thank you in advance.

答:
Data synchronization is a non-trivial problem.  If you are not familiar with how to do it in a 'standard' program, tackling it in this context may be beyond your design capabilities.  If you are familiar with data synchronization, the paper Data Synchronization Patterns In Mobile Application Design (McCormick and Schmidt from Vanderbilt) would probably be a good bit to read and build on your already existing knowledge (I'd also go and chase the references to other material that could be of use).

On the other hand, if you aren't familiar with data synchronization, you might want to instead look at using something that does it already.  Unfortunately, I don't have a deep set of knowledge for mobile design... but I have used a NoSQL database that does do replication / synchronization between databases - CouchDB.  This lead me to this article which is about mobile database synchronization with something called 'Couchbase Lite'.  The github repo for it starts out with the claim:

Couchbase Lite is an embedded lightweight, document-oriented (NoSQL), syncable database engine.

and the mobile portal for the database again states:

Supports peer-to-peer replication. By adding an extra HTTP listener component, your app can accept connections from other devices running Couchbase Lite and exchange data with them.

This may be an appropriate tool to use.  It is probably more reliable than rolling your own though it also means you're going to be using that database and having to fit to the way that it does things.

Title: Data Sync between Android apps in LAN


问:
What can slow a developer down?
What things tend to slow a developer down?

Please try to refrain from posting answers that:

are slow now but useful in the feature. (TDD, Refactoring, ...)

list a distraction.

答:
Oh this ones easy:

Meetings

More Meetings

Meetings about the last meeting

Meetings to prepare for the upcoming meeting

Developing a power point presentation for a meeting

Developing a power point presentation for a meeting discussing features that haven't been implemented, shouldn't be implemented, and for whatever reason that guy from sales will jump all over.  I can't predict what document you want displayed in the app based upon your current location without an internet connection or access to your hard-drive.  No really, just give up asking for it too.

Title: What can slow a developer down?


问:
Handling the process of large-scale lists
What are the efficient ways to process huge lists (+10 millions), and things to consider while manipulating huge lists.

First question, when should I use recursion, and when I shouldn't. In both cases, we are allocating memory to store data (the memory-complexity should be equal), using recursive approach with a huge list would be memory-consuming (stocking the call in Heap-memory), as well as storing data in a list (stack-memory). Which approach with less-cost? (usually we can write any recursive algorithm to iterative algorithm).

Second question, When it comes to memory-comlexity, should I think of transforming this list to other data structure (like LL, BST, .. to easily manipulate the data), The problem with such solutions is that the memory allocation in this case would be doubled (every node would have reference+node value instead of a value in a list).

Or should I think of hard-copying this list to disk (text-data or csv), and process the data by portion. The problem of this solution is that some operations demand the correlation between values, we can't process every portion independently, then reduce and concatenate the data.

Scenario 1: Sorting a huge list (Merge Sort(Recursive) Vs others  )

Scnario 2: let's consider this quick example (it's not the pefect and the most relevant to what I am trying to ask, but just to show another example).

We are adding product of 4 successive elements to every element of those four elements.

```<code>L=range(100)
from operator import mul
def prodElement(L):
    getItems= lambda i: L[i:i+4]
    list_mul=[]
    for i in xrange(0,len(L)-3,4):
        p=reduce(lambda x,y:x*y,getItems(i))
        L[i],L[i+1],L[i+2],L[i+3]= L[i]+p,L[i+1]+p,L[i+2]+p,L[i+3]+p
    return L

def prodElement_rec(r,L,i=0):
    if i>=len(L)-1: #Stop
        return res
    else:
        if i%4==0 or i==0:
            p= L[i]*L[i+1]*L[i+2]*L[i+3]
            L[i],L[i+1],L[i+2],L[i+3]= L[i]+p,L[i+1]+p,L[i+2]+p,L[i+3]+p
            return prodElement_rec(r,L,i+4)
res=[]
assert prodElement_rec(res,L)==prodElement(L)
</code>```

Again, I am not trying to solve a specific issue, but am trying to understand the best approaches to be used when it comes to huge lists (+10 millions items). What are the methods that I should think of, and critical issues that I should avoid in order to solve problem using huge lists.

答:
In the current form your question is likely to be closed as "too broad", but since you asked in this broad form, I try to give you a broad answer:

recursion: don't use recursion when the expected recursion depth will be in the order of magnitude of your list's size. Especially when your programming language does not optimize tail recursions automatically (Python does not). And assumed your recursion depth stays reasonable: use it only when it makes the code simpler and easier to understand. In your example above, the recursion depth will be about "list size /4" (which will probably end in a stack overflow when your list size is as large as you wrote), and the code is definitely not simpler than the non-recursive variant.

writing data to disk: do this only when you expect to exceed the available main memory of your system (which means the memory available to your program). This will imply the need for a so-called external algorithm for the give task, which is almost always more complicated than using in-memory algorithms. So do this only if you must. EDIT, due to the comment above: using a database is a good alternative for a lot of scenarios. This will introduce some additional programming overhead on one hand, but can save a lot at the other.

which data structure to use: start with the most simplest data structure which is suitable for the given task, and then measure your performance (maybe with smaller lists first, but be sure you know the approximate order of growth of your algorithm's runtime  when you start extrapolating for bigger lists). Only when your code does not run fast enough, try more complex data structures and algorithms (and don't forget to measure again).

To sum it up: it depends on what you are going to do with that lists, and your memory and time constraints.


问:
Redis strategy for cache item dependency
I'm implementing cache structure using Redis, my domain is like this:

There are multiple categories (3000+ categories). Each category contains multiple questions (around 20-30 questions per category). Each question has several properties like whether it's published, what's the type, etc

When loading the questions, I'll need to load questions from several categories and with some question filers specified by user that matches question properties: is published, type, etc

I implement this in Redis using string and set:

Each question is stored as string in Redis (serialized JSON) with key: "question:[QuestionId]"

Each category has list of question ids belonging to it (Redis set) with key: "category:[CategoryId]:questions"

For each category, each property filterable by user has its own set of question id (Redis set) e.g. published questions under category 1 has key: "category:1:questions:ispublished

When loading the questions, I just need to based on the filters provided by user, do the intersect of set in Redis to find relevant question ids and load those questions

So each category will have several cache items associated with it:

category:[CategoryId]:questions

category:[CategoryId]:questions:ispublished

category:[CategoryId]:questions:notpublished

category:[CategoryId]:questions:type:1

category:[CategoryId]:questions:type:2
etc

This is working fine. But the challenging is to maintain consistency of cache items when there's eviction.
Let's say if Redis cache decides to evict "category:[CategoryId]:questions:notpublished" cache item, how do i make sure all other cache items related to that category id also invalidated? I can do the checking of all the filters cache item to make sure they exist in cache before loading the questions, but that will require a lot of requests to Redis. Or any other strategy/way to solve my problem? I'm new to Redis and this is the first time I implement this type of cache structure in Redis

At the moment what I do is I just check for "category:[CategoryId]:questions" key. If it doesn't exist then I load data from database and set all cache items for that category. But it cannot detect if any other key is missing

答:
You can attack this issue from a couple of angles:

You can choose an eviction policy that will not evict those keys, e.g, eviction policy volatile-lru and set those keys without expiration. (more on eviction policies)

The issue here is that you might get OOM if there are no keys that can evict.

The second approach is to set an eviction listener, you can use the notify-keyspace-events to make redis publish keyspace and keyevent notifications. (more on key notifications)

The following command will make redis publish evictions on it keyspace notification channel
redis-cli config set notify-keyspace-events Ke

And the following command will establish a connection subscribed to all redis notifications:
redis-cli --csv psubscribe '__key*__:*'

This is clearly just an example of getting it done with redis-cli, you should implement it as a separate thread in your application that deletes all evicted key related data from your dataset.


问:
How to do Test Driven Development
I have just 2+ years of experience in application development. In those two years my approach towards development was as following

Analyze requirements

Identity Core component/Objects, Required functions, Behavior, Process and their constraints

Create classes, relation between them, constraints on objects behavior & states

Create functions, process with behavioral constraints as per requirements

Manually test application

If requirement changes modify component/functions, then manually test application

Recently I got Introduced to TDD and feel that this is very good way to do development as developed code has strong reason to exists and lot of post deployment issues are mitigated.

But my problem is I am not able to do create tests first, Rather I am identifying components and just writing test for them before I actually write components. my question is

Am I doing it is right? If not what exactly I have to change

Is there any way you can identify whether test you have written are enough?

Is it good practice to writing test for very simple functionality which might be equivalent to 1+1 = 2 or is it just an overplay?

Is it good to change functionality and accordingly test if requirement changes?

答:
Am I doing it is right? If not what exactly I have to change

It's hard to say just from that short description, but I suspect that, no, you are not doing it right. Note: I am not saying that what you are doing doesn't work or is in some way bad, but you are not doing TDD. The middle "D" means "Driven", the tests drive everything, the development process, the code, the design, the architecture, everything.

The tests tell you what to write, when to write it, what to write next, when to stop writing. They tell you the design and the architecture. (Design and architecture emerge from the code through refactoring.) TDD is not about testing. It isn't even about writing tests first: TDD is about letting the tests drive you, writing them first is just a necessary prerequisite for that.

It doesn't matter whether you actually write the code down, or have it fully fleshed out: you are writing (skeletons of) code in your head, then writing tests for that code. That's not TDD.

Letting go of that habit is hard. Really, really hard. It seems to be especially hard for experienced programmers.

Keith Braithwaite has created an exercise he calls TDD As If You Meant It. It consists of a set of rules (based on Uncle Bob Martin's Three Rules of TDD, but much stricter) that you must strictly follow and that are designed to steer you towards applying TDD more rigorously. It works best with pair programming (so that your pair can make sure you are not breaking the rules) and an instructor.

The rules are:

Write exactly one new test, the smallest test you can that seems to point in the direction of a solution

See it fail; compilation failures count as failures

Make the test from (1) pass by writing the least implementation code you can in the test method.

Refactor to remove duplication, and otherwise as required to improve the design. Be strict about using these moves:

you want a new method—wait until refactoring time, then … create new (non-test) methods by doing one of these, and in no other way:

preferred: do Extract Method on implementation code created as per (3) to create a new method in the test class, or

if you must: move implementation code as per (3) into an existing implementation method

you want a new class—wait until refactoring time, then … create non-test classes to provide a destination for a Move Method and for no other reason

populate implementation classes with methods by doing Move Method, and no other way

Typically, this will lead to very different designs than the oft-practiced "pseudo-TDD method" of "imagining in your head what the design should be, then writing tests to force that design, implement the design you had already envisioned before writing your tests".

When a group of people implement something like a tic tac toe game using pseudo-TDD, they typically end up with very similar designs involving some kind of a Board class with a 3×3 array of Integers. And at least a portion of the programmers will actually have written this class without tests for it because they "know that they're gonna need it" or "need something to write their tests against". However, when you force that same group to apply TDD As If You Meant It, they will often end up with a wide diversity of very different designs, often not employing anything even remotely similar to a Board.

Is there any way you can identify whether test you have written are enough?

When they cover all the business requirements. Tests are an encoding of the system requirements.

Is it good practice to writing test for very simple functionality which might be equivalent to 1+1 = 2 or is it just an overplay?

Again, you have it backwards: you don't write tests for functionality. You write functionality for tests. If the functionality to get the test to pass turns out to be trivial, that's great! You just fulfilled a system requirement and didn't even have to work hard for it!

Is it good to change functionality and accordingly test if requirement changes?

No. The other way round. If a requirement changes, you change the test which corresponds to that requirement, watch it fail, then change code to make it pass. The tests always come first.

It is hard to do this. You need dozens, maybe hundreds of hours of deliberate practice in order to build up some sort of "muscle memory" to get to a point, where when the deadline looms and you are under pressure, you don't even have to think about it, and doing this becomes the fastest and most natural way to work.

Title: How to do Test Driven Development


问:
Handling generated files in a Visual Studio Project
I have a Visual Studio Project that is using a MSBuild task to generate some code files. (The basis are xml files, and the generated code is quite lengthy, but noting special, just a lot of boilerplate.)

I’m not sure how I should handle the generated files:

Not include generated files in the project, and use MSBuild to make sure they get compiled (by adding respective <Compile...> tags to the <Target>).

Include generated files in the project, but exclude them from source control.

Any other options? Are there issues with these options? Experiences so far? Recommendations or best practices?

答:
Personally I include only the source files WRT source control. Its a rare case when generated files should be added to source control - maybe if they were generated once and never changed, and the generation step is lengthy or complex, otherwise I can't think of a good reason.

For compilation - if they need to be added to the project then I tend to add them - I prefer not to have hidden compilation files as part of the project as I prefer to know what its really building without any surprises. I do tend to put generated files in a filtered folder though so they are tucked away from daily view though.


问:
Extracting first and last name from a single name field
I'm working with the Twitter API which provides only a single field called name, which includes the full name of a person.

The application that we're constructing requires a first name and a last name.

Now my question is how I am able to extract the first and last name from a single name field.

I know that I can simply just split or explode the string but this won't work if the person for example has first name which consists of more than one word.

答:
There are lots of simple ways of doing this wrong - read this to see why. There is no way of getting it right programmatically.

That said, some of the wrong ways are not that bad, all things considered. If you can live with making occasional errors and correcting them with a list of exceptions after users notify you, then naive splitting on white space might be the right thing to do. But you must exercise your judgement whether that's the right trade-off for your application.


问:
Control (avoid) changing fields with side-effects
I have been thinking about a design problem and possible solutions in my own. I am pretty sure I am not the first one to have noticed it, but I cannot google for it since I do not know the standard naming of the different participants.

It is NOT the state pattern.

My problem is that, when dealing with ORM, I often end with something like that

```<code>Employee
--------
Id
Name
Surname
BirthDate
DefunctionDate
</code>```

And using an Object Relation-Mapping (in my case JPA), I end with two entities, Employee and Contract.

Now, most of the fields of Employee are just "intranscendent"(*1). It really does not affect the application if the Employee's name changes from 'John' to 'Mike'. As long as I put some validation for the input fields. But if, say, defunctionDate changes from null to some date, some logic must be executed (for instance, closing the current contracts, revoking system access, etc.). I would call those terms "transcendent"(*1).

The first step would be add an specific operation which sets such field setDefunctionDate and handles such logic, and I am ok with that. The problem that appears is how to ensure that the fields are not updated when updating "cargo" data.

I see three "easy" options:

Ignore changes in a bean: If I have an update(Employee employee) method, then each time the method is executed I should retrieve the object from DB and set the "transcendent" field(defunctionDate) of the incoming object with the value from the object stored in the DB. That "retrieve the object from DB" means one or several extra accesses to DB, which are not a good thing. Also, this has issues when there is cascading of the changes.

"Observer" pattern: Like 1., but in this case a modification is found in a "trascendental" change a listener that handles the extra logic is fired.

Another possible solution is having a method for each field in the entity, but I think this will usually be too verbose, and will break the purpose of having an ORM.

Of the previous options, I thing 2) would be the best, but I still do not like the fact of the extra DB accesses even when no trascendent field has been changed.

The only solution I can think of would be moving those "trascendental" fields to a separate entity, which would be in a one-to-one relationship with the original entity. Something like

```<code>Employee
--------
Id                   Employee_Trascendent
Name       --------> ---------
Surname              Employee_Id
BirthDate            DefunctionDate
</code>```

The API would only allow direct modification of the Employee entity, and DefunctionDate would only be modified by an specific API method.

That said, I find my solution a bit overcomplicated and, since I cannot see any reference to anything similar, I think that maybe I am missing some more obvious solution.

I would like your help to determine the correct terms to search ideas for and, if why I propose has a name, its name.

*1: If you know a better term please tell me it, remember I do not know the proper terminology.

答:
As I see it, the ORM doesn't create the side effects, your code does.  If you ask an ORM to save an entity, it does so, without performing additional operations, or should there be a database trigger of some sort, in my personal opinion you should remove it in favor of having more control in your program.

As such, don't worry about saving your entity multiple times (perhaps once in creation of an Employee once you know first name, last name, birth date, etc., then later in a later step).    If your program handles input of this information in multiple steps, then it should be saving as you go along.  The stress that you put on the database is only slightly more than it would be otherwise, and look what you gain in exchange:  stability and simplicity.  These are two commodities worth far more than performance and I would choose to have a stable and simple program with a slight performance hit over a fast instable and complicated program any day of the week.

I suggest that you use option 4.  You have one dbo section in your program that performs the actual duty of saving an Employee.  It gets accessed from different areas of your program, namely when you need to update information on an Employee that won't create side effects, and when you need to update information on an Employee that will create side effects.  In the latter case, you should perform all side effects in a transaction such that should the side effects or actual save of Employee fail, nothing is done.

The dbo should only provide the means to perform the save in its own transaction or as part of another transaction, but it should not know what side effects result from saving Employee.

I hope that answers your question.


问:
Should we use data object (or the data transfer object) for sharing data between these three classes?
I found an article by Martin Fowler that has made me doubt my design choices, particularly about data objects. Martin Fowler has written an article about what he thinks is a code smell.

In this article, he says:

The best smells are something that's easy to spot and most of time lead you to really interesting problems. Data classes (classes with all data and no behavior) are good examples of this. You look at them and ask yourself what behavior should be in this class. Then you start refactoring to move that behavior in there. Often simple questions and initial refactorings can be the vital step in turning anemic objects into something that really has class.

Now, on to my own use case of data classes/objects/DTOs/whatever. :-)

I am writing a set of classes that move credits from our company's sim to the sim of a recipient. This process has three stages:

Validation: at this stage, the data is validated – have we moved credits to this person's account before? Have we handled this item before? Can we retry, or have we reached the "manual mode" threshold?

Process: at this stage, we do the actual work of moving the credits from one account to the other. We use the objects retrieved in the validation phase, to lower the number of queries to the database, and also to improve our application's performance.

Post-process: at this point, we check the data and if the data must be auto-corrected (I.E. the user has entered wrong information and we know how to automatically fix it), we mark it for autocorrection.

Now, the items 2 and 3 are using a lot of data that is retrieved or initialized in stage 1: the event manager, the order and payment and transaction objects, and so on. What we do is the following:

The validation object stores all of its retrieved data that is useful to the rest of the process in a data transfer object (DTO). This object has only setters and getters.

The rest of the classes (the process class and the post-process class) accept the DTO as their constructor argument and do their processing, event management, and data manipulation on those objects. In the end, those objects are persisted in the database.

Is the data object (or the data transfer object) not recommended here? Should we use another way for sharing data between these three classes?

答:
Should we use another way for sharing data between these three classes?

No, that is not the point of what Fowler is talking about. The usage of a DTO is probably fine (Fowler himself recommends it, especially in a remote scenario). The point is that during refactoring, such a DTO might become a better place for operations which work exclusively on the data stored within the DTO (that actually does not mean to put the whole validation, processing and post-processing code in there).

Candidates are typically operations which might be reused in more than one of the steps you described above. Another indicator is when you start implementing something like a FooDTOManager class for a specific class FooDTO, instead of implementing the operations directly in FooDTO. What you should consider is the name your give to the DTO - it will ideally express some kind of abstraction and some kind of responsibility.  Use this responsibility as a guideline when deciding about which operations you put into the DTO, and which not.

However, if the only responsibility of your DTO objects (currently) is to transfer some data from step x to step y, then leave it as it is. Later, when your program evolves, you might find operations which may be suited as operations for this DTO - if there are currently none, it is ok, don't start to seek for a different solution.


问:
Would you use C, today, for a software project?
If yes, where and why would you use it?

If no, please provide an explanation to why C is not acceptable to you.

答:
Yes, but depends on project. C is very good for some low-level projects or part of biggest solution.

Eg. For bussines logic ok, but not for user interface.


问:
Program Compatibility - OS That Can Run Anything?
I know that programs that are built on one OS won't work on another, like a Windows program on a Linux distribution, and that there are programs that translate those system calls into system calls that the current OS can read (Wine for Linux). However would it theoretically be possible for there to be an OS that can understand the original system calls for programs built for the three main OSes (Windows, Linux, and Mac OS X)?</p>

答:
The thing is, MACs and PCs are fundamentally different hardware, in terms of CPU architecture. Compilers, for that matter, are nothing more than translation tools that rewrite your code from an abstract high-level programming language to low-level "words" (actual groups of bits) that the processor is reading and executing inside its logical hardware architecture. Under these circumstances, what you're suggesting would be like having someone who doesn't even know Latin is (was) a language, do complex mathematical operations using Latin numerals.

There are some approaches to the issue of cross-compatibility - for example, the Java Virtual Machine (JVM) is a piece of software that in itself depends on the architecture and OS of the machine on which it resides, but offers at the other end an "interface" to the CPU, hardware and system components, that is the same across all architectures, empowering Java applications to behave the same in various environments.

The issue with this, however, is that the translation layer offered by the JVM must use additional resources and do extra processing besides just the instructions in your application, in order to translate the instructions into the language that the native CPU understands - thus degrading the overall performance.


答:
Windows NT was specifically designed to support multiple OS "personalities". In fact, it originally wasn't even intended to be a drop-in replacement for Windows and DOS, it was intended as a drop-in replacement for OS/2!

On Windows NT, applications aren't written against the NT kernel, instead they are written against an OS personality, which in turn sits on top of the NT kernel. The original Windows NT shipped with 4 personalities: Win32/WinNT, DOS/Win16, OS/2, and Unix. This meant that you could not only run Windows NT applications, you could also run DOS applications, OS/2 applications, and even Unix applications unmodified. Nowadays, the OS/2 personality is removed, and the Unix personality is shipped separately.

Many Unix systems have similar facilities. In the beginning, when Linux was "the new kid on the block", Linux needed to be able to run applications for other Unices if it wanted to be viable. During that time, support for adding foreign Unix applications was added to Linux, for example Intel developed iBCS, which allowed Linux systems to run all sorts of Unix applications (Solaris, 386BSD, FreeBSD, NetBSD, BSDI/386, SVR4 (Interactive, Unixware, USL, Dell etc.), SVR3 generic, SCO, SCO OpenServer 5, Wyse V/386, Xenix V/386, Xenix 286). There's even the binfmt_misc module, which allows Linux to run applications written against arbitrary ABIs, by handing them off to a userspace program which interprets them.

Nowadays, it is the other way around: Linux is the established player, and the other Unices implement ABI compatibility with Linux. HP/UX, IBM AIX, FreeBSD, and many others all can run Linux applications unmodified.

It would be pretty easy for Apple to develop an OSX personality for Windows NT. It would also be possible for Microsoft to develop a version of Windows NT that runs as a personality on top of Mach alongside OSX. Whether those companies would do that is a totally different matter, though.

Title: Program Compatibility - OS That Can Run Anything?

Body: I know that programs that are built on one OS won't work on another, like a Windows program on a Linux distribution, and that there are programs that translate those system calls into system calls that the current OS can read (Wine for Linux). However would it theoretically be possible for there to be an OS that can understand the original system calls for programs built for the three main OSes (Windows, Linux, and Mac OS X)?</p>


问:
try/catch open/closed principle violation
I have three or more different custom exceptions that a class can throw and I need to use try/catch in order to discover which exception was thrown.

In my point of view this piece of code violates the Open/Closed principle, because if we look the definition we see:

"software entities (classes, modules, functions, etc.) should be open
  for extension, but closed for modification"

```<code>try {
    // something that throws
} catch (const FooException& e) {
    // ...
} catch (const BarException& e) {
    // ...
} catch (const BizException& e) {
    // ...
} catch (...)
{
    // ...
}
</code>```

What if I need to catch another exception? I will need to insert another catch statement, right?

Is there another way for doing this? Or the language is somehow forcing me to violate the principle?

答:
That depends on how you plan to recover from these exception, meaning what code is executed in the catch statements.
If it's the same for all 3 exceptions, you could create a superclass for them and catch the superclass. If your method has to throw a new exception, just make it extend the superclass and it would still be caught by the caller and would not need any changes in the client code.

Generally tough, if a method throws that many exceptions it's usually a hint that the method does to much and you might want to consider refactoring it.

If you want a more detailed answer, it would be helpfull to see a complete code listing of your method.


问:
DDD, modularizing the application and domain layers without breaking the DIP
Quoting DDD theory:

The application layer is thin in terms of domain logic - it merely
  coordinates the domain layer objects to perform the actual work.

When it comes to modularization, and assuming that the module containing the domain entities and the interfaces of the domain services belongs to the domain layer, the application layer depends on the domain layer, which breaks the dependency inversion principle.

The implementation of the high-level component's interface by the low
  level component requires that the low-level component package depend
  upon the high-level component for compilation, thus inverting the
  conventional dependency relationship.

What am I missing?

I add an UML diagram to clarify the problem I see.

The Persistence Layer depends upon an abstration in the Domain Layer
-> DIP ok!

The Application Layer depends upon an abstraction in the Domain Layer -> Does this break the DIP?

答:
The Dependency Inversion Principle has one major exception: At some point you must do something concrete. An example is in order.

Let's say you've got a Blogging application. You've got two tables in the database, and two domain models, say Blog and Post. Let's also say you are working with an MVC framework like ASP.NET MVC, Ruby on Rails, etc.

Now, let's say you've got another class called BlogPostsController implementing the basic CRUD operations for blog posts.

The framework implements the Dependency Inversion Principle by not hard coding the following lines anywhere in its code base:

```<code>new BlogPostsController();
</code>```

The framework looks at the incoming URL and constructs the name of the controller class dynamically. The framework doesn't have a hard dependency on your BlogPostsController class.

Now, let's look at the controller. Inside your controller you see new Post() peppered all over. This is not a violation of the Dependency Inversion Principle because at some point you, as a programmer, need to actually save a blog post to the database.

The Dependency Inversion Principle is mainly aimed at dependencies that aren't laser focused on the basic intent of a class, for instance creating a new "controller" in an MVC framework. You don't want a hard coded switch or if statement in order to do that. Authentication is another area where DIP is important because your BlogPostsController class shouldn't care how browser cookies are handled, or if the user logs in using a custom login page wired to a Database, or using Windows authentication or plain text authentication in the browser wired to LDAP behind the scenes.

Body:
The Dependency Inversion Principle has one major exception: At some point you must do something concrete. An example is in order.

Let's say you've got a Blogging application. You've got two tables in the database, and two domain models, say Blog and Post. Let's also say you are working with an MVC framework like ASP.NET MVC, Ruby on Rails, etc.

Now, let's say you've got another class called BlogPostsController implementing the basic CRUD operations for blog posts.

The framework implements the Dependency Inversion Principle by not hard coding the following lines anywhere in its code base:

new BlogPostsController();

The framework looks at the incoming URL and constructs the name of the controller class dynamically. The framework doesn't have a hard dependency on your BlogPostsController class.

Now, let's look at the controller. Inside your controller you see new Post() peppered all over. This is not a violation of the Dependency Inversion Principle because at some point you, as a programmer, need to actually save a blog post to the database.

The Dependency Inversion Principle is mainly aimed at dependencies that aren't laser focused on the basic intent of a class, for instance creating a new "controller" in an MVC framework. You don't want a hard coded switch or if statement in order to do that. Authentication is another area where DIP is important because your BlogPostsController class shouldn't care how browser cookies are handled, or if the user logs in using a custom login page wired to a Database, or using Windows authentication or plain text authentication in the browser wired to LDAP behind the scenes.


答: Yes, of course. I would use C for writing performance critical pieces of system or low level communication parts. For example I would use C for writing NIFs in Erlang project just because it is The Right Tool(tm) for this sort of job. Or I would use C for writing similar parts (XS) in Perl project.</p>

Title: Would you use C, today, for a software project?

Body:
If yes, where and why would you use it?

If no, please provide an explanation to why C is not acceptable to you.


答:
If you just want to log each exception - in some way depending on its specific type, you can split that concern out into a dedicated exception logger.

First, you need a base type - let's assume you just subclass std::exception. Now, your main code can just be:

```<code>try {
    // something that throws
} catch (const std::exception& e) {
    ExceptionLogger::log(e);
    throw;
}
</code>```

Have the log method use dynamic_cast to handle all the specific subtypes it knows, and you have just one place to modify when a new exception type is added.

NB. I made log a static method here, but you could reasonably have a local (or data member, or ...) ExceptionLogger instance configured differently per component, connected to a different output/target logger, etc. etc.

There are essentially two implementation options for the log method itself:

hand-craft something that knows each derived type, and what to do with it. This can use dynamic_cast explicitly:

```<code>void ExceptionLogger::log(std::exception const &ex) {
  if ((FooException const *e = dynamic_cast<FooException const *>(&ex))) {
    // handle foo
  } else if ((BarException const *e = dynamic_cast<BarException const *>(&ex))) {
    // handle bar
  } // else ... etc.
}
</code>```

(as you probably noticed, this is actually uglier than the original code, so all we've done is de-couple it from the code you didn't want to modify), or you can move exactly the same try/catch arrangement out of your function - just re-throw in the try block.

Write a generic typeid-based dispatcher, so you can de-couple the per-exception-type code from both your original function and the dispatcher. This is a form of ad-hoc visitation (you're essentially writing a visit method for each interesting subclass of std::exception). Now, you can register each new handler externally, without changing either your original code or the ExceptionLogger itself.

Title: try/catch open/closed principle violation

Body:
I have three or more different custom exceptions that a class can throw and I need to use try/catch in order to discover which exception was thrown.

In my point of view this piece of code violates the Open/Closed principle, because if we look the definition we see:

"software entities (classes, modules, functions, etc.) should be open
  for extension, but closed for modification"

```<code>try {
    // something that throws
} catch (const FooException& e) {
    // ...
} catch (const BarException& e) {
    // ...
} catch (const BizException& e) {
    // ...
} catch (...)
{
    // ...
}
</code>```

What if I need to catch another exception? I will need to insert another catch statement, right?

Is there another way for doing this? Or the language is somehow forcing me to violate the principle?

Body:
If you just want to log each exception - in some way depending on its specific type, you can split that concern out into a dedicated exception logger.

First, you need a base type - let's assume you just subclass std::exception. Now, your main code can just be:

try {
    // something that throws
} catch (const std::exception& e) {
    ExceptionLogger::log(e);
    throw;
}

Have the log method use dynamic_cast to handle all the specific subtypes it knows, and you have just one place to modify when a new exception type is added.

NB. I made log a static method here, but you could reasonably have a local (or data member, or ...) ExceptionLogger instance configured differently per component, connected to a different output/target logger, etc. etc.

There are essentially two implementation options for the log method itself:

hand-craft something that knows each derived type, and what to do with it. This can use dynamic_cast explicitly:

void ExceptionLogger::log(std::exception const &ex) {
  if ((FooException const *e = dynamic_cast<FooException const *>(&ex))) {
    // handle foo
  } else if ((BarException const *e = dynamic_cast<BarException const *>(&ex))) {
    // handle bar
  } // else ... etc.
}

(as you probably noticed, this is actually uglier than the original code, so all we've done is de-couple it from the code you didn't want to modify), or you can move exactly the same try/catch arrangement out of your function - just re-throw in the try block.

Write a generic typeid-based dispatcher, so you can de-couple the per-exception-type code from both your original function and the dispatcher. This is a form of ad-hoc visitation (you're essentially writing a visit method for each interesting subclass of std::exception). Now, you can register each new handler externally, without changing either your original code or the ExceptionLogger itself.


问:
Null Object Pattern and Input validation - copy real implementation or silently accept everything?
I have a WifiComponent in my Camera in my client application. It's responsible for handling the Wifi-related functionality of the Camera. The Camera represents a real world camera.

This WifiComponent can either be enabled (in which case I can do things with it, like checking connection status and scanning) or disabled (in which case you can't do anything with it at all, other than asking whether it's enabled).

When creating a Camera in my client application, I ask the camera whether its WifiComponent is enabled. Then I construct the appropriate subclass of WifiComponent, either WifiComponentImpl or NullWifiComponent.

Implementing the supportedWifiTypes() and wifiScan() methods are easy. The NullWifiComponent doesn't support any types, is instantly done with scanning and finds no results.

But now I have to implement a bool connect(WifiNetwork network, String password) method.
I want to say that I failed to connect... But I don't even support the WifiEncryptionType provided in the WifiNetwork! The real implementation throws an IllegalArgumentException if you pass it an unsupported WifiEncryptionType wifi network.

Do I...

Throw IllegalArgumentException, because I don't support the WifiEncryptionType requested?

Silently fail to connect (return false), no matter what's provided?

Generalized question:

If the real implementation fulfills a contract, and part of this contract is to throw exceptions for certain inputs, should a null-implementation prioritize its neutrality or the contract?

答:
As the null-implementation is supposed to be a drop-in replacement for the full-functional implementation, the null-implementation should fully adhere to the interface that it implements.

If the WifiComponent interface specifies that connect() throws an exception if it gets invoked with an unsupported WifiEncryptionType, then that is exactly what your null-implementation should do, especially if the application must use the same WifiComponent interface to learn which WifiEncryptionTypes are supported.

If the list of supported WifiEncryptionTypes doesn't come from your null-implementation, then your null-implementation should only throw an exception if a functional implementation is also required to throw it.

If the WifiComponent interface doesn't specify that an exception must be thrown, then it is better to assume the value would be acceptable to a functional implementation and report a generic connection failure (return false).


问:
Could we drop support for Android native browser on our web site?
I work with an interactive web portal that has a few single-page apps and complex html structure. The aim is to support all browsers that our customers use. We have implemented responsive web design to handle mobile platforms. We test on multiple platforms (mobile and desktop) to make sure that it works everywhere.

I recognise that this is a goal that is difficult to reach, especially for customers that use uncommon browsers. However, the browser (or browsers) that has given us the most grief lately is the native browser on Android phones and tablets. We suffer copied canvases, strange phenomena where the user cannot click on html elements that are close to the edge of the screen, formatting issues that are difficult to understand and/or fix, and other things.

Also, debugging on the native browser is cumbersome since you can't easily log from javascript using console.log.

My thought is basically that I want to ignore the native Android browser while testing, and bugs that show up only on the native Android browser in production will not get fixed. Is that a bad thing? Do people in general expect to be able to use their native Android browser to handle advanced web pages? I realize that there are a lot of Android users about, but perhaps they're not as used to working with complex web sites compared to other platforms? Will users understand if we recommend them to install Chrome to be able to use parts of our web site?

答:
Based on some research, I dug up some statistics for which browsers are most common in mobile users at this URL

The most popular browsers, determined by Web pages visited are: Android with 25.5 percent; iPhone with 21.4 percent; Chrome with 15.6 percent; Opera with 12.3 percent; UC Browser with 11.1 percent, according to StatCounter (April 2014).

Also you need to look at your own internal statistics on whether your users use a certain type of mobile browsers before you make a decision. I would advise to drop support for the native browser and just ask your users to download the Chrome or Firefox browser. I would give your users a choice because if they use Chrome they are more likely to be tracked by Google than if they used Firefox.

Please do more research before you make your decision because this is something that will effect your users' experience and your business.


答:
I think Phil's answer should get accepted in the end because it contains the best info. But to just answer your Is there another way for doing this? question specifically: here is another way which seperates the exception handling part pretty well, though it depends on the exact situation how usefull it is

```<code>template< class Fun >
void TryCatch( Fun f )
{
  try {
      f()
  } catch (const FooException& e) {
      // ...
  } catch (const BarException& e) {
      // ...
  } catch (const BizException& e) {
      // ...
  } catch (...)
  {
      // ...
  }
}

void DoSomething()
{
  TryCatch( []()
    {
      //do something
    } );
}
</code>```

Body:
I think Phil's answer should get accepted in the end because it contains the best info. But to just answer your Is there another way for doing this? question specifically: here is another way which seperates the exception handling part pretty well, though it depends on the exact situation how usefull it is

template< class Fun >
void TryCatch( Fun f )
{
  try {
      f()
  } catch (const FooException& e) {
      // ...
  } catch (const BarException& e) {
      // ...
  } catch (const BizException& e) {
      // ...
  } catch (...)
  {
      // ...
  }
}

void DoSomething()
{
  TryCatch( []()
    {
      //do something
    } );
}


问:
Is it possible to programmatically attach custom metadata to phone calls?
I'm trying to determine if it should be possible for a cell phone app to relay custom data along with a phone call. By "should be possible" I mean that I'm not trying to learn how to do it in iOS/Android/whatever, I'm just trying to determine if:

It is permitted by standards: the standards for the metadata that initiates a phone call allow for it to be extended. (I found all kinds of information about high level phone call APIs and CDRs which are kept after a phone call is made, but nothing in the "this is the data header that leaves your phone when you make a call" category).

I can be sure that my custom data will be forwarded intact by the cellular network nodes.

This type of functionality is typically available to apps (from my research: some cellular functionality is implemented by firmware, other functionality has legal issues and its APIs are restricted to privileged users).

In short, what I would ideally like to hear is something along the lines of:
"When you initiate a phone call, the phone generates this header. This part of the header can be used to send custom data, and cellular network nodes won't mess with it. The API for this should be available; for example on iOS/Android/whatever we have xyz()".

答:
So I went and looked at 3GPP TS 24.008 and I found :

For mobile stations supporting eMLPP basic calls may optionally have an associated priority level as defined in
  3GPP TS 23.067 [88]. This information may also lead to specified qualities of service to be provided by the MM sublayer.

That led me to http://www.scribd.com/doc/59337149/Enhanced-Multi-Level-Precedence-and-Preemption ; it appears that this feature already exists. Finding a network that will let you use it is probably another matter.

The actual payload messages are right there in the 3GPP document, e.g. p371 "Table 9.70a/3GPP TS 24.008: SETUP message content (mobile station to network direction)". It looks at first glance there may be exploitable fields for mobile-mobile calls such as the "user-user" field.

It is pretty much guaranteed that you won't be able to alter these messages without hacking the baseband software of your mobile phone. Doing so will invalidate its network certification. It definitely will not be available to apps.


问:
How do browsers paint a render tree to the screen?
I'm interested in building a browser-like rendering engine. I understand a bit about how OpenGL and GUI toolkits work. But how do browsers actually put pixels on the screen? Are they like software rasterizers that scan every line and paint whatever's in the render tree? Or do they act like GUI toolkits and call functions to display elements at certain coordinates? Are there any libraries that focus specifically on the painting portion of the browser's critical rendering path?</p>

答:
At the very bottom level, the browser will request a window from the GUI toolkit and use its painting functions to draw in them.

At the middle level, there is a rendering engine which takes a DOM and turns it into draw commands, such as Mozilla's Gecko or the popular "Webkit".

See also this talk: https://stackoverflow.com/questions/3154753/how-does-gecko-or-any-other-layout-engine-render-a-document-page?rq=1


问:
How to propagate data changes between dev, qa, and production
I have tools for propagating database definition changes, but any data changes I make I write scripts for and run them in each environment by hand.

There are some data changes/additions that have to be made routinely and I would like to create a GUI for handling this, but if I did that then I no longer have the sql scripts to run in other environments (unless I generate them from the GUI tool, but then I'm still left having to run those changes by hand in other environments).

One idea I'm mulling over is to write the GUI tool in such a way that it generates the xml files for objects I've added or changed and include these xml files in the publication of the web project. Then the application can look at these xml files and update the database accordingly.

Are there any standard practices or tools for pushing data changes automatically along with your db definition and/or code changes?

EDIT:

Based off the first answer I received it appears like I might have made it sound as though I want a tool to compare dev databases to production databases and propagate all changes. This is DEFINITELY NOT what I was trying to communicate.

One example of what I'm dealing with is language texts that have to be added (no, I can't use resource files for this because end users can modify the texts through the application at runtime). Instead of having to hand write scripts every time I need to add texts for a new item, it would be great if I could just create a GUI tool to simplify the process.

I think it's pretty obvious why I would prefer to use a GUI over hand writing SQL statements, and so the next question is why would I want to propagate this the same way we propagate code changes. Well, this isn't like other test data. This is data that will ALWAYS be propagated to each environment. The same sort of concerns that lead us to use tools to simplify the process of pushing code or database changes to each environment apply to the kind of data I'm talking about here.

答:
If you need a way to create reproducible changes to a database, GUI tools are often not the best possible approach. When you change something using a GUI tool, the GUI sometimes can only guess how the change was meant "in general". In SQL however, you can express the exact rules of change you have in mind - and it gives you the ability to push the changes into version control, test the changes and debug them when the test shows up an issue. And, as you noted by yourself, they provide a reproducible solution for your QA and Production environment.

So the first thing you should ask yourself is: do you really need a GUI tool.

However, when you think you have too much tedious work to do with every change, you may buy yourself a schema comparison tool (see here for some suggestions, there are different tools for different DBMS). Those tools can probably help you to compare different versions of your dev database schemas and may safe you some effort in creating the SQLs for your QA and prod environment.


问:
MVC pattern synchronisation
I am facing a problem in synchronizing my model and view threads

I have a view which is table. In it, user can select a few rows.
I update the view as soon as the user clicks on any row since I don't want the UI to be slow.
This updating is done by a logic which runs in the controller thread below.

At the same time, the controller will update the model data too, which takes place in a different thread. i.e., controller puts the query in a queue, which is then executed by the model thread - which is a single-threaded interface.

As soon as the query executes, controller will get a signal.

Now, In order to keep the view and model synchronized, I will update the view again based on the return value of the query (the data returned by model) - even though I updated the view already for that user action.

But, I am facing issues because, its taking a lot of time for the model to return the result, by that time user would have performed multiple clicks. So, as a result of updating the view again based on the information from model, the view sometimes goes back to the state in which the previous clicks were made

(Suppose user clicks thrice on different rows. I update the view as soon as the click happens. Also, I update the view when I get data back from the model - which is supposed to be same as the already updated state of the view. Now, when the user clicks third time, I get data for the first click from model. As a result, view goes back to a state which is generated by the first click)

Is there any way to handle such a synchronization issue?

答:
You describe a situation in which the user updates three rows. The first transaction completes after the third click, and all three rows update themselves with the stale data.

You need to think about the granularity of your model items. It sounds like you want each row on the UI to represent a single aggregate (transactional boundary). So when an aggregate is updated in the database, you should only update that aggregate's row on the UI.

In other words, I think the events to which your view is binding are too coarse-grained. When a model item is updated in the database, you should consider returning only that item's new state from the back end. Since the commands from the UI are being handled atomically, the resulting events should be atomic too.

Pseudo-C#:

```<code>class ViewController
{
    ...
    void RowUpdatedEventHandler(RowUpdatedEvent e)
    {
        var row = this.rows[e.AggregateId];
        row.Name = e.NewName;
        row.Price = e.NewPrice;
    }
}
</code>```

Title: MVC pattern synchronisation

Body:
You describe a situation in which the user updates three rows. The first transaction completes after the third click, and all three rows update themselves with the stale data.

You need to think about the granularity of your model items. It sounds like you want each row on the UI to represent a single aggregate (transactional boundary). So when an aggregate is updated in the database, you should only update that aggregate's row on the UI.

In other words, I think the events to which your view is binding are too coarse-grained. When a model item is updated in the database, you should consider returning only that item's new state from the back end. Since the commands from the UI are being handled atomically, the resulting events should be atomic too.

Pseudo-C#:

class ViewController
{
    ...
    void RowUpdatedEventHandler(RowUpdatedEvent e)
    {
        var row = this.rows[e.AggregateId];
        row.Name = e.NewName;
        row.Price = e.NewPrice;
    }
}


问:
Understanding Visual Studio Community Edition license
Recently Microsoft has released a free version of Visual Studio: Visual Studio Community Edition

the license says

IF YOU COMPLY WITH THESE LICENSE TERMS, YOU HAVE THE RIGHTS BELOW.

INSTALLATION AND USE RIGHTS.

a.   Individual license. If you are an individual working on your own
  applications to sell or for any other purpose, you may use the
  software to develop and test those applications.

b.   Organization licenses. If you are an organization, your users may
  use the software as follows:

·       Any number of your users may use the software to develop and
  test your applications released under Open Source Institute
  (OSI)-approved open source software licenses.

·       Any number of your users may use the software to develop and
  test your applications as part of online or in person classroom
  training and education, or for performing academic research.

·       If none of the above apply, and you are also not an enterprise
  (defined below), then up to 5 of your individual users can use the
  software concurrently to develop and test your applications.

·       If you are an enterprise, your employees and contractors may
  not use the software to develop or test your applications, except for
  open source and education purposes as permitted above. An “enterprise”
  is any organization and its affiliates who collectively have either
  (a) more than 250 PCs or users or (b) more than one million US dollars
  (or the equivalent in other currencies) in annual revenues, and
  “affiliates” means those entities that control (via majority
  ownership), are controlled by, or are under common control with an
  organization.

c.   Demo use. The uses permitted above include use of the software in
  demonstrating your applications.

d.   Backup copy. You may make one backup copy of the software, for
  reinstalling the software.

As an "Individual" I'm interested in the clause "a", however it's not that clear and explicit. for me it sounds a bit restrictive as it does not cover a wide range of usage (Open source, freelance work, contribution to applications you don't own etc), the confusion comes exactly from the terme 'OWN' used in the sentence,
I may be misinterpreting the whole thing as English is not my native language.
So how would you interpret the sentence?
Can we assume that we can use a software if the license does not make it clear, for example "it's not allowed to use it in this or that senario" as for "Entreprises" in the clause "b"?

答:
It looks like size of your client is important.

From Visual Studio 2013 and MSDN Licensing Whitepaper - November-2014 page 10:

"Example 2: A Fortune 500 firm has outsourced the development of its store-locator mobile application to a small agency. The application is not an open source project. The agency has 5 employees working on the project and would like to use Visual Studio Community 2013. Since the agency is a contractor developing this application for the Fortune 500 firm, and since the application is not an open source project, the agency cannot use Visual Studio Community 2013 for developing and testing the application. "

So your small team can't develop customized app for big company. Don't know what about boxed apps. Don't know what about "individual".

I've done some more research and it looks like small teams can sell apps build with VS2013Comm. There are no restrictions in EULA who can buy it. I guess the key words are sell and outsource. When you sell, it's still your app. While outsourcing, usually app isn't yours but clients.
That's my story and I'm stickin to it. Let me know if you think I'm wrong.


问:
Inheritance, Composition and Protocols
I'm reading a book on general object oriented concepts to try and gain a solid understanding of everything. One thing that is throwing me off is the difference between Inheritance and Composition. I know that in terms of Inheritance, it is "is-a" with the subclass. Such as an Employee class inherits from the Person class, because an employee "is-a" person. Composition's subclass is "has-a". For example, a Car class inherits from the Steering Wheel class because the car "has-a" steering wheel.

Cool, so far. But... isn't this still inheritance? I understand the difference between "is-a" and "has-a". I also understand that Composition is basically combining multiple classes to make another class that contains all of those objects. I have two questions:

Isn't composition still a form of inheritance in some ways?

Typing this out, I may have answered my own question. In Objective-C, we use Protocols to specify what needs to be inherited and what is optional. Is simply throwing a protocol into the header what differentiates Inheritance and Subclassing? Do we use protocols in both inheritance and composition?

I understand the difference quite well, and know how to utilize each through my programs. I guess it's just a question regarding semantics, if composition is really a form of inheritance or not.

答:
No, the two concepts are different.

A better car analogy would be regarding the engine. Let us assume we have an interface for an engine. It might have properties such as number of cylinders and RPM. You might be able to invoke behavior such as opening and closing the throttle. However, this is just an interface: engine is not an implementation. The Car class has-a engine: when you construct a car, you install something that implements that engine interface. Many cars have different engines as options.

Now there is the implementation. Perhaps we define a SixCylinderEngine class. It is-a engine because it implements that interface. It can be used anywhere the engine interface is used.

But wait! Some people want a supercharged version of the engine. This is not as simple as changing a variable in the existing engine, this is a major change. Different parts, a second drive belt, another major component (the supercharger), more horsepower, etc.

One way to accomplish this would be to subclass SixCylinderEngine and add in the supercharger. That has merit, but can introduce complex interdependencies between the subclass and superclass. That would be another is-a relationship.

Instead, we define a SuperchargedSixCylinderEngine class that implements Engine directly (is-a). In order to reuse code, it contains a SixCylinderEngine internally and delegates certain functions (has-a).

From here, the next step is to have a SuperchargedEngine which accepts any engine: 6, 8, 10 cylinder, anything you want.

Here is a code example of the difference.

Inheritence:

```<code>public int getHorsepower() {
  return 1.4 * super.getHorsepower();
}
</code>```

Composition:

```<code>private Engine engine;

public SuperchargedEngine(Engine e) {
  engine = e;
}

public int getHorsepower() {
  return 1.4 * engine.getHorsepower();
}
</code>```

Title: Inheritance, Composition and Protocols

Body:
No, the two concepts are different.

A better car analogy would be regarding the engine. Let us assume we have an interface for an engine. It might have properties such as number of cylinders and RPM. You might be able to invoke behavior such as opening and closing the throttle. However, this is just an interface: engine is not an implementation. The Car class has-a engine: when you construct a car, you install something that implements that engine interface. Many cars have different engines as options.

Now there is the implementation. Perhaps we define a SixCylinderEngine class. It is-a engine because it implements that interface. It can be used anywhere the engine interface is used.

But wait! Some people want a supercharged version of the engine. This is not as simple as changing a variable in the existing engine, this is a major change. Different parts, a second drive belt, another major component (the supercharger), more horsepower, etc.

One way to accomplish this would be to subclass SixCylinderEngine and add in the supercharger. That has merit, but can introduce complex interdependencies between the subclass and superclass. That would be another is-a relationship.

Instead, we define a SuperchargedSixCylinderEngine class that implements Engine directly (is-a). In order to reuse code, it contains a SixCylinderEngine internally and delegates certain functions (has-a).

From here, the next step is to have a SuperchargedEngine which accepts any engine: 6, 8, 10 cylinder, anything you want.

Here is a code example of the difference.

Inheritence:

public int getHorsepower() {
  return 1.4 * super.getHorsepower();
}

Composition:

private Engine engine;

public SuperchargedEngine(Engine e) {
  engine = e;
}

public int getHorsepower() {
  return 1.4 * engine.getHorsepower();
}


问:
Does this Decorator implementation violate the Liskov Substitution Principle?
Please consider the following implementation of the Decorator design pattern:

WordBank objects store strings and return them to the client through the method getWords().

The decorator class, WordSorter, is a subclass of WordBank (as in the Decorator pattern). However it's implementation of getWords() sorts some of the strings and removes them, before returning the array to the client.

For example a WordSorter might delete all of the strings in the bank that start with letter 'a', and only after that return the array to the client.

Does this violate the Liskov Substitution Principle? Since some implementations of WordBank return strings while others first sort through the strings and only return some of them, I'm not sure if it's safe to say that a WordSorter can be used anywhere any other WordBank is used. Or am I understanding this principle wrong?

答:
By the general description given, it sounds as though the concrete types WordBank and WordSorter (might be better called WordFilter) should be separate types both implement from a common interface IWordSource, and/or inherit from a common abstract base class WordSourceBase which does so, rather than having either concrete type inherit from the other (setting aside the question of what it should mean when a method returns an array).  Code which wants to be able to store things into a word holder and know that items will be returned in the order supplied should demand a WordBank.  Code that wants something that can supply a list of words, but doesn't care how that list is produced should demand an IWordSource.  Code that wants something that can be given to code that expects an IWordSource but filters the supplied data first should create a WordSorter/WordFilter.

While I would not go so far as to suggest that instantiable classes should always be sealed, I would suggest that many situations where one might consider inheriting from an instantiable class would be better handled by having the original instantiable class inherit from an abstract base, and having the proposed derivative type also inherit from that same base.  Code which is concerned about precise details of how the original instantiable class works (which might be different in the derived type) can demand a reference of that type, while code which is only interested in the abstract behaviors can accept a reference of that base type (which could then identify either the original type or a derivative).


答:
If you want an OCP-conforming way of handling an unspecified list of exceptions, then you can consider "chain of responsibility". But it's not clear from your question whether your code is specified to handle "an arbitrary set of exceptions, each in a different way, all of which will be specified in future and is subject to change", or whether the fixed list of three that it currently handles is a fundamental and reliable part of the design.

Adding another exception to the list of things that your code needs to handle isn't "extending" the code you have, it is "modifying" it. So if you're in the former, flexible, case then you have an OCP violation on your hands because you'll need to modify your code to handle an anticipated change. If you're in the latter case, perhaps because Foo, Bar and Biz represent the only three legal base classes for all exceptions that your code is permitted to handle different from the ... case, then you might be OK.

Provided that "something that throws" has a well-defined and stable interface, then you don't ever need to add to the list of exceptions you handle. So your code isn't in itself a violation of OCP. Part of OCP is that you don't make backward-incompatible changes to existing interfaces that people rely on throughout the code. Throwing a new exception is a backward-incompatible interface change, it is modification.

If "something that throws" has a badly documented interface, or one subject to change in future, such that it can suddenly start throwing something it didn't throw before, then you do have a violation of OCP: "something" violates it by being open to modification. These violations tend to spread, so your code will have to violate it too.

If "something" is well-specified, but your code is using information about "something" that goes beyond its interface, then you have a problem with over-coupling between components. I'm unsure whether to consider that also an OCP violation, I'm not really in a position where the taxonomy of issues beyond the first is important to me ;-)

Note that in any case a complete commitment to OCP is a reasonably high standard. You might find that "I'm not going to write the code this way because it violates the Open/Closed Principle" simply doesn't suit you or your colleagues. Which is not necessarily to say you should be ignorant of whether you're violating it or not.


问:
Which according to you are the top languages to watch out for in 2011 and beyond?
Which according to you are the top languages to watch out for in 2011 and beyond?

This article  talks about 9 languages to watch out for in 2011. What are your views and inputs on this?

答: I think, MS is going to promote and push forward F# (they already do this AFAIU). Also, I would like to understand what is going to happen with Java.


问:
Use cases for "private" interfaces?
I was wondering if there was a valid use case for being able to properly define the specific internal properties and functions of a class in a way similar to how an interface defines the public properties and functions of a class.

Imagine the task that you have to build a class that describes a human being.

Obviously, each human is a humanoid creature but not every humanoid creature is a human so you'd probably have an interface IHumanoid with functions like these (since it isn't useful to hardcode the body plan into the class):

```<code>public interface IHumanoid {
    function get head():IHead;
    function get torso():ITorso;
    function get leftArm():IArm;
    function get rightArm():IArm;
    function get leftLeg():ILeg;
    function get rightLeg():ILeg;
}
</code>```

Further and also obviously, each human is a mammal but not every mammal is a human, so there's probably another interface IMammal with two definitions for males and females floating around somewhere:

```<code>public interface IMammal {
    function procreate(partner:IMammal):void;
}

public interface IMaleMammal extends IMammal {
    function inseminate(female:IFemaleMammal):void;
}

public interface IFemaleMammal extends IMammal {
    function conceive(partner:IMaleMammal):Boolean;
    function giveBirth():IMammal;
    function nurse(offspring:IMammal):void;
}
</code>```

Thus our class probably looks something like this now:

```<code>public class Human implements IHumanoid, IMammal {
    private var _head:IHead;
    private var _torso:ITorso;
    private var _leftArm:IArm;
    private var _rightArm:IArm;
    private var _leftLeg:ILeg;
    private var _rightLeg:ILeg;

    public function Human() {
        // ctor...
    }

    public function get head():IHead {
        return _head;
    }

    public function get torso():ITorso {
        return _torso;
    }

    public function get leftArm():IArm {
        return _leftArm;
    }

    public function get rightArm():IArm {
        return _rightArm;
    }

    public function get leftLeg():ILeg {
        return _leftLeg;
    }

    public function get rightLeg():ILeg {
        return _rightLeg;
    }

    public function procreate(partner:IMammal):void {
        // "abstract" function
    }
}

public class MaleHuman extends Human implements IMaleMammal {
    override public function procreate(partner:IMammal):void {
        if (partner is IFemaleMammal) {
            inseminate(partner);
        }
    }

    public function inseminate(female:IFemaleMammal):void {
        female.conceive(this);
    }
}

public class FemaleHuman extends Human implements IFemaleMammal {
    override public function procreate(partner:IMammal):void {
        if (partner is IMaleMammal) {
            conceive(partner);
        }
    }

    public function conceive(partner:IMaleMammal):Boolean {
        // ...
    }

    public function giveBirth():IMammal {
        // ...
    }

    public function nurse(offspring:IMammal):void {
        // ...
    }
}
</code>```

From this we can implement our classes further and everything's working nice and fine until we get the task to use the existing interfaces to implement some other classes. Perhaps a gorilla, an orca and a platypus.

Ignoring the massive issue the platypus will pose to our current interface structure (*cough* egg  laying mammal *cough*), we have the "problem" that nothing prevents us from giving the gorilla 2 brains, the orca 8 lungs and the platypus half a dozen livers. And while we might be disciplined enough to follow the structure mammals typically have we cannot guarantee the same if we open the API for other developers who might code some seriously screwed up things which still look okay to the outside world.

Therefore I was wondering if there was a valid use case to create something like a "private interface" which defines non-public functions and properties. Perhaps something along these lines:

```<code>public structure SMammal {
    function get brain():IBrain;
    function get liver():ILiver;
    function get leftLung():ILung;
    function get rightLung():ILung;
    function get leftKidney():IKidney;
    function get rightKidney():IKidney;
}

public class Human implements IHumanoid, IMammal follows SMammal {
    private function get brain():IBrain {
        // ...
    }

    private function get liver():ILiver {
        // ...
    }

    // etc. etc.
}
</code>```

Does such a feature exist in any programming language? Can abstract classes be used to solve this? Or shouldn't we care about this at all as long as the public interface somehow works as expected?

答: At least in .NET languages, it's possible to apply an access specifier to an interface.  This can be helpful when an some combinations of an assembly's internal classes share common abilities, but those combinations and abilities do not fit a hierarchical relationship.  The fact that the abilities do not fit a hierarchical relationship makes it necessary to use interfaces to represent them, but in no way implies that external code should be allowed to define types that claim to implement the interfaces.  Further, interfaces cannot contain any methods whose parameter types or return types have narrower access than the interfaces themselves.  If class Fred is declared internal, and an interface IFred has a method which returns a Fred, then the interface must be declared internal.  If nested class Fred.Joe is private and nested interface Fred.IJoe has a method that returns a Fred.Joe, then Fred.IJoe must likewise be declared private.

Title: Use cases for "private" interfaces?


问:
How to tell that a Javascript code already needs AMD (RequireJS, …)?
At some point code is complicated less if you introduce a new abstract than if you continue as it was.

Some trigger should fire in a head of a programmer. Like, I was coding fine, but now I've added a few lines of code so I need to stop introducing that much complexity and incapsulate those into a new method. Programmer should complicate easy things step-by-step. Do not introduce new abstracts before they're needed.

Asyncronous modules (AMD) like RequireJS help to organize code in JavaScript. But when the trigger of introducing this abstract should fire?

答:
I don't think I understood your question too well. Are you asking about some of the diagnostic aspects of your code which will signal to you that it's time to shift it to AMD?

Well at our organisation we used the most popular AMD Framework, The Dojo Toolkit. And we used it really early on, even before our code became complex.

Talking about shifting a codebase from non AMD to AMD, I have the following points:

How many engineers are working together? If there are many, there is a great need to split up your large code base into multiple files where people can work in parallel.

Are you building a platform first and are separate teams using that platform? Eg: A team may be working on UI Widget Controls while other teams may be requireing it. Again a perfect place to use AMD.

Do you have an intelligent build tool in place? If not, your end users are not going to like the sluggishness of your AMD powered App.

Most importantly, even before AMD, check if your project is using Object Oriented Practices. If it is , this is again a beautiful use case to separate out your files into classes, functions, objects etc.

Is there a lot of circular or complex dependency amongst files? Well, this is what AMD was built for!


问:
Extracting first and last name from a single name field
I'm working with the Twitter API which provides only a single field called name, which includes the full name of a person.

The application that we're constructing requires a first name and a last name.

Now my question is how I am able to extract the first and last name from a single name field.

I know that I can simply just split or explode the string but this won't work if the person for example has first name which consists of more than one word.

答: I would consider using a regular expression pattern with grouping to extract only the beginning and the end words. </p>


问:
Every function is a closure?
Wikipedia says, that closure - is a function, which has an access to variables, declared outside of the function. There is even an example:

```<code>function startAt(x)
   function incrementBy(y)
       return x + y
   return incrementBy

variable closure1 = startAt(1)
variable closure2 = startAt(5)
</code>```

But according to most programming languages (including python, javascript, swift, etc.) the next example is correct (written in python):

```<code># Script starts
test = "check"

def func(test2):

    def func2():
        return test2 == test

    return func2()

print func("check") // returns TRUE
# Script ends
</code>```

Basically, func is not a closure, but it obviously uses variable test, declared outside of the function. Does that mean func IS a closure?

Even in C++ you can run this:

```<code>std::string test = "check";

bool func(std::string test2) {
    if (test2 == test)
        return true;
    else
        return false;
}

int main() {
    if (func("check"))
        std::cout << "TRUE" << std::endl; // prints TRUE
}
</code>```

Eventually, this makes every function being a closure. Where am I wrong?

答:
No, not every function is a closure.

Wikipedia says:

... closure ... is a function or reference to a function together with a referencing environment — a table storing a reference to each of the non-local variables (also called free variables or upvalues) of that function.

I'd add "non-local and non-global", but the idea is correct.

Neither your C++ nor Python examples use closures. In both cases it's just scoping rules allow functions to see their outer scope and global scope.

"Closure" happens in the 1st example - incrementBy is constructed in and then returned from it's outer function, capturing argument x. When you assign variable closure1 = startAt(1), you end up having a closure (function) inside closure1 var which captured argument, which value happened to be 1, so when you call closure1(2) the result is 3 (1 + 2).

Think of it as memorizing some information about closure's declaration scope: incrementBy retain a memory about insides of startAt, specifically a value of it's argument x.

In lambda calculus, as I know, those "non-local" variables are called "free", and functions with free variables are called "open terms". Closure is a process of "closing" open terms by "fixing" values of those free variables in aforementioned "environment table". Hence the name.

It's worth noting that in Python and JS closure happens implicitly, while in PHP you have to explicitly tell which variables you want to close over (capture): http://php.net/manual/en/functions.anonymous.php - note use keyword in declarations:

```<code>// equivalent to the 1st example
function startAt($x) { //        vvvvvvvv          vv
    $incrementBy = function ($y) use ($x) { return $x + $y };
    return $incrementBy;
}
</code>```

Title: Every function is a closure?

Body:
No, not every function is a closure.

Wikipedia says:

... closure ... is a function or reference to a function together with a referencing environment — a table storing a reference to each of the non-local variables (also called free variables or upvalues) of that function.

I'd add "non-local and non-global", but the idea is correct.

Neither your C++ nor Python examples use closures. In both cases it's just scoping rules allow functions to see their outer scope and global scope.

"Closure" happens in the 1st example - incrementBy is constructed in and then returned from it's outer function, capturing argument x. When you assign variable closure1 = startAt(1), you end up having a closure (function) inside closure1 var which captured argument, which value happened to be 1, so when you call closure1(2) the result is 3 (1 + 2).

Think of it as memorizing some information about closure's declaration scope: incrementBy retain a memory about insides of startAt, specifically a value of it's argument x.

In lambda calculus, as I know, those "non-local" variables are called "free", and functions with free variables are called "open terms". Closure is a process of "closing" open terms by "fixing" values of those free variables in aforementioned "environment table". Hence the name.

It's worth noting that in Python and JS closure happens implicitly, while in PHP you have to explicitly tell which variables you want to close over (capture): http://php.net/manual/en/functions.anonymous.php - note use keyword in declarations:

// equivalent to the 1st example
function startAt($x) { //        vvvvvvvv          vv
    $incrementBy = function ($y) use ($x) { return $x + $y };
    return $incrementBy;
}