1. Общ преглед
Като цяло, нулевите променливи, препратките и колекциите са трудни за обработка в Java кода. Те не само са трудни за идентифициране, но и са сложни за справяне.
Всъщност всяка грешка при справяне с null не може да бъде идентифицирана по време на компилиране и води до NullPointerException по време на изпълнение.
В този урок ще разгледаме необходимостта от проверка за нула в Java и различни алтернативи, които ни помагат да избегнем нулеви проверки в нашия код.
2. Какво е NullPointerException?
Според Javadoc за NullPointerException се изхвърля, когато приложението се опитва да използва null в случай, когато се изисква обект, като например:
- Извикване на метод на екземпляр на нулев обект
- Достъп или модификация на поле на нулев обект
- Приемайки дължината на null , сякаш е масив
- Достъп или промяна на слотовете от null , сякаш е масив
- Хвърляне на нула , като че ли по- Може да се изхвърли стойност
Нека да видим бързо няколко примера за Java кода, които причиняват това изключение:
public void doSomething() { String result = doSomethingElse(); if (result.equalsIgnoreCase("Success")) // success } } private String doSomethingElse() { return null; }
Тук се опитахме да извикаме извикване на метод за нулева препратка. Това би довело до NullPointerException.
Друг често срещан пример е, ако се опитаме да получим достъп до нулев масив:
public static void main(String[] args) { findMax(null); } private static void findMax(int[] arr) { int max = arr[0]; //check other elements in loop }
Това причинява NullPointerException на ред 6.
По този начин достъпът до всяко поле, метод или индекс на нулев обект причинява NullPointerException , както може да се види от примерите по-горе.
Чест начин за избягване на NullPointerException е да се провери за null :
public void doSomething() { String result = doSomethingElse(); if (result != null && result.equalsIgnoreCase("Success")) { // success } else // failure } private String doSomethingElse() { return null; }
В реалния свят програмистите трудно определят кои обекти могат да бъдат нулеви. Агресивно безопасна стратегия може да бъде проверка на null за всеки обект. Това обаче причинява много излишни нулеви проверки и прави нашия код по-малко четим.
В следващите няколко раздела ще разгледаме някои от алтернативите в Java, които избягват такава излишък.
3. Обработка на null чрез API договора
Както беше обсъдено в последния раздел, достъпът до методи или променливи на нулеви обекти причинява NullPointerException. Също така обсъдихме, че поставянето на нулева проверка на обект преди достъп до него елиминира възможността за NullPointerException.
Въпреки това, често има API, които могат да обработват нулеви стойности. Например:
public void print(Object param) { System.out.println("Printing " + param); } public Object process() throws Exception { Object result = doSomething(); if (result == null) { throw new Exception("Processing fail. Got a null response"); } else { return result; } }
Най печат () метод разговор просто ще отпечатате "нула" , но няма да се хвърли изключение. По същия начин, process () никога няма да върне null в своя отговор. По-скоро изхвърля изключение.
Така че за клиентски код, който има достъп до горните API, няма нужда от нулева проверка.
Тези API обаче трябва да го посочват изрично в договора си. Често срещано място за API за публикуване на такъв договор е JavaDoc .
Това обаче не дава ясна индикация за договора за API и по този начин разчита на разработчиците на клиентски код да гарантират неговото съответствие.
В следващия раздел ще видим как няколко IDE и други инструменти за разработка помагат на разработчиците с това.
4. Автоматизиране на API договори
4.1. Използване на анализ на статичен код
Инструментите за анализ на статичен код помагат да се подобри качеството на кода до голяма степен. И няколко такива инструмента също позволяват на разработчиците да поддържат нулевия договор. Един пример е FindBugs.
FindBugs помага за управление на нулевия договор чрез анотациите @Nullable и @NonNull . Можем да използваме тези пояснения върху всеки метод, поле, локална променлива или параметър. Това прави изрично за клиентския код дали анотираният тип може да бъде нулев или не. Да видим пример:
public void accept(@Nonnull Object param) { System.out.println(param.toString()); }
Тук @NonNull ясно показва, че аргументът не може да бъде нулев. Ако клиентският код извика този метод, без да проверява аргумента за нула, FindBugs ще генерира предупреждение по време на компилация.
4.2. Използване на поддръжка на IDE
Разработчиците обикновено разчитат на IDE за писане на Java код. А функции като интелигентно попълване на код и полезни предупреждения, като например когато дадена променлива може да не е била назначена, със сигурност помагат до голяма степен.
Някои IDE също така позволяват на разработчиците да управляват API договори и по този начин елиминират необходимостта от инструмент за статичен анализ на код. IntelliJ IDEA предоставя анотации @NonNull и @Nullable . За да добавим поддръжката за тези пояснения в IntelliJ, трябва да добавим следната зависимост на Maven:
org.jetbrains annotations 16.0.2
Сега IntelliJ ще генерира предупреждение, ако липсва нулевата проверка, както в последния ни пример.
IntelliJ също така предоставя анотация на договор за обработка на сложни API договори.
5. Твърдения
Досега говорихме само за премахване на необходимостта от нулеви проверки от клиентския код. Но това рядко е приложимо в реални приложения.
Нека сега предположим, че работим с API, който не може да приеме нулеви параметри или може да върне нулев отговор, който трябва да се обработва от клиента . Това представлява необходимостта да проверим параметрите или отговора за нулева стойност.
Here, we can use Java Assertions instead of the traditional null check conditional statement:
public void accept(Object param){ assert param != null; doSomething(param); }
In line 2, we check for a null parameter. If the assertions are enabled, this would result in an AssertionError.
Although it is a good way of asserting pre-conditions like non-null parameters, this approach has two major problems:
- Assertions are usually disabled in a JVM
- A false assertion results in an unchecked error that is irrecoverable
Hence, it is not recommended for programmers to use Assertions for checking conditions. In the following sections, we'll discuss other ways of handling null validations.
6. Avoiding Null Checks Through Coding Practices
6.1. Preconditions
It's usually a good practice to write code that fails early. Therefore, if an API accepts multiple parameters that aren't allowed to be null, it's better to check for every non-null parameter as a precondition of the API.
For example, let's look at two methods – one that fails early, and one that doesn't:
public void goodAccept(String one, String two, String three) { if (one == null || two == null || three == null) { throw new IllegalArgumentException(); } process(one); process(two); process(three); } public void badAccept(String one, String two, String three) { if (one == null) { throw new IllegalArgumentException(); } else { process(one); } if (two == null) { throw new IllegalArgumentException(); } else { process(two); } if (three == null) { throw new IllegalArgumentException(); } else { process(three); } }
Clearly, we should prefer goodAccept() over badAccept().
As an alternative, we can also use Guava's Preconditions for validating API parameters.
6.2. Using Primitives Instead of Wrapper Classes
Since null is not an acceptable value for primitives like int, we should prefer them over their wrapper counterparts like Integer wherever possible.
Consider two implementations of a method that sums two integers:
public static int primitiveSum(int a, int b) { return a + b; } public static Integer wrapperSum(Integer a, Integer b) { return a + b; }
Now, let's call these APIs in our client code:
int sum = primitiveSum(null, 2);
This would result in a compile-time error since null is not a valid value for an int.
And when using the API with wrapper classes, we get a NullPointerException:
assertThrows(NullPointerException.class, () -> wrapperSum(null, 2));
There are also other factors for using primitives over wrappers, as we covered in another tutorial, Java Primitives versus Objects.
6.3. Empty Collections
Occasionally, we need to return a collection as a response from a method. For such methods, we should always try to return an empty collection instead of null:
public List names() { if (userExists()) { return Stream.of(readName()).collect(Collectors.toList()); } else { return Collections.emptyList(); } }
Hence, we've avoided the need for our client to perform a null check when calling this method.
7. Using Objects
Java 7 introduced the new Objects API. This API has several static utility methods that take away a lot of redundant code. Let's look at one such method, requireNonNull():
public void accept(Object param) { Objects.requireNonNull(param); // doSomething() }
Now, let's test the accept() method:
assertThrows(NullPointerException.class, () -> accept(null));
So, if null is passed as an argument, accept() throws a NullPointerException.
This class also has isNull() and nonNull() methods that can be used as predicates to check an object for null.
8. Using Optional
8.1. Using orElseThrow
Java 8 introduced a new Optional API in the language. This offers a better contract for handling optional values compared to null. Let's see how Optional takes away the need for null checks:
public Optional process(boolean processed) { String response = doSomething(processed); if (response == null) { return Optional.empty(); } return Optional.of(response); } private String doSomething(boolean processed) { if (processed) { return "passed"; } else { return null; } }
By returning an Optional, as shown above, the process method makes it clear to the caller that the response can be empty and must be handled at compile time.
This notably takes away the need for any null checks in the client code. An empty response can be handled differently using the declarative style of the Optional API:
assertThrows(Exception.class, () -> process(false).orElseThrow(() -> new Exception()));
Furthermore, it also provides a better contract to API developers to signify to the clients that an API can return an empty response.
Although we eliminated the need for a null check on the caller of this API, we used it to return an empty response. To avoid this, Optional provides an ofNullable method that returns an Optional with the specified value, or empty, if the value is null:
public Optional process(boolean processed) { String response = doSomething(processed); return Optional.ofNullable(response); }
8.2. Using Optional with Collections
While dealing with empty collections, Optional comes in handy:
public String findFirst() { return getList().stream() .findFirst() .orElse(DEFAULT_VALUE); }
This function is supposed to return the first item of a list. The Stream API's findFirst function will return an empty Optional when there is no data. Here, we have used orElse to provide a default value instead.
This allows us to handle either empty lists, or lists, which after we have used the Stream library's filter method, have no items to supply.
Alternatively, we can also allow the client to decide how to handle empty by returning Optional from this method:
public Optional findOptionalFirst() { return getList().stream() .findFirst(); }
Therefore, if the result of getList is empty, this method will return an empty Optional to the client.
Using Optional with collections allows us to design APIs that are sure to return non-null values, thus avoiding explicit null checks on the client.
It's important to note here that this implementation relies on getList not returning null. However, as we discussed in the last section, it's often better to return an empty list rather than a null.
8.3. Combining Optionals
When we start making our functions return Optional we need a way to combine their results into a single value. Let's take our getList example from earlier. What if it were to return an Optional list, or were to be wrapped with a method that wrapped a null with Optional using ofNullable?
Our findFirst method wants to return an Optional first element of an Optional list:
public Optional optionalListFirst() { return getOptionalList() .flatMap(list -> list.stream().findFirst()); }
By using the flatMap function on the Optional returned from getOptional we can unpack the result of an inner expression that returns Optional. Without flatMap, the result would be Optional
9. Libraries
9.1. Using Lombok
Lombok is a great library that reduces the amount of boilerplate code in our projects. It comes with a set of annotations that take the place of common parts of code we often write ourselves in Java applications, such as getters, setters, and toString(), to name a few.
Another of its annotations is @NonNull. So, if a project already uses Lombok to eliminate boilerplate code, @NonNull can replace the need for null checks.
Before we move on to see some examples, let's add a Maven dependency for Lombok:
org.projectlombok lombok 1.18.6
Now, we can use @NonNull wherever a null check is needed:
public void accept(@NonNull Object param){ System.out.println(param); }
So, we simply annotated the object for which the null check would've been required, and Lombok generates the compiled class:
public void accept(@NonNull Object param) { if (param == null) { throw new NullPointerException("param"); } else { System.out.println(param); } }
If param is null, this method throws a NullPointerException. The method must make this explicit in its contract, and the client code must handle the exception.
9.2. Using StringUtils
Generally, String validation includes a check for an empty value in addition to null value. Therefore, a common validation statement would be:
public void accept(String param){ if (null != param && !param.isEmpty()) System.out.println(param); }
This quickly becomes redundant if we have to deal with a lot of String types. This is where StringUtils comes handy. Before we see this in action, let's add a Maven dependency for commons-lang3:
org.apache.commons commons-lang3 3.8.1
Let's now refactor the above code with StringUtils:
public void accept(String param) { if (StringUtils.isNotEmpty(param)) System.out.println(param); }
So, we replaced our null or empty check with a static utility method isNotEmpty(). This API offers other powerful utility methods for handling common String functions.
10. Заключение
В тази статия разгледахме различните причини за NullPointerException и защо е трудно да се идентифицират. След това видяхме различни начини да избегнем излишността в кода около проверка за нула с параметри, типове връщане и други променливи.
Всички примери са достъпни на GitHub.