Guava: Reducing Cyclomatic Complexity with Objects.firstNonNull(…)


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 on employee object.
  • Too many lines of code, and seriously, it looks very 2003.


Guava provides a much cleaner solution to address these problems:-

final Employee employee = Objects.firstNonNull(employeeService.getByName(employeeName),
                                               new Employee());

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s