I've been reading a bunch of blog posts espousing the virtues of the Test Data Builder Pattern. It seems like a good idea, but all of the posts are years old.
When C# introduced Object Initializes, did it make the Test Data Builder pattern obsolete?
Before Object Initializers, you would have needed the following code to initialize a person object:
Person p = new Person("John", "Doe", "555-555-1234");
At the time, having a builder would have cleaned up the code like this:
Person person = new PersonBuilder()
.WithFirstName("John")
.WithLastName("Doe")
.WithPhoneNumber("555-555-1234");
Now with object initializers, it can look like this without writing any builder methods:
Person p = new Person() {FirstName="John", LastName="Doe", Phone="555-555-1234"};
In this simple example, it would seem that the builder pattern is not needed. Am I missing something? Do people still use the builder pattern? If so, what are the benefits?
Advantages of the Builder pattern include: Allows you to vary a product's internal representation. Encapsulates code for construction and representation. Provides control over steps of construction process.
Using the Builder pattern to construct test fixtures Using a Builder allows test fixtures to be created more easily, and with clearer intent. The type of test objects I typically use this Builder approach for are domain model objects, such as Account, User, Widget or whatever.
The builder pattern, as the name implies, is an alternative way to construct complex objects. This pattern should be used when we want to build different immutable objects using the same object building process. 3.
Here are key consequences of the Builder pattern: It lets you vary a product's internal representation. The Builder object provides the director with an abstract interface for constructing the product. The interface lets the builder hide the representation and internal structure of the product.
In many cases you can replace builders with object initializers.
However, there are a few cases where builders are still a good option.
Immutable objects is one example. e.g. Jon Skeets protobuff implementation is a good example of real world builder pattern for immutable objects. (https://codeblog.jonskeet.uk/2008/08/20/lessons-learned-from-protocol-buffers-part-1-messages-builders-and-immutability/)
Person john = new Person.Builder()
.SetFirstName("John")
.SetLastName("Doe")
.Build(); //creates an immutable person
Other cases might be to apply preset values. eg.
Rectangle rect = RectangleBuilder.MakeSquare(10).Build();
Car car = CarBuilder.MakeVolvo().PimpIt().SetColor(Color.Red).Build();
In this case you might set multiple properties at once so you can start from a prototype of some sort and continue from there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With