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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public Integer getPackageQuantity() { | |
return ObjectUtils.firstNonNull(quantity, innerPackQuantity, DEFAULT_QUANTITY); | |
} |
Another option is to roll your own utility method using lambdas.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Product class | |
public Integer getPackageQuantity2() { | |
return firstNonNull(quantity, innerPackQuantity, DEFAULT_QUANTITY); | |
} | |
// Utils class | |
public static <T> T firstNonNull(T... args) { | |
return Stream.of(args) | |
.filter(Objects::nonNull) | |
.findFirst() | |
.get(); | |
} |
No comments:
Post a Comment