Design Patterns: Builder
Since always it’s correct to say that as our application grows, the classes and objects usually become more and more complex. All of this complexity is just a reflection of our real world.
Invoice with many attributes, receiving all of them in the constructor method:
Creating an invoice:
Too many parameters, huh? This class works perfectly, but it’s difficult to be used. Some parameters can be optional, and we don’t know if there’s any rules to build it (like the taxes calculation).
I’ll show you something that will make your life better, in order to ease the use of the constructor method.
The Builder pattern
The builder pattern has the intention to separate the construction of a complex object from its representation. By doing so, the same construction process can create different representations (Gang of Four).
So, let’s create a class that will build our
Consuming the builder:
Better? The creation logic of any invoice is abstracted now. The use of the method chaining made our class more fluent, and our code cleaner too. :)
That’s all folks! Thanks, hope to see you soon!!!