TransWikia.com

Builder Pattern: Is there any advantage of having instance variables + product reference instead of just product reference?

Software Engineering Asked by user3760100 on October 29, 2021

Consider the product class:

class Car {
   private String color;
   private String model_num;
   //getters and setters for the above fields
}

Consider builder class 1:

class CarBuilder1 {
   private Car car;
   //setters for color, model_num
   //build() method returning car obj
}

Now, consider builder class 2:

class CarBuilder2 {
   private Car car;
   private String color;
   private String model_num;
   //setters for color,model_num
   //build() which instantiates car object using fields and returns it
}

We are using 2x the memory of Car class with CarBuilder1, when we can just have one set of variables(already present in the Car object) in CarBuilder2. Yet I see lot of places using CarBuilder1, is there any specific reason for this? Is there any advantage of CarBuilder1 over CarBuilder2 which makes people willing to compromise on the extra storage required?

2 Answers

The builder pattern is meant to encapsulate the steps of the creation process:

  • CarBuilder2 is a variant of Joshua Bloch's builder pattern. The main intent is to facilitate the creation of objects that require many parameters in their constructor.

  • CarBuilder1 is a lighter variant of this pattern that is possible if an only if the Car constructor has no side-effect, and parameters are not mandatory at construction and unused objects are destroyed/garbage-collected automatically. If these conditions are met, it provides the same result without the overhead.

Variant 1 is often used, in situations when object expose a lot of setters and don't care about initial state. Since both builders expose the same interface, if Car constructor evolves to make the model and the color required, you could still evolve to CarBuilder2 without any effect on the clients of the builder.

Remark: the extra storage is btw probably not the reason, because once the build is completed, the builder can be destroyed or garbage-collected. The reason is probably to avoid a lot of boiler-plate code

Answered by Christophe on October 29, 2021

Variables consume 64 bits or so, so 8 bytes. Primitives all fit in that, and objects are kept as references to the heap. So, we are talking about 16 bytes or so. I don't think that matters that much.

Also, I just want to mention: Don't use getters/setters, they are bad for you! Setters more so than getters, but they're both bad. Object-orientation is about having behavior in your objects.

Answered by Robert Bräutigam on October 29, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP