Marking field as required when using Lombok Builder
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:
1 2 | 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.
– Alexander
4 thoughts on “Marking field as required when using Lombok Builder”
But we still need to remember to have relevant unit test.
It would be better to not allow compile a class.
You are right, you still need to have unit tests to cover it.
If you can share a better way that will identify this during compilation time,
I am willing to learn ๐
IMHO, bad approach.
Your client don’t know the required fields until exact developer takes a look to the builder code.
Yes, client should not able to build my class object until they provide all required field.
As I am owner of this class I know better how to create this class in terms of all required filed.