StepBuilder Pattern
The StepBuilder pattern, a lesser-known sibling of the Builder pattern.
Unlike traditional builders, StepBuilder guides developers through a structured, more intuitive creation process, making it a valuable addition to your toolkit.
What does it solve ?
In contrast to a conventional builder pattern, the StepBuilder takes on the role of guide through the object creation process.
Each steps declare the next step so that the developer can not do any mistake or forget some mandatory steps.
With step builder, you can really imagine the creation of your object as a succession of steps to walk into. No traps just keep going one step after another till you reach your goal -> build your object instance.
Example
Imagine an email composed of a subject
, content
, sender
, receiver
.
With a generic builder generated by Lombok by example, you would be able to write something like:
var myEmail = Email.builder()
.withSubject("my subject")
.withContent("Hello World")
.withSender("sender@gmail.com")
.withReceiver("receiver@gmail.com")
.build();
This would build an email instance without any problem.
But on the other hand it also allows to write it like that:
var myEmail = Email.builder()
.withSubject("my subject")
.build();
Or even worse like that:
var myEmail = Email.builder()
.build();
And this will compile perfectly fine. Only at runtime you might figure out that some properties are not defined...
Wouldn't it be better if we could check that at compile time ?
There comes the step builder !
With a step builder you can't omit any mandatory property. Each step define its successor(s) and there is no way to bypass it. (At compile time!)
(Note: this does not prevent to have optional steps or paths)