DEV Community

RyTheTurtle
RyTheTurtle

Posted on

QuickBytes: Stop Using Lombok's @NonNull

Lombok is a powerful, if controversial, library that adds brevity and expressiveness to Java through it's annotation processing. One of the most popular annotations I see used in projects leveraging Lombok is the @NonNull annotation. This annotation is commonly used to indicate that a field or method parameter is not supposed to be null.

public void foo(@NonNull String bar){ 
    // bar will not be null here
}
Enter fullscreen mode Exit fullscreen mode

The problem with this is communication. Many times I see developers using this on their methods and classes as a standard procedure for anything that's expected to not be null. Upon further inspection, the reason often boils down to "if this field is null it will cause an exception, so I put @NonNull here to make sure it's not null".

The problem is that, per the Lombok documentation, @NonNull simply generates a null check condition at the top of your method and throws a NullPointerException if the value is null.

This is rarely the intended or desired behavior for a method. Instead, prefer a more thoughtful approach to handling input validation

  • If you can gracefully handle a null input by selecting a default value or taking an alternative path of logic, write your own code to handle it gracefully instead of throwing an exception
  • If you cannot handle a null field gracefully, throw a specific exception that explains why a value is required in the exception message. emailAddress is required for customer validation, and cannot be null is a more meaningful error message than NullPointerException: field emailAddress is null.
  • If you really just want to immediately short circuit your method if a null value is present and don't have a more meaningful message to convey or an alternative path to take, use @NonNull to autogenerate the null checks for you.

Top comments (0)