The question is basically for Static Utility Classes, which exist in a package to provide certain functionality to other classes. I'll take a common example stripParenthesis()
Method 1. Explicit Null Check
public static String stripParenthesis(String str) {
if(str == null) {
return str;
}
return str.replaceAll("[()]",""); // remove paarenthesis
}
Method 2. Using Lombok's @NonNull
/* @NonNull will throw NPE */
public static String stripParenthesis(@NonNull String str) {
return str.replaceAll("[()]",""); // remove paarenthesis
}
Method 3. Explicit NPE
public static String stripParenthesis(String str) throws NullPointerException {
if(str == null) {
throw NPE();
}
return str.replaceAll("[()]",""); // remove paarenthesis
}
All the 3 methods are correct. I do not prefer 2nd approach since it throws a NPE as unchecked exception. The caller can unexpectedly fail.
Is there a general convention to follow here?
I would not use method 1 as ignoring null usually means it blows somewhere else instead, where the problem may get harder to track. Let no method accept nulls unnecessarily and you'll see no NPEs as there'll no nulls anywhere. Use a method like Strings#nullToEmpty to get rid of null ASAP.
I do not prefer 2nd approach since it throws a NPE as unchecked exception. The caller can unexpectedly fail.
An NPE is always unchecked. You can use 2' and declare it, but this doesn't make it really better, as a @NonNull argument declaration is actually stating what happens in the clearest possible way. It's @Documented, which means that it appears in the javadoc.
Method 1. Explicit Null Check.
if(str == null) { return str; }
What do you try to achieve returning null? This masking error by delegating needed null checks and behaviours back to the caller. Maybe you presume returning of something like Optional.empty()?
Method 2. Using Lombok's @NonNull - isn't an equal option. This isn't a part of the java standard with related third party frameworks problems. The javax similar annotations are, but they're not forcing null checks, they designed mostly for static analysers. Despite this, Lombok is reliable framework.
Method 3. Explicit NPE - core solid method, it works always, if you hesitate only between that three - use it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With