The builder pattern is nice and useful, and using Lombok @Builder annotation instead of implementing it each time can save a lot of time.
However, there is one problem with this. You can’t really define a required field.
For example, Let’s assume we have this class:
The usage will be like this:
MyClass obj1 = MyClass.builder().name("Name").email("Email").build();
MyClass obj2 = MyClass.builder().build();
In this example, I have built 2 objects: obj1 and obj2.
obj1 was provided with all the arguments but obj2 was built without providing any argument, means both name and email will remain null.
One solution is to add a unit test for the places that are using this class and make sure we got an error in case something is not provided, but this solution is not scalable. Maybe we are covering all the cases today, but another field may be added tomorrow and we can easily forget to update it somewhere.
What I found to be really useful is the @NonNull annotation (which is part of Lombok as well).
By adding the @NonNull annotation to the required fields, in case a field is not supplied, a NullPointerException will be thrown.
So, if we’ll change our class to this:
And take a look at our example, obj1 will be built as expected, but the builder of obj2 (which try to call the private constructor of MyClass with a null value) will throw a NullPointerException.
Using this technique, we can catch missing stuff early during the run of our unit tests instead of in some specific cases after deployment and it’s good for documentation as well 🙂
More information about the @NonNull annotation can be found on Lombok website.