Yesterday I had to write an ugly piece of code, in order to perform many null-checks on the fields of an object, in order to avoid NPE from ternary operator construct.
The problematic piece of code:
ResourceThresholds rt = getThresholdsFromConfig();
Thresholds defaultPerContainer = getDefaultThresholds();
return new Thresholds((!rt.getCpu().equals("")) ? Long.parseLong(rt.getCpu()) : defaultPerContainer.getCpu(),
(!rt.getMemory().equals("")) ? Long.parseLong(rt.getMemory()) : defaultPerContainer.getMemory(),/*omitted for brevity*/);
I get a NPE on defaultPerContainer.getCpu()
, because the field cpu = null
.
And this is fine, Java works the way it works.
Why I didn't just defaulted the field Long cpu = 0L;
? Because I need the null
value as an indicator that we do not set any value.
The final functional variant of this particular piece of code ended up being:
Long cpuVal;
if (!rt.getCpu().equals("")) {
cpuVal = Long.parseLong(rt.getCpu());
} else {
cpuVal = defaultPerContainer.getCpu();
}
Long memory;
if (!rt.getMemory().equals("")) {
memory = Long.parseLong(rt.getMemory());
} else {
memory = defaultPerContainer.getMemory();
}
//... many similar if-elses that give me the desired value;
//which is really ugly, and I believe I am not the only one hitting this.
return new Thresholds(cpuVal, memory..);
This code works as I needed to work but it is ugly!
Q1: Can someone hint me on whether I can find a way of using Optional<T>
to resolve the NPE in the first variant with the ternary operator? Because this snippet works: !rt.getCpu().equals("")) ? Long.parseLong(rt.getCpu()) : null
i.e. if I explicitly put null
as a value, I get null
when the condition is met.
In general, is there any elegant Java 8+ way to deal with this?
Q2: how do you optimize the glorious if-else construct for null-checking?