简体   繁体   中英

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?

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

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

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. IE delete an entire line, rather than edit in the middle of a long parameter list; not to mention editing the wrong parameter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM