Search code examples
c#design-patternsconstructorbuilderfluent-interface

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:

  • Every Team object has its minimal operational state, in other words, set of properties which have to be set (mandatory), so that the object is ready to use.

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?

  • What happens if I (for example) omit the WithNickName call?

  • Does this mean that the nickname should be defaulted to some DefaultNickname?

  • Does this mean that the example (see the link) is bad, because the object can be left in invalid state?

  • And, well, I suspect that in this case the fluent building approach actually loses it's "beauty", doesn't it?


Solution

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

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