Rule Definition
NULL pointer dereference issues can occur through a number of flaws, including race conditions, and simple programming omissions
Remediation
Optional.isPresent should be used before invoking Optional.get. But PLEASE Note that one major benefit we get from an Optional is that it provides a set of higher order functions, which can be chained without worrying whether the value is present or not. orElse(...), orElseGet(...), or orElseThrow(...) or .ifPresentOrElse(...) as following sample
Optional.ifPresentOrElse is similar to Optional.ifPresent from Java 1.8, but it performs a second action if the value is not present. For example, if the task was to print the ZIP code and it is provided or print a message otherwise, we could do the following:
public String printZipCode(String userId) {
userRepository.findById(userId)
.flatMap(User::getAddress)
.flatMap(Address::getZipCode)
.ifPresentOrElse(
System.out::println,
() -> System.out.println("The zip Code is not provided!")
);
}
--------------------------
Java 10 introduced a better alternative — Optional.orElseThrow — whose behavior is the same, but the method name is screaming that an exception will be thrown if the value is not present.
The code above is only intending to show an ugly usage of Optionals. A more elegant approach would be to make a chain of higher-order functions provided by the Optional API:
public String findZipCode(String userId) {
return userRepository.findById(userId)
.flatMap(User::getAddress)
.flatMap(Address::getZipCode)
.orElse("");
}
Violation Code Sample
Optional<Department> deptOpt= studList.stream().min(comparator.comparing(Department::getDepartmentNo));
Department department = null;
department = deptOpt.get(); // Violation
}
Fixed Code Sample
Optional<Department> deptOpt= studList.stream().min(comparator.comparing(Department::getDepartmentNo));
Department department = null;
if(deptOpt.isPresent()) // Violation FIXED
department = deptOpt.get();
}
Reference
https://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html
https://dzone.com/articles/features-to-avoid-null-reference-exceptions-java-a
https://cwe.mitre.org/data/definitions/476.html
Related Technologies
Technical Criterion
Programming Practices - Error and Exception Handling
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.