DEV Community

Discussion on: Builder Design Pattern

Collapse
 
feacur profile image
Leonid Kapitonov • Edited

Thank you for the article.

I want to add couple-o-things. I'm sorry if I sound pushy, please feel free to parry my notes and point my mistakes.

Please, oh please, do use named arguments for vague stuff (concerning methods as well):

  • C#: Burger burger = new Burger(size: 14, cheese: true, tomato: true, lettuce: false, pepperoni: false);
  • Java: Burger burger = new Burger(/*size*/ 14, /*cheese*/ true, /*tomato*/ true, /*lettuce*/ false, /*pepperoni*/ false);
  • Kotlin: Burger burger = new Burger(size = 14, cheese = true, tomato = true, lettuce = false, pepperoni = false);

Remember about default values, which is a thing in C# and Kotlin. Sorry, Java.

Also you can place these setters inside original Burger class. Unfortunately, this way object initialization wouldn't be atomic anymore.

I just checked google, so I wouldn't suggest using double braces initialization for Java. C# initializers are OK, though, and atomic. I do not know of the same stuff for Kotlin, but its syntax for constructors is great in the first place.

Basically, the problem grows out of Java itself, because I see more elegant solutions in other languages like C# and Kotlin. At least more complex example required in order to favour builders and factories.

Collapse
 
nishparadox profile image
Nishan Pantha

True that. It'd be much easier if there was a concept like named argument in languages like Java.

Collapse
 
miffpengi profile image
Miff

If you don't need your properties to be necessarily set at creation, you can also set properties when constructing the object in C# even if they're not in the constructor.

var burger = new Burger(14){ Cheese = true, Tomato = true, Lettuce = false, Pepperoni = false };
Enter fullscreen mode Exit fullscreen mode