I have an application where I need to handle a lot of numbers (Integers or Longs) comming from external sources.
The numbers can be null. In case they are null I always need to convert them to 0.
The problem seems trivial, but I don't want to write hundreds of times:
if (someNumber == null) {
someNumber = 0;
}
I don't like it for two reasons:
- I don't like to write three lines of code for such simple task, especially because I need to do it many times
- I don't like to to "mutate" someNumber (assign new value to someNumber variable)
I tried some other ways which can be seen here:
public static void main(String[] args) {
Integer zeroOrNull = new Random().nextBoolean() ? 0 : null;
// version1: this is nasty (I already mentioned why)
if (zeroOrNull == null) {
zeroOrNull = 0;
}
// version2: this seems to much for so simple task...
zeroOrNull = Optional.ofNullable(zeroOrNull).orElseGet(() -> 0);
// version3: creating an util might be considerable. Is there already such predefined util ?
zeroOrNull = MyUtil.getValueOrZero(zeroOrNull); // returns value or )
System.out.println(zeroOrNull); // I want 0 here in case of null
}
What is the preffered and nice way to do such "test for null/conversion to 0" ? Any chance to do this conversion implicitly?
null
value, then just do not allow it. Change the calling code at first to not send innull
. If you still must distinguish between present and absent, then usejava.util.Optional
, but as a method parameter (not inside the method for its implementation).if (someNumber == null) { someNumber = 0; }
that is exactly what you should do.Integer i = MoreObjects.firstNonNull( possibleNull, 0);