Avoiding Null Anti Patterns

[CG]jupoulton
761 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

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
1
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// {...}
/**
* 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.

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content