Search code examples
javabuilderpojolombok

How to Enforce instantiation of immutable pojo with mandatory variables?


Problem Statement

I want to enforce such a situation that whenever the instance of the immutable pojo is to created all the mandatory variables must be passed in as parameters.

Let's Suppose I have Pojo like this

public class pojo {
    private final String str;
    private int number;
}

Now, As I said the pojo is immutable, I am using Lombok's Builder and Getter annotation. Something Like,

@Getter
@Builder
public class pojo {
    private final String str;
    private int number;
}

Now, In this pojo the variable str is mandatory, and any instance of class pojo without a valid value of str is of no requirement.

Now, Object of class Pojo can be constructed using Builder in such a way

pojo obj = pojo.builder().build();

But the field str is mandatory and the above statement will create an object with str = null and number = 0. Now i can make use of @NonNull over str to ensure that Object creation throws a Null pointer Exception at runtime if someone tries to build the object of pojo without specifying str. But I want to enforce this check at compile time, Is there a way to stop object creation if str is not given as paramter?


Solution

  • You can do this if you write your Builder by hand. Have your builder() factory method return a class like UnreadyBuilder which doesn't have a build() method. Then the setName() setter (or whatever it's called) on UnreadyBuilder can return a ReadyBuilder object which does have a build() method.

    That said: do you really need this to be checked at compile time? It's a lot of extra code for a pretty marginal benefit.