Monday, February 10, 2014

No Null Checks: Use firstNonNull method

When a reference is null I need to use a default value.
Use a common method to encapsulate selecting the first non null value.


In this example I am getting a package quantity for a product.  Since the data is not perfect, I use either the quantity, inner pack quantity or a default.  Since this method is in a domain object this is the only place this logic lives.

There are several firstNonNull methods you can use.  The one below is from apache commons and uses a variable argument parameter - so you can pick between many fields for the first non null value.  The one downside is that it returns null if all the values are null.  Be use to include a constant default in the group.


Another option is to roll your own utility method using lambdas.

The findFirst function returns an instance of Optional. The terminating get method call is on the Optional and throws a NoSuchElementException if all the arguments are null.

No comments:

Post a Comment