Search code examples
javalomboknotnull

Checking input==null with @NonNull vs letting NPE be thrown


public void test(@NonNull String input){
    #1 log(input.length());
}
  1. Using lombok @NotNull annotation removes boilerplate code. But if a null was passed as the input, it also ultimately throws an NPE (by default). So what's the difference in using @NonNull vs letting an NPE being thrown at line #1?

public void test(String input){
if(input ==null){
    throw NPE;
}
log(input.length());
}
  1. On a similar note, if the input is null and something could be done about it (e.x. set a default value or bypass the block if null), then it makes sense to do an explicit check for null. Otherwise is there any point in doing this check. Is it better to not do a null check and let NPE be thrown? If the answer to this question is, don't do null check, then why Lombok @NonNull exists?

Solution

  • "Fail fast" will help you in avoiding unwanted side effects. What if your method would dereference your null parameter after 20 lines, and within the 19 lines before, some state had already been changed (write to a log file, started transaction, some file or OutputStream creation)? In general, you don't want any of your method expressions to be executed if the API contract (parameter must not be null) has been violated.