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

Posted by MainMa on Programmers See other posts from Programmers or by MainMa
Published on 2012-05-25T08:54:26Z Indexed on 2012/05/31 22:50 UTC
Read the original article Hit count: 412

When using method chaining like:

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

there may be two approaches:

  • Reuse the same object, like this:

    public Car PaintedIn(Color color)
    {
        this.Color = color;
        return this;
    }
    
  • 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;
    }
    

Is the first one wrong or it's rather a personal choice of the developer?


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

// 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?

Any thoughts?

© Programmers or respective owner

Related posts about coding-style

Related posts about readability