Yippie-Ki-Yay
Yippie-Ki-Yay

Reputation: 22814

C# construction objects with builder

Fluent builder is a well-known pattern to build objects with many properties:

Team team = teamBuilder.CreateTeam("Chelsea")
    .WithNickName("The blues")
    .WithShirtColor(Color.Blue)
    .FromTown("London")
    .PlayingAt("Stamford Bridge");

However, using it doesn't seem very clear to me due to one particular reason:

Now, how should the Fluent builder approach be used considering that you have to maintain this state?

Should the With_XYZ members modify the part of the object, that can't affect this state?

Maybe there are some general rules for this situation?


Update:

If the CreateTeam method should take the mandatory properties as arguments, what happens next?

Upvotes: 4

Views: 1908

Answers (2)

Michael S. Scherotter
Michael S. Scherotter

Reputation: 10785

CreateTeam() should have the mandatory the properties as parameters.

Team CreateTeam(string name, Color shirtColor, string Town)
{
}

Upvotes: 8

radarbob
radarbob

Reputation: 5101

Seems to me the points of Fluent Interface are:

  • Minimize the number of parameters to zero in a constructor while still dynamically initializing certain properties upon creation.
  • Makes the property/ parameter-value association very clear - in a large parameter list, what value is for what? Can't tell without digging further.
  • The coding style of the instantiation is very clean, readable, and editable. Adding or deleting property settings with this formatting style is less error prone. I.E. delete an entire line, rather than edit in the middle of a long parameter list; not to mention editing the wrong parameter

Upvotes: 3

Related Questions