Back
Close

Avoiding Null Anti Patterns

[CG]jupoulton
5,902 views

Require non null parameters

One of the first things you can do to avoid null-related problems is to require that given values be not null by using the static method Objects.requireNonNull(variable, errorMessage).

If you elect not to use this method, your code will have to check for null every time the given value should be used which is error-prone and confusing. If a null manages to slip into your code, your program may start behaving in mysterious and unexpected ways.

By requiring non-null values from the very start of a method's execution, you will easily isolate the problem when dealing with a NullPointerException. This makes debugging far easier than if the program crashes several hundred lines later.

You may also attach a custom error message to the NPE by using Objects.requireNonNull.

Use Objects.requireNonNull
// {...}
/**
* This method requires a non null String
* A NullPointerException will be thrown if this is not the case. However, take a look at the line where the NPE would occur.
*/
public static boolean containsVowels(String word) {
// TODO make sure word is not null with requireNonNull().
// If word is null, add the custom message "please don't give me a null"
String[] vowels = { "a", "e", "i", "o", "u" };
for (int i = 0; i < 5; ++i) {
// If the following line generates a crash during runtime, it is not clear wether `word` or `vowel` is null.
// Is there a bug in your code or is your method being used wrong?
if (word.toLowerCase().contains(vowels[i])) {
return true;
}
// To avoid this sort of problem, add the instruction
// Objects.requireNonNull(word, "please don't give me a null");
// as the first line of the method
}
return false;
}
//{...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

If you are a Guava user, you will have recognised this behaviour in Guava's Preconditions.checkNotNull.

Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants