hanki.dev

use notNull to check for null params in Java

I often like to check if my function params are null at the start of the function, using a basic if check:

public void myFunction(String myParam) {
    if (myParam == null || myParam.isEmpty()) {
        throw new NullPointerException("Parameter myParam cannot be null");
    }
    // Code here
}

Which is fine, and it works. But today I found out that Apache Commons Lang's Validate class class has notEmpty function which does this for you!

public void myFunction(String myParam) {
    notEmpty(myParam, "Parameter myParam cannot be null");
    // Code here
}

If you ask me, that's a lot more clean and readable 🤑

#java