Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static Utility Methods - explicit NULL check vs @NonNull vs explicit throws

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?

like image 305
AgentX Avatar asked Feb 17 '26 02:02

AgentX


2 Answers

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.

like image 131
maaartinus Avatar answered Feb 19 '26 16:02

maaartinus


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.

like image 30
Les Avatar answered Feb 19 '26 15:02

Les



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!