When using method chaining, do I reuse the object or create one?
- by MainMa
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?