PROBLEM
Ever written code like this?
Employee employee = employeeService.getByName(employeeName);
if (employee == null) {
employee = new Employee();
}
While it works, it has several minor problems:-
- The above code has cyclomatic complexity of 2 due to the
if
logic. - We cannot define
final
onemployee
object. - Too many lines of code, and seriously, it looks very 2003.
SOLUTION
Guava provides a much cleaner solution to address these problems:-
final Employee employee = Objects.firstNonNull(employeeService.getByName(employeeName),
new Employee());
Leave a Reply