In this blog post, we’ll explore how you can utilize Lombok @NonNull annotation to make your code more resilient against null-related issues.
What is @NonNull?
The @NonNull annotation in Lombok is designed to help you automatically generate null checks for your variables. By annotating a variable or a method parameter with @NonNull, Lombok will insert a null check at the beginning of the method or constructor, and if the check fails, a NullPointerException will be thrown.
Without Project Lombok
Without Lombok @NonNull annotation, we need to manually write a code to handle null pointer exceptions:package net.javaguides.lombok.nonnull;
import net.javaguides.lombok.User;
public class NonNullExample {
private String name;
public NonNullExample(User user) {
if (user == null) {
throw new NullPointerException("person is marked @NonNull but is null");
}
this.name = user.getFirstName();
}
public static void main(String[] args) {
NonNullExample example = new NonNullExample(null);
}
}
With Project Lombok
With Project Lombok, we are not writing any code to handle null pointer null but we are just adding @NonNull annotation:package net.javaguides.lombok.nonnull; import lombok.NonNull; import net.javaguides.lombok.User; public class NonNullLombokExample { private String name; public NonNullLombokExample(@NonNull User person) { this.name = person.getFirstName(); } public static void main(String[] args) { NonNullLombokExample example = new NonNullLombokExample(null); } }The @NonNull annotation automatically generates that null check for you.
Common Use Cases
Method Parameters: As seen above, you can use @NonNull to annotate method or constructor parameters to ensure that they are never passed a null value.
Field Initialization: You can use @NonNull on fields that are expected to be initialized immediately, either directly or through a constructor.
Limitations and Considerations
While @NonNull is beneficial, there are certain things to keep in mind:
Lombok doesn't add null-checks everywhere: and Lombok adds null-checks in constructors, setters, and builder methods. It won't add checks to general methods or in other places.
Runtime Overhead: Remember that the checks Lombok adds are runtime checks. They will slightly increase the execution time whenever they're triggered. However, this overhead is usually negligible.
Debugging: If you're not familiar with Lombok, it might initially be confusing when you see a NullPointerException thrown from a line that doesn't contain an explicit null check. It's essential to remember that Lombok has added these checks during the compilation process.
Comments
Post a Comment
Leave Comment