问:
When using method chaining, do I reuse the object or create one?
When using method chaining like:

var car = new Car().OfBrand(Brand.Ford).OfModel(12345).PaintedIn(Color.Silver).Create();
```

<p>there may be two approaches:</p>

<ul>
<li><p>Reuse the same object, like this:</p>

<pre class="lang-cs prettyprint-override"><code>public Car PaintedIn(Color color)
{
    this.Color = color;
    return this;
}
</code>```

Create a new object of type Car at every step, like this:

public Car PaintedIn(Color color)
{
    var car = new Car(this); // Clone the current object.
    car.Color = color; // Assign the values to the clone, not the original object.
    return car;
}
```</li>
</ul>

<p>Is the first one <em>wrong</em> or it's rather a personal choice of the developer?</p>

<hr>

<p>I believe that he first approach may quickly cause the intuitive/misleading code. Example:</p>

<pre class="lang-cs prettyprint-override"><code>// Create a car with neither color, nor model.
var mercedes = new Car().OfBrand(Brand.MercedesBenz).PaintedIn(NeutralColor);

// Create several cars based on the neutral car.
var yellowCar = mercedes.PaintedIn(Color.Yellow).Create();
var specificModel = mercedes.OfModel(99).Create();

// Would `specificModel` car be yellow or of neutral color? How would you guess that if
// `yellowCar` were in a separate method called somewhere else in code?
</code>```

Any thoughts?

答:
I'd put the fluent api to it's own "builder" class seperate from the object it is creating. That way, if the client doesn't want to use the fluent api you can still use it manually and it doesn't pollute the domain object (adhering to single responsibility principle). In this case the following would be created:

Car which is the domain object

CarBuilder which holds the fluent API

The usage would be like this:

var car = CarBuilder.BuildCar()
    .OfBrand(Brand.Ford)
    .OfModel(12345)
    .PaintedIn(Color.Silver)
    .Build();
```

<p>The <code>CarBuilder</code> class would look like this (I'm using C# naming convention here):</p>

<pre class="lang-cs prettyprint-override"><code>public class CarBuilder {

    private Car _car;

    /// Constructor
    public CarBuilder() {
        _car = new Car();
        SetDefaults();
    }

    private void SetDefaults() {
        this.OfBrand(Brand.Ford);
          // you can continue the chaining for
          // other default values
    }

    /// Starts an instance of the car builder to
    /// build a new car with default values.
    public static CarBuilder BuildCar() {
        return new CarBuilder();
    }

    /// Sets the brand
    public CarBuilder OfBrand(Brand brand) {
        _car.SetBrand(brand);
        return this;
    }

    // continue with OfModel(...), PaintedIn(...), and so on...
    // that returns "this" to allow method chaining

    /// Returns the built car
    public Car Build() {
        return _car;
    }

}
</code>```

Note that this class will not be thread safe (each thread will need it's own CarBuilder instance). Also note that, even though fluent api is a really cool concept, it probably is overkill for the purpose of creating simple domain objects.

This deal is more useful if you're creating an API for something much more abstract and has more complex set up and execution, which is why it works great in unit testing and DI frameworks. You can see some other examples under the Java section of the wikipedia Fluent Interface article with persistance, date handling and mock objects.

EDIT:

As noted from the comments; you could make the Builder class a static inner class (inside Car) and Car could be made immutable. This example of letting Car be immutable seems a bit silly; but in a more complex system, where you absolutely don't want to change the contents of the object that is built, you might want to do it.

Below is one example of how to do both the static inner class and how to handle an immutable object creation that it builts:

// the class that represents the immutable object
public class ImmutableWriter {

    // immutable variables
    private int _times; private string _write;

    // the "complex" constructor
    public ImmutableWriter(int times, string write) {
        _times = times;
        _write = write;
    }

    public void Perform() {
        for (int i = 0; i < _times; i++) Console.Write(_write + " ");
    }

    // static inner builder of the immutable object
    protected static class ImmutableWriterBuilder {

        // the variables needed to construct the immutable object
        private int _ii = 0; private string _is = String.Empty;

        public void Times(int i) { _ii = i; }

        public void Write(string s) { _is = s; }

        // The stuff is all built here
        public ImmutableWriter Build() {
            return new ImmutableWriter(_ii, _is);
        }

    }

    // factory method to get the builder
    public static ImmutableWriterBuilder GetBuilder() {
        return new ImmutableWriterBuilder();
    }
}
```

<p>The usage would be the following:</p>

<pre class="lang-cs prettyprint-override"><code>var writer = ImmutableWriter
                .GetBuilder()
                .Write("peanut butter jelly time")
                .Times(2)
                .Build();

writer.Perform();
// console writes: peanut butter jelly time peanut butter jelly time
</code>```

Edit 2: Pete in the comments made a blog post about using builders with lambda functions in the context of writing unit tests with complex domain objects. It is an interesting alternative to make the builder a bit more expressive.

In the case of CarBuilder you need to have this method instead:

public static Car Build(Action<CarBuilder> buildAction = null) {
    var carBuilder = new CarBuilder();
    if (buildAction != null) buildAction(carBuilder);
    return carBuilder._car;
}
```

<p>Which can be used as this:</p>

<pre class="lang-cs prettyprint-override"><code>Car c = CarBuilder
    .Build(car =>
        car.OfBrand(Brand.Ford)
           .OfModel(12345)
           .PaintedIn(Color.Silver);
</code>```

Body:
I'd put the fluent api to it's own "builder" class seperate from the object it is creating. That way, if the client doesn't want to use the fluent api you can still use it manually and it doesn't pollute the domain object (adhering to single responsibility principle). In this case the following would be created:

Car which is the domain object

CarBuilder which holds the fluent API

The usage would be like this:

var car = CarBuilder.BuildCar()
    .OfBrand(Brand.Ford)
    .OfModel(12345)
    .PaintedIn(Color.Silver)
    .Build();

The CarBuilder class would look like this (I'm using C# naming convention here):

public class CarBuilder {

    private Car _car;

    /// Constructor
    public CarBuilder() {
        _car = new Car();
        SetDefaults();
    }

    private void SetDefaults() {
        this.OfBrand(Brand.Ford);
          // you can continue the chaining for
          // other default values
    }

    /// Starts an instance of the car builder to
    /// build a new car with default values.
    public static CarBuilder BuildCar() {
        return new CarBuilder();
    }

    /// Sets the brand
    public CarBuilder OfBrand(Brand brand) {
        _car.SetBrand(brand);
        return this;
    }

    // continue with OfModel(...), PaintedIn(...), and so on...
    // that returns "this" to allow method chaining

    /// Returns the built car
    public Car Build() {
        return _car;
    }

}

Note that this class will not be thread safe (each thread will need it's own CarBuilder instance). Also note that, even though fluent api is a really cool concept, it probably is overkill for the purpose of creating simple domain objects.

This deal is more useful if you're creating an API for something much more abstract and has more complex set up and execution, which is why it works great in unit testing and DI frameworks. You can see some other examples under the Java section of the wikipedia Fluent Interface article with persistance, date handling and mock objects.

EDIT:

As noted from the comments; you could make the Builder class a static inner class (inside Car) and Car could be made immutable. This example of letting Car be immutable seems a bit silly; but in a more complex system, where you absolutely don't want to change the contents of the object that is built, you might want to do it.

Below is one example of how to do both the static inner class and how to handle an immutable object creation that it builts:

// the class that represents the immutable object
public class ImmutableWriter {

    // immutable variables
    private int _times; private string _write;

    // the "complex" constructor
    public ImmutableWriter(int times, string write) {
        _times = times;
        _write = write;
    }

    public void Perform() {
        for (int i = 0; i < _times; i++) Console.Write(_write + " ");
    }

    // static inner builder of the immutable object
    protected static class ImmutableWriterBuilder {

        // the variables needed to construct the immutable object
        private int _ii = 0; private string _is = String.Empty;

        public void Times(int i) { _ii = i; }

        public void Write(string s) { _is = s; }

        // The stuff is all built here
        public ImmutableWriter Build() {
            return new ImmutableWriter(_ii, _is);
        }

    }

    // factory method to get the builder
    public static ImmutableWriterBuilder GetBuilder() {
        return new ImmutableWriterBuilder();
    }
}

The usage would be the following:

var writer = ImmutableWriter
                .GetBuilder()
                .Write("peanut butter jelly time")
                .Times(2)
                .Build();

writer.Perform();
// console writes: peanut butter jelly time peanut butter jelly time

Edit 2: Pete in the comments made a blog post about using builders with lambda functions in the context of writing unit tests with complex domain objects. It is an interesting alternative to make the builder a bit more expressive.

In the case of CarBuilder you need to have this method instead:

public static Car Build(Action<CarBuilder> buildAction = null) {
    var carBuilder = new CarBuilder();
    if (buildAction != null) buildAction(carBuilder);
    return carBuilder._car;
}

Which can be used as this:

Car c = CarBuilder
    .Build(car =>
        car.OfBrand(Brand.Ford)
           .OfModel(12345)
           .PaintedIn(Color.Silver);


答:
The most important thing is that whatever the decision you choose, it is clearly stated in the method name and/or comment.

There is no standard, sometimes the method will return a new object (most of the String methods do so) or will return this object for chaining purpose or for memory efficiency).

I once designed a 3D Vector object and for every math operation I had both methods implemented. For instant the scale method :

```<code>Vector3D scaleLocal(float factor){
    this.x *= factor;
    this.y *= factor;
    this.z *= factor;
    return this;
}

Vector3D scale(float factor){
    Vector3D that = new Vector3D(this); // clone this vector
    return that.scaleLocal(factor);
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: When using method chaining, do I reuse the object or create one?

Body:
When using method chaining like:

var car = new Car().OfBrand(Brand.Ford).OfModel(12345).PaintedIn(Color.Silver).Create();
```

<p>there may be two approaches:</p>

<ul>
<li><p>Reuse the same object, like this:</p>

<pre class="lang-cs prettyprint-override"><code>public Car PaintedIn(Color color)
{
    this.Color = color;
    return this;
}
</code>```

Create a new object of type Car at every step, like this:

public Car PaintedIn(Color color)
{
    var car = new Car(this); // Clone the current object.
    car.Color = color; // Assign the values to the clone, not the original object.
    return car;
}
```</li>
</ul>

<p>Is the first one <em>wrong</em> or it's rather a personal choice of the developer?</p>

<hr>

<p>I believe that he first approach may quickly cause the intuitive/misleading code. Example:</p>

<pre class="lang-cs prettyprint-override"><code>// Create a car with neither color, nor model.
var mercedes = new Car().OfBrand(Brand.MercedesBenz).PaintedIn(NeutralColor);

// Create several cars based on the neutral car.
var yellowCar = mercedes.PaintedIn(Color.Yellow).Create();
var specificModel = mercedes.OfModel(99).Create();

// Would `specificModel` car be yellow or of neutral color? How would you guess that if
// `yellowCar` were in a separate method called somewhere else in code?
</code>```

Any thoughts?

Body:
The most important thing is that whatever the decision you choose, it is clearly stated in the method name and/or comment.

There is no standard, sometimes the method will return a new object (most of the String methods do so) or will return this object for chaining purpose or for memory efficiency).

I once designed a 3D Vector object and for every math operation I had both methods implemented. For instant the scale method :

Vector3D scaleLocal(float factor){
    this.x *= factor;
    this.y *= factor;
    this.z *= factor;
    return this;
}

Vector3D scale(float factor){
    Vector3D that = new Vector3D(this); // clone this vector
    return that.scaleLocal(factor);
}


答:
The first approach does have the drawback you mention, but as long as you make it clear in the docs any half-competent coder shouldn't have problems. All of the method-chaining code I've personally worked with has worked this way.

The second approach obviously has the drawback of being more work. You also have to decide whether the copies you return are going to do shallow or deep copies: which is best may vary from class to class or method to method, so you'll either be introducing inconsistency or compromising on the best behaviour. It's worth noting that this is the only option for immutable objects, like strings.

Whatever you do, don't mix and match within the same class!


问:
From where do financial firms obtain the stock data to analyze
I've been thinking about the subject and I've always wondered, from where do they obtain the data that is analized in applications, I've looked at Nasdaq's website and they do not seem to have any sort of APIs, do the firms parse yahoo's finance section, or are there special contracts, agreements in places with the different stock markets?</p>

答: They subscribe to data feeds to the various exchanges and record the data as it comes in. Free sources like Yahoo and Google can have errors in the data, can be delayed, and don't have all the information that professional traders require.</p>


答:
Create a separate static inner builder.

Use normal constructor arguments for required parameters. And fluent api for optional.

Don't create a new object when setting colour, unless you rename the method NewCarInColour or something similar.

I would do something like this witht he brand as required and the rest optional (this is java, but yours looks like javascript, but pretty sure they are interchangeable with a bit of nit picking) :

```<code>Car yellowMercedes = new Car.Builder(Brand.MercedesBenz).PaintedIn(Color.Yellow).create();

Car specificYellowModel =new Car.Builder(Brand.MercedesBenz).WithModel(99).PaintedIn(Color.Yellow).create();
</code>```

Body:
Create a separate static inner builder.

Use normal constructor arguments for required parameters. And fluent api for optional.

Don't create a new object when setting colour, unless you rename the method NewCarInColour or something similar.

I would do something like this witht he brand as required and the rest optional (this is java, but yours looks like javascript, but pretty sure they are interchangeable with a bit of nit picking) :

Car yellowMercedes = new Car.Builder(Brand.MercedesBenz).PaintedIn(Color.Yellow).create();

Car specificYellowModel =new Car.Builder(Brand.MercedesBenz).WithModel(99).PaintedIn(Color.Yellow).create();


问:
Test Driven Development, has it reduced stress for developers?
I understand the benefits of test driven development, but have there been any studies that reveal the level of satisfaction with the product or stress levels of the authoring developers with the introduction of unit testing?

I'm looking for case studies, or preferably research papers.

答:
```<code> > Test Driven Development, has it reduced stress for developers?
</code>```

No but it has changed the kind of stress.

In non tdd legacy projects I have stress because of code quality and increased maintenance costs. Especially I have stress in judging why "this tiny change in program logic costs so much time and money".

In tdd projects there are "clever" stakeholders who want to further increase productivity by abolishing the "tdd-waste of time" with all its unnecessary code. So defending TDD is stress.

If you are more productive because of good code quality you have to implement more features in a given timeslot.

I can think of some non-tdd legacy projects that caused a lot of stress where I wished that they were tdd-projects.

Body:
 > Test Driven Development, has it reduced stress for developers?

No but it has changed the kind of stress.

In non tdd legacy projects I have stress because of code quality and increased maintenance costs. Especially I have stress in judging why "this tiny change in program logic costs so much time and money".

In tdd projects there are "clever" stakeholders who want to further increase productivity by abolishing the "tdd-waste of time" with all its unnecessary code. So defending TDD is stress.

If you are more productive because of good code quality you have to implement more features in a given timeslot.

I can think of some non-tdd legacy projects that caused a lot of stress where I wished that they were tdd-projects.


问:
Plagued by multithreaded bugs
On my new team that I manage, the majority of our code is platform, TCP socket, and http networking code. All C++.  Most of it originated from other developers that have left the team. The current developers on the team are very smart, but mostly junior in terms of experience.

Our biggest problem: multi-threaded concurrency bugs. Most of our class libraries are written to be asynchronous by use of some thread pool classes. Methods on the class libraries often enqueue long running taks onto the thread pool from one thread and then the callback methods of that class get invoked on a different thread. As a result, we have a lot of edge case bugs involving incorrect threading assumptions.  This results in subtle bugs that go beyond just having critical sections and locks to guard against concurrency issues.

What makes these problems even harder is that the attempts to fix are often incorrect. Some mistakes I've observed the team attempting (or within the legacy code itself) includes something like the following:

Common mistake #1 - Fixing concurrency issue by just put a lock around the shared data, but forgetting about what happens when methods don't get called in an expected order.  Here's a very simple example:

```<code>void Foo::OnHttpRequestComplete(statuscode status)
{
    m_pBar->DoSomethingImportant(status);
}

void Foo::Shutdown()
{
    m_pBar->Cleanup();
    delete m_pBar;
    m_pBar=nullptr;
}
</code>```

So now we have a bug in which Shutdown could get called while OnHttpNetworkRequestComplete is occuring on. A tester finds the bug, captures the crash dump, and assigns the bug to a developer. He in turn fixes the bug like this.

```<code>void Foo::OnHttpRequestComplete(statuscode status)
{
    AutoLock lock(m_cs);
    m_pBar->DoSomethingImportant(status);
}

void Foo::Shutdown()
{
    AutoLock lock(m_cs);
    m_pBar->Cleanup();
    delete m_pBar;
    m_pBar=nullptr;
}
</code>```

The above fix looks good until you realize there's an even more subtle edge case. What happens if Shutdown gets called before OnHttpRequestComplete gets called back? The real world examples my team has are even more complex, and the edge cases are even harder to spot during the code review process.

Common Mistake #2 - fixing deadlock issues by blindly exiting the lock, wait for the other thread to finish, then re-enter the lock - but without handling the case that the object just got updated by the other thread!

Common Mistake #3 - Even though the objects are reference counted, the shutdown sequence "releases" it's pointer. But forgets to wait for the thread that is still running to release it's instance. As such, components are shutdown cleanly, then spurious or late callbacks are invoked on an object in an state not expecting any more calls.

There are other edge cases, but the bottom line is this:

Multithreaded programming is just plain hard, even for smart people.

As I catch these mistakes, I spend time discussing the errors with each developer on developing a more appropriate fix. But I suspect they are often confused on how to solve each issue because of the enormous amount of legacy code that the "right" fix will involve touching.

We're going to be shipping soon, and I'm sure the patches we're applying will hold for the upcoming release. Afterwards, we're going to have some time to improve the code base and refactor where needed. We won't have time to just re-write everything. And the majority of the code isn't all that bad. But I'm looking to refactor code such that threading issues can be avoided altogether.

One approach I am considering is this. For each significant platform feature, have a dedicated single thread where all events and network callbacks get marshalled onto. Similar to COM apartment threading in Windows with use of a message loop. Long blocking operations could still get dispatched to a work pool thread, but the completion callback is invoked on on the component's thread. Components could possibly even share the same thread. Then all the class libraries running inside the thread can be written under the assumption of a single threaded world.

Before I go down that path, I am also very interested if there are other standard techniques or design patterns for dealing with multithreaded issues.  And I have to emphasize - something beyond a book that describes the basics of mutexes and semaphores. What do you think?

I am also interested in any other approaches to take towards a refactoring process.  Including any of the following:

Literature or papers on design patterns around threads. Something beyond an introduction to mutexes and semaphores. We don't need massive parallelism either, just ways to design an object model so as to handle asynchronous events from other threads correctly.

Ways to diagram the threading of various components, so that it will be easy to study and evolve solutions for. (That is, a UML equivalent for discussing threads across objects and classes)

Educating your development team on the issues with multithreaded code.

What would you do?

答:
You are already on the way by acknowledging the problem and actively looking for a solution. Here's what I would do:

Sit down and design a threading model for your application. This is a document which answers questions like: Which types of threads do you have? What things should be done in which thread? What different kinds of synchronization patterns should you use? In other words, it should describe the "rules of engagement" when battling multithreading problems.

Use thread analysis tools to check your codebase for errors. Valgrind has a thread checker called Helgrind which is good at spotting things like shared state being manipulated without proper synchronization. There are most certainly other good tools out there, go look for them.

Consider migrating away from C++. C++ is a nightmare to write concurrent programs in. My personal choice would be Erlang, but that is a matter of taste.

Title: Plagued by multithreaded bugs


问:
What is the name for the idiom using method chaining to build an object?
I frequently use a pattern where I using method chaining to setup an object, similar to a Builder or Prototype pattern, but not creating new objects with each method call, instead modifying the original object.

Example:

```<code>new Menu().withItem("Eggs").withItem("Hash Browns").withStyle("Diner");
</code>```

Just wondering if there is a name for this pattern and whether it is considered an anti-pattern, because although it can read more fluently, it can lead to long method chains.

答:
whether it is considered an anti-pattern,

definitely not an anti-pattern. jQuery is probably the most well used implementation of this.

because although it can read more fluently, it can lead to long method
  chains

Yes it can, but what is the alternative ? You can end up with almost a plain english sentence, with the api guiding you to what is available and appropriate.

ContentLicense: CC BY-SA 4.0


答:
Your code has significant other issues apart from just that. Manually deleting a pointer? Calling a cleanup function? Owch. Also, as accurately pointed out in the question comment, you don't use RAII for your lock, which is another fairly epic fail and guarantees that when DoSomethingImportant throws an exception, terrible things happen.

The fact that this multithreaded bug is occurring is just a symptom of the core problem- your code has extremely bad semantics in any threading situation and you're using completely unreliable tools and ex-idioms. If I were you, I'd be amazed that it functions with a single thread, let alone more.

Common Mistake #3 - Even though the objects are reference counted, the
  shutdown sequence "releases" it's pointer. But forgets to wait for the
  thread that is still running to release it's instance. As such,
  components are shutdown cleanly, then spurious or late callbacks are
  invoked on an object in an state not expecting any more calls.

The whole point of reference counting is that the thread has already released it's instance. Because if not, then it cannot be destroyed because the thread still has a reference.

Use std::shared_ptr. When all threads have released (and nobody, therefore, can be calling the function, as they have no pointer to it), then the destructor is called. This is guaranteed safe.

Secondly, use a real threading library, like Intel's Thread Building Blocks or Microsoft's Parallel Patterns Library. Writing your own is time-consuming and unreliable and your code is full of threading details which it doesn't need. Doing your own locks is just as bad as doing your own memory management. They have already implemented many general-purpose very useful threading idioms which work correctly for your use.

Title: Plagued by multithreaded bugs

Body:
On my new team that I manage, the majority of our code is platform, TCP socket, and http networking code. All C++.  Most of it originated from other developers that have left the team. The current developers on the team are very smart, but mostly junior in terms of experience.

Our biggest problem: multi-threaded concurrency bugs. Most of our class libraries are written to be asynchronous by use of some thread pool classes. Methods on the class libraries often enqueue long running taks onto the thread pool from one thread and then the callback methods of that class get invoked on a different thread. As a result, we have a lot of edge case bugs involving incorrect threading assumptions.  This results in subtle bugs that go beyond just having critical sections and locks to guard against concurrency issues.

What makes these problems even harder is that the attempts to fix are often incorrect. Some mistakes I've observed the team attempting (or within the legacy code itself) includes something like the following:

Common mistake #1 - Fixing concurrency issue by just put a lock around the shared data, but forgetting about what happens when methods don't get called in an expected order.  Here's a very simple example:

```<code>void Foo::OnHttpRequestComplete(statuscode status)
{
    m_pBar->DoSomethingImportant(status);
}

void Foo::Shutdown()
{
    m_pBar->Cleanup();
    delete m_pBar;
    m_pBar=nullptr;
}
</code>```

So now we have a bug in which Shutdown could get called while OnHttpNetworkRequestComplete is occuring on. A tester finds the bug, captures the crash dump, and assigns the bug to a developer. He in turn fixes the bug like this.

```<code>void Foo::OnHttpRequestComplete(statuscode status)
{
    AutoLock lock(m_cs);
    m_pBar->DoSomethingImportant(status);
}

void Foo::Shutdown()
{
    AutoLock lock(m_cs);
    m_pBar->Cleanup();
    delete m_pBar;
    m_pBar=nullptr;
}
</code>```

The above fix looks good until you realize there's an even more subtle edge case. What happens if Shutdown gets called before OnHttpRequestComplete gets called back? The real world examples my team has are even more complex, and the edge cases are even harder to spot during the code review process.

Common Mistake #2 - fixing deadlock issues by blindly exiting the lock, wait for the other thread to finish, then re-enter the lock - but without handling the case that the object just got updated by the other thread!

Common Mistake #3 - Even though the objects are reference counted, the shutdown sequence "releases" it's pointer. But forgets to wait for the thread that is still running to release it's instance. As such, components are shutdown cleanly, then spurious or late callbacks are invoked on an object in an state not expecting any more calls.

There are other edge cases, but the bottom line is this:

Multithreaded programming is just plain hard, even for smart people.

As I catch these mistakes, I spend time discussing the errors with each developer on developing a more appropriate fix. But I suspect they are often confused on how to solve each issue because of the enormous amount of legacy code that the "right" fix will involve touching.

We're going to be shipping soon, and I'm sure the patches we're applying will hold for the upcoming release. Afterwards, we're going to have some time to improve the code base and refactor where needed. We won't have time to just re-write everything. And the majority of the code isn't all that bad. But I'm looking to refactor code such that threading issues can be avoided altogether.

One approach I am considering is this. For each significant platform feature, have a dedicated single thread where all events and network callbacks get marshalled onto. Similar to COM apartment threading in Windows with use of a message loop. Long blocking operations could still get dispatched to a work pool thread, but the completion callback is invoked on on the component's thread. Components could possibly even share the same thread. Then all the class libraries running inside the thread can be written under the assumption of a single threaded world.

Before I go down that path, I am also very interested if there are other standard techniques or design patterns for dealing with multithreaded issues.  And I have to emphasize - something beyond a book that describes the basics of mutexes and semaphores. What do you think?

I am also interested in any other approaches to take towards a refactoring process.  Including any of the following:

Literature or papers on design patterns around threads. Something beyond an introduction to mutexes and semaphores. We don't need massive parallelism either, just ways to design an object model so as to handle asynchronous events from other threads correctly.

Ways to diagram the threading of various components, so that it will be easy to study and evolve solutions for. (That is, a UML equivalent for discussing threads across objects and classes)

Educating your development team on the issues with multithreaded code.

What would you do?


问:
Which hashing algorithm is best for uniqueness and speed?
Which hashing algorithm is best for uniqueness and speed? Example (good) uses include hash dictionaries.

I know there are things like SHA-256 and such, but these algorithms are designed to be secure, which usually means they are slower than algorithms that are less unique. I want a hash algorithm designed to be fast, yet remain fairly unique to avoid collisions.

答:
CityHash by Google is the algorithm you are looking for. It is not good for cryptography but is good for generating unique hashes.

Read the blog for more details and the code is available here.

CityHash is written in C++. There also is a plain C port.

About 32-bit support:

All the CityHash functions are tuned for 64-bit processors. That said, they will run (except for the new ones that use SSE4.2) in 32-bit code. They won't be very fast though. You may want to use Murmur or something else in 32-bit code.


问:
How do the algorithms to solve problems encountered in interviews translate into real world solutions?
I have recently finished an undergraduate course in computer science and I am looking for a job. During the search I encountered several interesting (and tough) problems that needed clever algorithms to solve. I also use google code jam as a practice set.

I cannot understand how those solutions translate in solving real world problems. Many problems appear (to me) not only contrived and fantastical but also highly specific to be a general purpose solution (although it isn't impossible to extend them using ingenuity).

Are these problems there only to test the problem solving skills or are these some aspect of real world problem camouflaged?

答:
Generally these questions are only there to test your problem solving skills especially, as you've found, when you're asked for a solution to a contrived scenario.

However, you may find in some cases the company will use examples from their field, but that's usually because they can pull an example from their own code base, so they already have a good solution (or, at least, a working one) - and see if you can come up with something similar. But even in these cases, it's not as if they're looking for someone who can solve a particular problem for them.

Just concentrate on your general problem solving ability. It's like learning to drive... practice often and for long enough and it will become second nature. Good luck!


问:
Checking for emptiness of collections with (in)equalities - what's the best practice?
For a long time now I've been in the habit of checking whether a collection (array, dictionary, whatever) is non-empty with a nonequality. Like this:

```<code>if ( MyArray.Length < 1 )
{
    // Do something if the array is empty
}
</code>```

Sometimes I do this for strings too, and other kinds of collections. In practice, this should be the same as

```<code>if ( MyArray.Length == 0 )
{
    // Do something if the array is empty
}
</code>```

Because the length of collection should never be less than 0 anyway, right? So I always thought - what the heck, I'll include the inequality and be double-safe even in the case the sky falls down.

But today a though struck me that the second version might be more readable than the first. It expresses more clearly that the case I'm looking for is the empty array, which is not immediately apparent from the first version. So maybe I should use that instead? Since, you know, if a collection length is less than 0, then I'm screwed anyway.

Which version do you use, and which would you suggest others to use (and why)?

Clarification: This was meant as a question about simple collections, where obtaining .Length is O(1) or otherwise inexpensive. If .Length itself is a nontrivial operation (such as necessitating the iteration through a linked list, or contacting the DB), then this is the wrong approach altogether.

The question was about x < 1 vs x == 0 where x is a nonnegative integer (although it might not be typed as such).

答:
Some collection that is empty has length of zero.

Some collection with a negative length is something else.

Use second one or implement a method like IsEmpty().


答:
Common mistake #1 - Fixing concurrency issue by just put a lock around the shared data, but forgetting about what happens when methods
  don't get called in an expected order. Here's a very simple example:

The mistake here is not the "forgetting", but the "not fixing it". If you have things happening in an unexpected order, you have a problem. You should solve it instead of trying to work around it (slapping a lock onto something is usually a work-around).

You should try to adapt the actor model/messaging to a certain degree and to have separation of concern. The role of Foo is clearly to handle some kind of HTTP communication. If you want to design your system to do this in parallel, it's the layer above that must handle object lifecycles and access synchronization accordingly.

Trying to have a number of threads operate on the same mutable data is hard. But it's also rarely necessary. All common cases that demand this, have already been abstracted into more manageable concepts and implemented a number of times for about any major imperative language. You just have to use them.

Title: Plagued by multithreaded bugs


问:
'dock' working in simple words
I would like to know the idea behind the working of 'docking' in applications. I have worked with applications where components from individual forms are docked on a single main form to provide the necessary GUI. But I don't have any idea whats happening in the background.

According to Wikipedia

A dock is a graphical user interface element that typically provides the user with a way of launching, switching between, and monitoring running programs or applications.

Now I am a bit confused if it is some component or an event or a property or something else.

EDIT :  The applications was developed in Delphi on windows platform. There is something more in Delphi (manual dock and automatic dock).

答:
Let me see:
A dock shows, in bar form, one icon for each of my favorite applications and folders PLUS one icon for each running (but non-favorite) application, changing the appearance of the icons when the application is running or if the application has any status to communicate to the user (e.g., number of unread emails or printer jobs on queue).

This describes to me both my MacOS dock and my KDE dock.

Title: 'dock' working in simple words


答:
It is a graphical component as you said.

You place your application launchers on that component and the dock keeps them accessible easily.

Most docks also tracks running applications and behave accordingly like higlighting the launcher icon or something else. You can say that it is an advanced toolbar.

Title: 'dock' working in simple words

Body:
I would like to know the idea behind the working of 'docking' in applications. I have worked with applications where components from individual forms are docked on a single main form to provide the necessary GUI. But I don't have any idea whats happening in the background.

According to Wikipedia

A dock is a graphical user interface element that typically provides the user with a way of launching, switching between, and monitoring running programs or applications.

Now I am a bit confused if it is some component or an event or a property or something else.

EDIT :  The applications was developed in Delphi on windows platform. There is something more in Delphi (manual dock and automatic dock).


答:
That depends.

Is your Car an Entity or a Value object? If the car is an entity, then object identity is of importance, so you should return the same reference. If the object is a value object, it should be immutable, meaning the only way is to return a new instance every time.

An example of the latter would be DateTime class in .NET which is a value object.

```<code>var date1 = new DateTime(2012,1,1);
var date2 = date1.AddDays(1);
// date2 now refers to Jan 2., while date1 remains unchanged at Jan 1.
</code>```

However if the model is an entity, I like Spoike's answer on using a builder class to build you object. In other words, that example you gave only makes sense IMHO if the Car is a value object.

Body:
That depends.

Is your Car an Entity or a Value object? If the car is an entity, then object identity is of importance, so you should return the same reference. If the object is a value object, it should be immutable, meaning the only way is to return a new instance every time.

An example of the latter would be DateTime class in .NET which is a value object.

var date1 = new DateTime(2012,1,1);
var date2 = date1.AddDays(1);
// date2 now refers to Jan 2., while date1 remains unchanged at Jan 1.

However if the model is an entity, I like Spoike's answer on using a builder class to build you object. In other words, that example you gave only makes sense IMHO if the Car is a value object.


答:
It depends on the type of programming jobs you're interviewing for and who's doing the interviewing.

If the potential employer is hiring someone who's going to be working on an embedded system where there aren't any existing frameworks or libraries, they may need someone who can code clever algorithms. In this case, it's a valid thing to ask.

But, if they're looking for someone to maintain and enhance a 5 year old corporate CRUD or reporting app, then it's probably a waste of their time and yours to ask you to code an algorithm that's already in the framework they're using (example, asking someone to code a sorted list in C# from scratch). It's much more valuable to give them an example of something that needs to be fixed/enhanced and let them tell you how they would approach it.

It's my opinion that to a lot of interviewers use complex programming puzzles and other such stuff unrelated to the work they're doing to make themselves feel superior to applicants rather than to evaluate the applicants' skill level. Others use them because Google/Facebook/Microsoft/etc. use them so they think they should too in order to be 'cool'.

I'm not to saying that asking problem solving questions should be off limits but that good ones should fit the job or be reasonably simple and generic with no trickery or gotchas involved. FizzBuzz instead of Kobayashi Maru

So, in my experience, such questions rarely have anything to do with the job at hand and some are asked for the wrong reasons.

Title: How do the algorithms to solve problems encountered in interviews translate into real world solutions?

Body:
I have recently finished an undergraduate course in computer science and I am looking for a job. During the search I encountered several interesting (and tough) problems that needed clever algorithms to solve. I also use google code jam as a practice set.

I cannot understand how those solutions translate in solving real world problems. Many problems appear (to me) not only contrived and fantastical but also highly specific to be a general purpose solution (although it isn't impossible to extend them using ingenuity).

Are these problems there only to test the problem solving skills or are these some aspect of real world problem camouflaged?


问:
timers with threads on queue
So I've been asking the wrong questions for the last three days and after searching a lot I think I have an idea of what I need, my question is how to use timers with two threads writing and reading on one queue.
In other words, I have one queue(or any other data structure) and two threads, producer and consumer,
so the producer write values on the queue, with a time for each value(let's say 10 seconds) and the consumer read the queue, both are using lock mechanism, what I need is a timer function that check which value has passed the 10 seconds and remove it from the queue.

I know how to implement the producer/consumer threads, but I don't know where to put this, is it a third thread or what? and do I need to write the time of the value when entered the queue, so the timer function can check it, or just write 10 and the timer function will decrement 1 each second?

答:
If the time to use is the time when it entered the queue, then you need no priority queue, just a simple FIFO. The consumer thread reads items until it finds one that is not outdated, then it reads that one as well.

Pseudo code:

```<code>typedef struct
{
  obj_t  obj;
  time_t time;
} queue_item_t;

result_t fifo_add (const obj_t* obj)
{
  queue_item_t qi;

  qi.obj  = *obj;
  qi.time = time(NULL);

  return add_to_fifo(&qi);
}

result_t fifo_remove (obj_t* returned_obj)
{
  queue_item_t qi;
  bool item_expired;

  do
  {
    if(remove_from_fifo(&qi) == EMPTY_QUEUE)
    {
      return EMPTY_QUEUE;
    }
    item_expired = expired(&qi);
  } while(item_expired);

  if(item_expired) // all items removed, all had expired
  {
    return EMPTY_QUEUE;
  }

  *returned_obj = qi.obj;
  return OK;
}

inline bool expired (const queue_item_t* ptr_qi)
{
  return ptr_qi->time < time(NULL) - TIMEOUT_CONSTANT;
}
</code>```

Just pseudo, nothing compiled or tested. You can put the mutex guards inside the add and remove functions for optimal performance.

Title: timers with threads on queue

Body:
If the time to use is the time when it entered the queue, then you need no priority queue, just a simple FIFO. The consumer thread reads items until it finds one that is not outdated, then it reads that one as well.

Pseudo code:

typedef struct
{
  obj_t  obj;
  time_t time;
} queue_item_t;

result_t fifo_add (const obj_t* obj)
{
  queue_item_t qi;

  qi.obj  = *obj;
  qi.time = time(NULL);

  return add_to_fifo(&qi);
}

result_t fifo_remove (obj_t* returned_obj)
{
  queue_item_t qi;
  bool item_expired;

  do
  {
    if(remove_from_fifo(&qi) == EMPTY_QUEUE)
    {
      return EMPTY_QUEUE;
    }
    item_expired = expired(&qi);
  } while(item_expired);

  if(item_expired) // all items removed, all had expired
  {
    return EMPTY_QUEUE;
  }

  *returned_obj = qi.obj;
  return OK;
}

inline bool expired (const queue_item_t* ptr_qi)
{
  return ptr_qi->time < time(NULL) - TIMEOUT_CONSTANT;
}

Just pseudo, nothing compiled or tested. You can put the mutex guards inside the add and remove functions for optimal performance.


问:
Are we always supposed to create a setup to deploy or application?
I have recently developed an application in C# which is supposed to run within the environment of the company i work for.

I could technically generate a Setup or use ClickOnce to handle the deployment of the application, but I am considering basically copying the EXE file into a public directory and have everybody execute it from there.

The program recovers data from a database, makes some computations and displays the results.

I was wondering what the downfalls of this idea were. So far, I came up with the following:

I have to make sure that the prerequisites are installed on each machine (for example, .Net Framework 4.0)

I will not be able to "automatically" create a shortcut and the entries in the "Start Menu" (not a problem, user can do it manually).

In particular, I was wondering if the fact that several user actually run the same application at the same time could result in a problem (cocurrency, efficiency)?

答: It may cause problems if you fix a bug and want to deploy it while someone else is using the application (since the exe will be locked). </p>


答:
We do this (more or less) with one of our major internal applications.

When we deploy, we just copy the application to a shared directory on a server. Users have a shortcut to a batch file on the same server. The batch file checks the application timestamp against the user's local copy, and then copies it over if the server version is newer.

This works really well for us. Deploying to users is as simple as copying a shortcut to their desktops.

Title: Are we always supposed to create a setup to deploy or application?

Body:
I have recently developed an application in C# which is supposed to run within the environment of the company i work for.

I could technically generate a Setup or use ClickOnce to handle the deployment of the application, but I am considering basically copying the EXE file into a public directory and have everybody execute it from there.

The program recovers data from a database, makes some computations and displays the results.

I was wondering what the downfalls of this idea were. So far, I came up with the following:

I have to make sure that the prerequisites are installed on each machine (for example, .Net Framework 4.0)

I will not be able to "automatically" create a shortcut and the entries in the "Start Menu" (not a problem, user can do it manually).

In particular, I was wondering if the fact that several user actually run the same application at the same time could result in a problem (cocurrency, efficiency)?


答: There is the "launcher dock" as others have described, but there is also a GUI control that pins child windows to the sides of a host window, such as AvalonDock. It is called a "docking layout system".</p>

Title: 'dock' working in simple words


问:
Two git repositories, one project
I am building an app using Code Igniter, it is being based on CI-Bonfire.

I am pulling in the dev branch of CI-Bonfire using git, I want the entire project to be git controlled as well, but I want to be able to just pull the latest changes from the dev branch of CI-Bonfire, but push my entire app to a different repository.

All changes that I make to the files that come from bonfire will be config changes, so all pulls will be able to merge automatically.

Is this possible?

答:
Let's see if I understand you correctly: You want to have your own git repo, containing all the bonfire code. You then want to make your own changes and NOT push them back to the bonfire-repo, but to your own. And from time to time, you still want to pull in the recent changes from the bonfire-repo?

That sounds pretty much like the normal git workflow, just without merging your changes back to original repo. Of course it's possible.

I haven't actually tested it, but it should be something like this:

Create the repo: git init

Add a remote for the bonfire-repo: git remote add bonfire https://github.com/ci-bonfire/Bonfire.git

Pull in the code: git pull bonfire developer (or use the master branch or whatever)

Create project on Github (not a fork of the bonfire-repo, just a new, empty project)

Add a remote for your own repo: git add remote origin git@github.com:<User>/<Project>.git

Make your changes, commit them

Push to your own repo: git push origin master (or whatever branch you like)

Now, if you want to pull in the latest changes from bonfire, just do step 3. again whenever you want. And for your own changes, just keep doing steps 6. and 7.

Title: Two git repositories, one project


答:
Personally, I think that neither version is good, and both are a sign of bad API design on part of the author of Array.

For example, in Ruby (not that I would propose the Ruby core library as an example of good API design) it would be

```<code>do_something if my_array.empty?
</code>```

Which coincidentally is almost the same as your English prose comment.

It also helps making your code more generic, because checking for emptiness is possible in O(1) steps for almost all collections, whereas computing the length may take as long as O(n) (in case of a linked list, for example) or even forever (in case of an infinite lazy stream).

Think about

```<code>list_of_all_primes.empty?
</code>```

vs.

```<code>list_of_all_primes.length.zero? # Oops.
</code>```

Title: Checking for emptiness of collections with (in)equalities - what's the best practice?

Body:
For a long time now I've been in the habit of checking whether a collection (array, dictionary, whatever) is non-empty with a nonequality. Like this:

```<code>if ( MyArray.Length < 1 )
{
    // Do something if the array is empty
}
</code>```

Sometimes I do this for strings too, and other kinds of collections. In practice, this should be the same as

```<code>if ( MyArray.Length == 0 )
{
    // Do something if the array is empty
}
</code>```

Because the length of collection should never be less than 0 anyway, right? So I always thought - what the heck, I'll include the inequality and be double-safe even in the case the sky falls down.

But today a though struck me that the second version might be more readable than the first. It expresses more clearly that the case I'm looking for is the empty array, which is not immediately apparent from the first version. So maybe I should use that instead? Since, you know, if a collection length is less than 0, then I'm screwed anyway.

Which version do you use, and which would you suggest others to use (and why)?

Clarification: This was meant as a question about simple collections, where obtaining .Length is O(1) or otherwise inexpensive. If .Length itself is a nontrivial operation (such as necessitating the iteration through a linked list, or contacting the DB), then this is the wrong approach altogether.

The question was about x < 1 vs x == 0 where x is a nonnegative integer (although it might not be typed as such).

Body:
Personally, I think that neither version is good, and both are a sign of bad API design on part of the author of Array.

For example, in Ruby (not that I would propose the Ruby core library as an example of good API design) it would be

do_something if my_array.empty?

Which coincidentally is almost the same as your English prose comment.

It also helps making your code more generic, because checking for emptiness is possible in O(1) steps for almost all collections, whereas computing the length may take as long as O(n) (in case of a linked list, for example) or even forever (in case of an infinite lazy stream).

Think about

list_of_all_primes.empty?

vs.

list_of_all_primes.length.zero? # Oops.


问:
DDD: Identifying aggregate root
I am designing the a web application using Domain-Driven Design. I have following scenario:

Each Application Group can have one Application and each Application can have multiple Configurations. I am trying figuring out which one will be aggregate object...

Which one will be aggregate roots and why?

答:
I believe Eric Evans wrote, "Models are neither right nor wrong; they are simply more or less useful". The question is, which model helps you solve the problem in a clean way. By just referring to the names of a number of classes, it is impossible for others to determine which model would help you solve your problem.

But as to the why should you choose one model over the other:

If one entity (A) does not make sense to load outside the context of a different entity (B), then entity A should probably be aggregated inside entity B. Also, nobody should reference A in this case.

Just because there is a relationship between your entities doesn't necessarily mean that they should be aggregated.

As an example on an aggregate, I once worked at writing an online job site. One of the features was that a person to create a CV, and companies could search for CVs. A CV would contain a list of competencies (A competency in this context mean something like, "I am higly skilled in .NET. I have used it for 12 years, last in 2012). It does not make sense to load a competency in itself. In only makes sense in the context of a CV. Though you could search for CVs matching certain competency requirements, the result would not be a list of competencies, but a list of CVs meeting the required competencies. So in this example, the CV was an aggregate root.

But are terms like 'Application Group', 'Application', and 'Configuration' really part of your domain, or is it part of your infrastructure? I'm not saying that they couldn't. Depend of course entirely on the nature of the application you are working on. But it does sound a lot like system infrastructure in my ears.

Title: DDD: Identifying aggregate root


问:
What is the best way to allow a non-coding designer to design intranet web pages?
We have an intranet site which was done in .net with plenty of functionality but management wants it to look more visually attractive and get the graphic designer involved.  The graphic designer is NOT a programmer nor has any desire to learn how to code.  She would be updating the main page only. I was trying to figure out how to make it easy for her to update the site.  I was looking into Joomla but it requires PHP, MySQL, and Apache.  Our box is .net/iis/sql.  Does anyone have experience with this?  Just a bit concerned about compatibility issues.  or maybe there is an easier way.  I'm more of a back end guy than a graphics guy.</p>

答:
I'm not sure that there's any 'easy' way: somewhere along the line, someone is going to have to turn the designers non-code ideas into code. Unless you can find a tool to do that automatically, but I somewhat doubt it exists (for pure HTML maybe, but you'll still have to 'weave' that into whatever flavour of .NET you have).

Does the graphic designer have any web experience? It's important, because even if she can't code html/css, she should at least know some of the basic things that you can/can't/shouldn't do.

What you really need is a web designer. Rub the lamp :)


答:
Typically designers will create the look and feel of the site in Photoshop.

Then someone (possibly the designer, possibly a front-end developer) will take the Photoshop (psd) file and convert it to HTML/CSS. Some parts of the psd will be replaced with pure HTML/CSS and some of it will need to be sliced up and used as background images.

Once the redesign is in HTML/CSS then your .NET developer can implement the new look and feel into the intranet site.

As far as I know there is no tool that will let a designer that does not want to touch any code create a .NET site AND let them have full control over the look and feel. WYSIWYG editors are getting better but they still will not deliver the quality custom look of a site that was designed in an app like Photoshop and hand coded into HTML/CSS.

If you don't have a developer that is experienced in converting a Photoshop file to HTML/CSS then I suggest you let management browse the templates at http://themeforest.net/category/site-templates/admin-templates they are pretty good and many will include a layered psd that your designer can customize if needed.

Title: What is the best way to allow a non-coding designer to design intranet web pages?

Body: We have an intranet site which was done in .net with plenty of functionality but management wants it to look more visually attractive and get the graphic designer involved.  The graphic designer is NOT a programmer nor has any desire to learn how to code.  She would be updating the main page only. I was trying to figure out how to make it easy for her to update the site.  I was looking into Joomla but it requires PHP, MySQL, and Apache.  Our box is .net/iis/sql.  Does anyone have experience with this?  Just a bit concerned about compatibility issues.  or maybe there is an easier way.  I'm more of a back end guy than a graphics guy.</p>


问:
Is it legal to use icons from some other application while developing?
On my machine while developing I'm using icons from other application (in particular MS Paint and Paint.NET) as sign for the user that if he chooses to open that file (with our own internal command) it would open in those applications.

Is it legal to extract the icons from those applications and use them? Commit them to repository and then use on all developers' machines (even those that do not have Paint.NET installed)?

Let me make it clear once more. I'm not talking about including those icons in release version. Providing proper icons is up to graphics/skin designer. I'm talking just about the developing process.

Would extracting the icons in run-time either directly or based on file types change anything?

Recently there was a similar question: Can I legally use the icon of a different software? Yet mine differs in that I do not want to release those icons along my application.

EDIT

Let me emphasis an issue which (judging by answers so far) was missed.

If using the icons in above described circumstances was against the license/law (again judging from answers) then how about asking operating system for an icon of the application or an icon associated with the file. This will likely end in showing the very same icon...

How about file browsing apps for which showing those icons is crucial part of their working rather than a nice but minor feature?

How (from license/law point of view) is operating system/file browser/... different from my own developed application that they are (as I assume they are) allowed to query those icons and show them while I'm not. After all one could claim that looking at his beautiful icons in file browser aided my development like unit tests do and so I should pay extra like I do for using those unit tests...

(Also if icon would be queried at run-time from operating system it might be irrelevant whether it is on my development machine or on a released version at client machine...)

答:
Technically speaking, the moment you copy the icon, you have to abide by the licensing terms, or otherwise obtain the copyright holder's permission. So even using them in your own development efforts without ever including them in a distribution could be considered copyright infringement and punishable as such - although the chances of you getting sued over it are probably quite small.

There's an easy practical solution: Use placeholder artwork under a permissive license. Creative Commons is chock-full of icons that are good enough for this purpose, and without any legal obstacles for you - many of them can even be re-released as part of a commercial distribution. Just use those instead of ripping icons from a proprietary product under questionable legal circumstances.


问:
Objective-C message passing related queries
I am learning objective-C after having good knowledge of C/C++. I have 2 questions:

Are Obj-C message passing and C++ vtable, two different ways of implementing polymorphism or Are they two very different concepts which I have misinterpreted into different implementations of same concept?

I read following line from this pdf http://www.gnustep.org/resources/documentation/ObjectivCBook.pdf

Polymorphism takes a pluralistic point of view and notes that several classes can each have a method with the same name. Argument overloading takes the point of the view of the method name and notes that it can have different effects depending on what kind of object it applies to

In essence both do what we want from them i.e. calling method according to the object. What is the difference then?

答:
Both are variants of dynamic dispatch (aka overloading resolved at execution time).

Overloading is for me (I'm not an original, that's Cardelli and Weger classification) a kind of polymorphism. I'm not sure I understand what could be meant here. If I'm guessing correctly, your citation is making a difference between "polymorphism" which would be overloading on the special this parameter resolved at execution time using the dynamic type of the argument, and "overloading" which would be overloading on the other parameters resolved at compilation time (and thus using the static type of the arguments).


问:
At which point do you "know" a technology enough to list it on a resume
I recently had a programmer in for an interview, who listed Python, PHP, Rails and ASP as a few of their skills. In the interview however, they interviewee didn't enough know what control structures and basic logic were, they had only followed a few demo tutorials.

So my question is this: At which point can you add a technology to your resume accurately. Is it when you can demonstrate all basic concepts, write a useful program in it, or are just comfortable using it without having to refer to the documentation every 30 seconds.

I don't believe this is overly subjective, a baseline should easily be established based on feedback.

答:
If all you do is list the skills with no other context, then most people reading your resume would expect you to know those well enough to handle interview questions on them. However, there is plenty of context you can put around each skill to make it more obvious what your level of expertise is. Some examples:

List how long you've used the skill

Java (5 years)

C++ (3 years)

SQL (1 year)

Give each skill a rating

Java (5/5)

C++ (3/5)

SQL (1/5)

List skills in categories

Currently using: Java, C++
Previous experience: SQL

ContentLicense: CC BY-SA 2.5


答:
What AProgrammer said, with one crucial addition: message passing (a la Smalltalk, Objective-C, Ruby) permits the forwarding of a message (for transparent proxies) or even the runtime generation of a method implementing that message.

I'm using Smalltalk terminology, where a message is the name of the function/method being invoked. Objective-C folk would probably call this the selector. When an object receives a message, it looks up in some method dictionary a method corresponding to the message name - some function that actually does something. If no such method is found, the object's #doesNotUnderstand: (Smalltalk) or :method_missing? (Ruby) or - forwardInvocation: (Objective-C) is run.

Thus, an object receiving a message that it does not understand may react to that object in arbitrary ways. That includes, upon receiving such a message, creating a method that can handle this message, and installing that method in the object's method dictionary.

(This is definitely possible in Smalltalk where one normally has a compiler always available; it's probably possibly in Ruby, where you have instance_eval/class_eval. I don't know if it's possible in Objective-C; I don't know the language well enough.)

These things are not possible in languages that use vtable lookup.

Title: Objective-C message passing related queries

Body:
I am learning objective-C after having good knowledge of C/C++. I have 2 questions:

Are Obj-C message passing and C++ vtable, two different ways of implementing polymorphism or Are they two very different concepts which I have misinterpreted into different implementations of same concept?

I read following line from this pdf http://www.gnustep.org/resources/documentation/ObjectivCBook.pdf

Polymorphism takes a pluralistic point of view and notes that several classes can each have a method with the same name. Argument overloading takes the point of the view of the method name and notes that it can have different effects depending on what kind of object it applies to

In essence both do what we want from them i.e. calling method according to the object. What is the difference then?


问:
Software design approach for large relational database
I am working on a personal side project that will utilize a complex and large relational database. During the design of the database I had some co-workers give advice to how I should approach my application; they advised to use the entity framework.

From what I've read and what I am watching it sounds like the entity framework is the right tool for the job. However what I have come to programmer.stackexchange for is to ask whether or not somebody who has just going going in their career should do.

Let me rephrase; I have 3 years web design / development experience (html/css/js/php/mysql) and now about 1 year experience with actual software engineering C#/VB. So the question is should I utilize the entity framework or should I build this rather complex and ambitious project without the entity framework; ergo building all the SQL that will handle massive amounts of relational data?

The reason why I ask is because I want to get the most ROI (knowledge and experience) from the project.

答:
Both approaches will lead to you learning useful, but different skills.

One will help you learn the intricacies of EF, the other will allow you to better learn the raw tsql.

I would consider both important. So, shouldn't you pick what is best for this particular case (EF) and learn it?

There is endless knowledge that can be acquired, concentrate your efforts on the most immediately beneficial.


答:
will utilize a complex and large relational database

OR mappers like EF can help you to avoid tedious work with "complex" models. You have to write less code, especially less CRUD code. On the other hand, when handling a "large" database (in terms of massive amounts of relational data, as you wrote), you have to be careful that the OR mapper does not produce more problems than it solves for you. For such kind of DB, you will typically have to make use of fine-tuned SQLs, SQL bulk processing, stored procedures etc., all things where ORM won't be helpful.

And even when large just means "lot of tables and relations", EF may become a bottleneck, see the links behind this forum post:

http://social.msdn.microsoft.com/Forums/en/adodotnetentityframework/thread/a0f6c057-558c-45d1-98e6-231cc0a41613

Those SO links may be helpful for you, too:

https://stackoverflow.com/questions/6185918/entity-framework-4-1-for-large-number-of-tables-715

https://stackoverflow.com/questions/2981054/entity-framework-4-handling-very-large-1000-tables-data-models

Title: Software design approach for large relational database

Body:
I am working on a personal side project that will utilize a complex and large relational database. During the design of the database I had some co-workers give advice to how I should approach my application; they advised to use the entity framework.

From what I've read and what I am watching it sounds like the entity framework is the right tool for the job. However what I have come to programmer.stackexchange for is to ask whether or not somebody who has just going going in their career should do.

Let me rephrase; I have 3 years web design / development experience (html/css/js/php/mysql) and now about 1 year experience with actual software engineering C#/VB. So the question is should I utilize the entity framework or should I build this rather complex and ambitious project without the entity framework; ergo building all the SQL that will handle massive amounts of relational data?

The reason why I ask is because I want to get the most ROI (knowledge and experience) from the project.


问:
Good workflow for software development with scrum and continuous integration
I'm studying an approach to understand better how the continuous integration workflow fits better in a software development company with the scrum method.

I'm thinking something like this:

Would that be a nice workflow?

答:
First, a caveat: Scrum is a pretty rigorous methodology. I have worked for a couple of organisations that have tried to use Scrum, or Scrum-like approaches but neither of them really came close to using the full discipline in its entirety. From my experiences I am an Agile-enthusiast, but a (reluctant) Scrum-skeptic.

As I understand it, Scrum & other Agile methods have two main objectives:

The first is to provide an explicit mechanism for managing risks and
the ongoing discovery of risks.

The second is to provide a structured mechanism for stakeholder
communication, requirements discovery and requirements management.

The first (risk management) objective is achieved through iterative development; making mistakes and learning lessons quickly, allowing the team to build the understanding and the intellectual capability to reduce risk and move towards a reduced-risk solution with a low-risk "austere" solution already in the bag.

Development Automation, including continuous integration, is the most critical factor in the success of this approach. Risk discovery & Lesson-learning must be fast, friction-free, and free of confounding social factors. (People learn MUCH faster when it is a machine that tells them they are wrong rather than another human - egos only get in the way of learning).

As you can probably tell - I am also a fan of test-driven development. :-)

The second objective has less to do with development automation, and more to do with Human Factors. It is harder to implement because it requires buy-in from the front end of the business, who are unlikely to see the need for the formality.

Development Automation can have a role here, in that automatically generated documentation and progress reports can be used to keep stakeholders outside of the development team continuously updated with progress, and information radiators showing build status and passing/failing test suites can be used to communicate progress on feature development, helping (hopefully) support the adoption of the Scrum communications process.

So, in summary:

The diagram that you used to illustrate your question only captures part of the process. If you wanted to study agile/scrum and CI, I would argue that it is important to consider the broader social and human-factors aspects of the process.

I must end by banging the same drum that I always do. If you are trying to implement an agile process in a real-world project, the best predictor of your chance of success is the level of automation that has been deployed; it reduces friction, increases velocity & paves the road to success.


问:
Choosing a restrictive license to be in compliance, but not enforcing it
I'm very curious about this: Lets say that you have to use the GPL in your library because some dependency uses it or (if your library is fork) the upstream library uses GPL. Now GPL doesn't play well with a couple of important open source licenses which means that some users simply can't use your librar because of licensing issues, which doesn't help anybody

An option that I've been toying with is still using GPL to maintain dependency compatibility but telling users that I will not enforce it against open source software or (if that's way too broad) software that uses open source but not completable licenses like Apache, MPL, CC, etc.

Would there be any legal ramifications of doing this? Would this put my users at legal risk?

答:
Your best option would be to structure / package your library such that users of your library would not be bound by the GPL.  The FSF FAQ describes a few means of how this can be achieved.

This is the "viral" aspect of GPL, and yes, you would potentially be exposing your future users to legal issues.  More importantly, most users wouldn't / shouldn't use your package for risk of violating the GPL.

Here's why.

http://www.gnu.org/licenses/gpl-faq.html#WhoHasThePower

``` the copyright holders of the software are the ones who have the power to enforce the GPL
```

You stated that you are working on a forked project that is GPL'd, so you are not the sole copyright owner of the product.  So while you may rescind your right to enforce the copyright, you cannot make that claim for all of the other copyright holders unless they have also made that claim.  At which point, the project is public domain and not GPL but that's off topic.

If your users only use your library for internal, never-distributed-to-the-public applications, then they would be okay with using your libraries.  I suspect that's not your target audience though.

http://www.gnu.org/licenses/gpl-faq.html#GPLRequireSourcePostedPublic

As I alluded to, there are several options that you can consider depending upon which version of the GPL is in effect.  For example, if your users can call your library / use its output after a fork or an exec, then your library is not considered part of their application.  You may be able to relicense your fork of the project to a more compatible GPL version.   Check out the following links to see what's going to work for you.

http://www.gnu.org/licenses/gpl-faq.html#GPLAndPlugins
http://www.gnu.org/licenses/gpl-faq.html#LinkingWithGPL

Their FAQ is well worth the read and you will discover quite a few options to work with.

Body:
Your best option would be to structure / package your library such that users of your library would not be bound by the GPL.  The FSF FAQ describes a few means of how this can be achieved.

This is the "viral" aspect of GPL, and yes, you would potentially be exposing your future users to legal issues.  More importantly, most users wouldn't / shouldn't use your package for risk of violating the GPL.

Here's why.

http://www.gnu.org/licenses/gpl-faq.html#WhoHasThePower

 the copyright holders of the software are the ones who have the power to enforce the GPL

You stated that you are working on a forked project that is GPL'd, so you are not the sole copyright owner of the product.  So while you may rescind your right to enforce the copyright, you cannot make that claim for all of the other copyright holders unless they have also made that claim.  At which point, the project is public domain and not GPL but that's off topic.

If your users only use your library for internal, never-distributed-to-the-public applications, then they would be okay with using your libraries.  I suspect that's not your target audience though.

http://www.gnu.org/licenses/gpl-faq.html#GPLRequireSourcePostedPublic

As I alluded to, there are several options that you can consider depending upon which version of the GPL is in effect.  For example, if your users can call your library / use its output after a fork or an exec, then your library is not considered part of their application.  You may be able to relicense your fork of the project to a more compatible GPL version.   Check out the following links to see what's going to work for you.

http://www.gnu.org/licenses/gpl-faq.html#GPLAndPlugins
http://www.gnu.org/licenses/gpl-faq.html#LinkingWithGPL

Their FAQ is well worth the read and you will discover quite a few options to work with.


问:
Plagued by multithreaded bugs
On my new team that I manage, the majority of our code is platform, TCP socket, and http networking code. All C++.  Most of it originated from other developers that have left the team. The current developers on the team are very smart, but mostly junior in terms of experience.

Our biggest problem: multi-threaded concurrency bugs. Most of our class libraries are written to be asynchronous by use of some thread pool classes. Methods on the class libraries often enqueue long running taks onto the thread pool from one thread and then the callback methods of that class get invoked on a different thread. As a result, we have a lot of edge case bugs involving incorrect threading assumptions.  This results in subtle bugs that go beyond just having critical sections and locks to guard against concurrency issues.

What makes these problems even harder is that the attempts to fix are often incorrect. Some mistakes I've observed the team attempting (or within the legacy code itself) includes something like the following:

Common mistake #1 - Fixing concurrency issue by just put a lock around the shared data, but forgetting about what happens when methods don't get called in an expected order.  Here's a very simple example:

```<code>void Foo::OnHttpRequestComplete(statuscode status)
{
    m_pBar->DoSomethingImportant(status);
}

void Foo::Shutdown()
{
    m_pBar->Cleanup();
    delete m_pBar;
    m_pBar=nullptr;
}
</code>```

So now we have a bug in which Shutdown could get called while OnHttpNetworkRequestComplete is occuring on. A tester finds the bug, captures the crash dump, and assigns the bug to a developer. He in turn fixes the bug like this.

```<code>void Foo::OnHttpRequestComplete(statuscode status)
{
    AutoLock lock(m_cs);
    m_pBar->DoSomethingImportant(status);
}

void Foo::Shutdown()
{
    AutoLock lock(m_cs);
    m_pBar->Cleanup();
    delete m_pBar;
    m_pBar=nullptr;
}
</code>```

The above fix looks good until you realize there's an even more subtle edge case. What happens if Shutdown gets called before OnHttpRequestComplete gets called back? The real world examples my team has are even more complex, and the edge cases are even harder to spot during the code review process.

Common Mistake #2 - fixing deadlock issues by blindly exiting the lock, wait for the other thread to finish, then re-enter the lock - but without handling the case that the object just got updated by the other thread!

Common Mistake #3 - Even though the objects are reference counted, the shutdown sequence "releases" it's pointer. But forgets to wait for the thread that is still running to release it's instance. As such, components are shutdown cleanly, then spurious or late callbacks are invoked on an object in an state not expecting any more calls.

There are other edge cases, but the bottom line is this:

Multithreaded programming is just plain hard, even for smart people.

As I catch these mistakes, I spend time discussing the errors with each developer on developing a more appropriate fix. But I suspect they are often confused on how to solve each issue because of the enormous amount of legacy code that the "right" fix will involve touching.

We're going to be shipping soon, and I'm sure the patches we're applying will hold for the upcoming release. Afterwards, we're going to have some time to improve the code base and refactor where needed. We won't have time to just re-write everything. And the majority of the code isn't all that bad. But I'm looking to refactor code such that threading issues can be avoided altogether.

One approach I am considering is this. For each significant platform feature, have a dedicated single thread where all events and network callbacks get marshalled onto. Similar to COM apartment threading in Windows with use of a message loop. Long blocking operations could still get dispatched to a work pool thread, but the completion callback is invoked on on the component's thread. Components could possibly even share the same thread. Then all the class libraries running inside the thread can be written under the assumption of a single threaded world.

Before I go down that path, I am also very interested if there are other standard techniques or design patterns for dealing with multithreaded issues.  And I have to emphasize - something beyond a book that describes the basics of mutexes and semaphores. What do you think?

I am also interested in any other approaches to take towards a refactoring process.  Including any of the following:

Literature or papers on design patterns around threads. Something beyond an introduction to mutexes and semaphores. We don't need massive parallelism either, just ways to design an object model so as to handle asynchronous events from other threads correctly.

Ways to diagram the threading of various components, so that it will be easy to study and evolve solutions for. (That is, a UML equivalent for discussing threads across objects and classes)

Educating your development team on the issues with multithreaded code.

What would you do?

答:
Other posters have commented well on what should be done to fix the core issues.  This post is concerned with the more immediate problem of patching the legacy code well-enough to buy you time to redo everything the right way.  In other words, this isn't the right way to do things, its just a way to limp along for now.

Your idea of consolidating key events is a good start.  I would go so far as to use a single dispatch thread to handle all key synchronization events, wherever there is order dependency.  Setup a thread-safe message queue and wherever you currently perform concurrency sensitive operations (allocations, cleanups, callbacks, etc.), instead send a message to that thread and have it perform or  trigger the operation.  The idea is that this one thread controls all work-unit starts, stops, allocations, and cleanups.

The dispatch thread does not solve the problems you described, it just consolidates them in one place.  You still have to worry about events/messages occurring in unexpected order.  Events with significant run-times will still need to be sent off to other threads, so there are still issues with concurrency on shared data.  One way to mitigate that is to avoid passing data by reference.  Whenever possible, the data in dispatch messages should be copies which will be owned by the recipient.  (This is along the lines of making data immutable that others have mentioned.)

The advantage of this dispatch approach is that within the dispatch thread you have a kind of safe-haven where you at least know that certain operations are occurring sequentially.  The disadvantage is that it creates a bottleneck and extra CPU overhead.  I suggest not worrying about either of those things at first: focus on gaining some measure of correct operation first by moving as much as you can into the dispatch thread.  Then do some profiling to see what is taking up the most CPU time and begin shifting it back out of the dispatch thread using correct multithreading techniques.

Again, what I'm describing is not the right way to do things, but its a process that can move you toward the right way in increments that are small enough to meet commercial deadlines.

Title: Plagued by multithreaded bugs


答: You would be the one responsible for enforcing the GPL on anyone who uses your project, so if you have no intention of enforcing it then your users would only have to worry about you lying in an attempt to trap them. They may also have to worry about the owner of whatever GPL library you link to, due to the viral nature of the GPL. Your best option is to find a way to circumvent having to release your project under the GPL, as its really the only "safe" method.</p>

Title: Choosing a restrictive license to be in compliance, but not enforcing it

Body:
I'm very curious about this: Lets say that you have to use the GPL in your library because some dependency uses it or (if your library is fork) the upstream library uses GPL. Now GPL doesn't play well with a couple of important open source licenses which means that some users simply can't use your librar because of licensing issues, which doesn't help anybody

An option that I've been toying with is still using GPL to maintain dependency compatibility but telling users that I will not enforce it against open source software or (if that's way too broad) software that uses open source but not completable licenses like Apache, MPL, CC, etc.

Would there be any legal ramifications of doing this? Would this put my users at legal risk?


答:
In terms of learning:

Both are useful for most developer careers.

If you use EF in your project, you'll obtain experience you can use with other ORMs.

If you don't use EF in this project, you'll have more experience with raw SQL which will serve you later for other databases.

Depending on your career:

EF would be better if you know that you will probably spend most of your time in the future developing CRUD applications. They often benefit a lot from ORMs, so most are relying on ORMs with practically no direct access to the database.

No EF would be better if you know that you will handle applications which doesn't use ORMs either because they have a structure too inappropriate for ORMs or because they use lots of legacy code or just because they are written in languages where there are no good quality ORMs.

Note that if you have little experience with actual software engineering, you must be careful when using EF: be sure to understand how your code is translated into SQL queries by EF, and also be sure to understand the queries themselves. The best way to do it is through extensive SQL profiling. If you see something you didn't expect, search and find why the code was translated this way.

Seriously, do it. Lots of people who start using ORMs with little or no experience in SQL are finding themselves writing terrible code which doesn't do what they are expecting, and when, once on production server, they notice that their code runs the exact same query several hundred times instead of one, it's <s>too late</s> too expensive to solve.

In terms of performance:

EF is neither slow nor fast. If you're using it correctly, your application will be fast enough. If something is slow, use the profiler to find where is the bottleneck, and if you find that the slowness is caused by EF, and not how you use it, then do a direct query to solve this bottleneck.


问:
Quantifying the price for source code and software product
I'm about to undertake a project. This requires me to write code, and tons of it. The client's requirement is to hand in all source code at the end of the project.

My question is: How do I quantify the price for source code and the software product? Is there any metric that one follows to determine pricing? How would I quantify the software product?

Extra info: The application must run anywhere, in any OS, including tablets (iPad, Galaxy tabs, etc.), Smartphones (iPhone, Android phones, etc.) and also on the web.
(Now, imagine how much code this will be).

答:
Do not accept a project when its not clear both the outcome and the money the client need to pay. I just do the following:

Come up with steps and payments the client need to do.

When the previous step is done and fully paid and the client is happy move to the next.

For the payment method, chose the payment based on the features. So if the client has the opportunity to drop the features if he/she cant not pay the whole project.

Getting paid based on lines of code (LOC) is a stupid thing. Because LOC does not mean anything!. Be smart write a good code and charge based on the feature!.

Good luck,


问:
Fear of releasing a hobby project - how to overcome?
I don't know if this question is strictly related to software development, but still I'll give it a try:

Like a lot of programmers, I love to work on hobby projects. Sometimes, seemingly good ideas turn out to be not so good, so I drop the project. But sometimes, something useful comes out of the project. So, I could release it, present it to the world, right?

Wrong. Somehow, I don't seem to be able to make this step. I fear that my code is not good enough, I can always think of things which are suboptimal, of features which could be added. So, I don't release anything, I lose interest, and at one point abandon the project.

Is this normal? How do you overcome such a situation?

答:
Completely normal, in any domain beyond software as well. Make sure it builds in a few different environments, write a README, and toss it to github/codeplex/etc. Getting through this the first time is the only way to overcome the anxiety.

Second, third, and n-th times are where the fun lies!


答:
Getting contributors into an open source project that is already bug-free is probably harder than ones with lots of easy bugs to solve, as these bugs are an incentive for early users to make themselves familiar with the code.

When Linus first introduced Linux kernel, it wasn't a complete, stable, bug-free, and clean code; it was an incomplete, crappy, unportable, and hardwired for Finnish keyboard.

Title: Fear of releasing a hobby project - how to overcome?

Body:
I don't know if this question is strictly related to software development, but still I'll give it a try:

Like a lot of programmers, I love to work on hobby projects. Sometimes, seemingly good ideas turn out to be not so good, so I drop the project. But sometimes, something useful comes out of the project. So, I could release it, present it to the world, right?

Wrong. Somehow, I don't seem to be able to make this step. I fear that my code is not good enough, I can always think of things which are suboptimal, of features which could be added. So, I don't release anything, I lose interest, and at one point abandon the project.

Is this normal? How do you overcome such a situation?


答:
If you have some time to dedicate to refactoring your application, I would advise you to take a look at the actor model (see e.g. Theron, Casablanca, libcppa, CAF for C++ implementations).

Actors are objects that run concurrently and communicate with each other only using asynchronous message exchange. So, all the problems of thread management, mutexes, deadlocks, etc, are dealt with by an actor implementation library and you can concentrate on implementing the behaviour of your objects (actors),
which boils down to repeating the loop

Receive message

Perform computation

Send message(s) / create / kill other actors.

One approach for you could be to do some reading on the topic first, and possibly have a look at one library or two to see if the actor model can be integrated in your code.

I have been using (a simplified version of) this model in a project of mine for a few months now and I am amazed by how robust it is.

Title: Plagued by multithreaded bugs


问:
When using method chaining, do I reuse the object or create one?
When using method chaining like:

var car = new Car().OfBrand(Brand.Ford).OfModel(12345).PaintedIn(Color.Silver).Create();
```

<p>there may be two approaches:</p>

<ul>
<li><p>Reuse the same object, like this:</p>

<pre class="lang-cs prettyprint-override"><code>public Car PaintedIn(Color color)
{
    this.Color = color;
    return this;
}
</code>```

Create a new object of type Car at every step, like this:

public Car PaintedIn(Color color)
{
    var car = new Car(this); // Clone the current object.
    car.Color = color; // Assign the values to the clone, not the original object.
    return car;
}
```</li>
</ul>

<p>Is the first one <em>wrong</em> or it's rather a personal choice of the developer?</p>

<hr>

<p>I believe that he first approach may quickly cause the intuitive/misleading code. Example:</p>

<pre class="lang-cs prettyprint-override"><code>// Create a car with neither color, nor model.
var mercedes = new Car().OfBrand(Brand.MercedesBenz).PaintedIn(NeutralColor);

// Create several cars based on the neutral car.
var yellowCar = mercedes.PaintedIn(Color.Yellow).Create();
var specificModel = mercedes.OfModel(99).Create();

// Would `specificModel` car be yellow or of neutral color? How would you guess that if
// `yellowCar` were in a separate method called somewhere else in code?
</code>```

Any thoughts?

答:
I see a few problems here that I think might be confusing... Your first line in the question:

```<code>var car = new Car().OfBrand(Brand.Ford).OfModel(12345).PaintedIn(Color.Silver).Create();
</code>```

You're calling a constructor (new) and a create method... A create() method would almost always be a static method or a builder method, and the compiler should catch it in a warning or error to let you know, either way, this syntax is either wrong or has some terrible names. But later on, you don't use both, so let's look at that.

```<code>// Create a car with neither color, nor model.
var mercedes = new Car().OfBrand(Brand.MercedesBenz).PaintedIn(NeutralColor);

// Create several cars based on the neutral car.
var yellowCar = mercedes.PaintedIn(Color.Yellow).Create();
var specificModel = mercedes.OfModel(99).Create();
</code>```

Again with the create though, just not with a new constructor. Thing is, I think you're looking for a copy() method instead. So if that's the case, and it's just a poor name, let's look at one thing...  you call mercedes.Paintedin(Color.Yellow).Copy() - It should be easy to look at that and tell it's being 'painted' before being copied - just a normal flow of logic, to me. So put the copy first.

```<code>var yellowCar = mercedes.Copy().PaintedIn(Color.Yellow)
</code>```

to me, it is easy to see there that you are painting the copy, making your yellow car.

Body:
I see a few problems here that I think might be confusing... Your first line in the question:

var car = new Car().OfBrand(Brand.Ford).OfModel(12345).PaintedIn(Color.Silver).Create();

You're calling a constructor (new) and a create method... A create() method would almost always be a static method or a builder method, and the compiler should catch it in a warning or error to let you know, either way, this syntax is either wrong or has some terrible names. But later on, you don't use both, so let's look at that.

// Create a car with neither color, nor model.
var mercedes = new Car().OfBrand(Brand.MercedesBenz).PaintedIn(NeutralColor);

// Create several cars based on the neutral car.
var yellowCar = mercedes.PaintedIn(Color.Yellow).Create();
var specificModel = mercedes.OfModel(99).Create();

Again with the create though, just not with a new constructor. Thing is, I think you're looking for a copy() method instead. So if that's the case, and it's just a poor name, let's look at one thing...  you call mercedes.Paintedin(Color.Yellow).Copy() - It should be easy to look at that and tell it's being 'painted' before being copied - just a normal flow of logic, to me. So put the copy first.

var yellowCar = mercedes.Copy().PaintedIn(Color.Yellow)

to me, it is easy to see there that you are painting the copy, making your yellow car.


答:
They are very, very different mechanisms that provide vastly different features.

The C++ virtual dispatch mechanism is like a function pointer.  The C++ compiler generates a construction function that fills a thunking table with pointers for calling functions.  The lookup is as quick as calling void(*)().  This is completely static though and doesn't allow for replacing functions during runtime (although this could probably be done) expanding functionality or providing symbolic lookup like @signature("helloWorld").  If you want to do this in C++ you have to write it in, like Qt did and has a moc that generates the crap that has to occur.

The Objective-C message system is utterly different.  There's this objc_msg_lookup or whatever function.  Because in Objective-C the messages that an object can respond to can change on the fly, during runtime, there is absolutely no way to build a virtual dispatch like C++ has.  Instead you have some sort of message id, maybe even a string since the system also has to be able to find @signatures or whatever they were, that is searched every time you make a call.  This is why the language has the IMPL thingy that gives you a function pointer to call when you are in a tight loop or something.

It's been years since I've worked in Objective-C but I very much doubt this has changed.

Which is better?  Neither.  Each is better for different things.