I am trying out some code optimization and my current unique title validation for an object looks like this:
public boolean validateTitle(RawProfileConstraint rawProfileConstraint) {
RawProfileConstraint result = profileConstraintMapper.validateTitle(rawProfileConstraint.getTitle());
return (!rawProfileConstraint.getTitle().equals(result.getTitle()));
}
This works, until it throws a tantrum where the database is unable to retrieve a record that contains the title that I'm trying to validate - a.k.a it is available. result will be null in that case.
How can I incorporate a handler for null in this case scenario without your usual if-else?
Simply check if result is null before dereferencing it:
return result != null
&& !rawProfileConstraint.getTitle().equals(result.getTitle());
or
return result == null
|| !rawProfileConstraint.getTitle().equals(result.getTitle());
depending upon what you want the result to be when result == null (false and true respectively).
&& and || short-circuit, so they won't evaluate the right-hand operand unless necessary:
false && anything == false, so there's no need to evaluate anythingtrue || anything == true, so there's no need to evaluate anythingOne option to avoid checking for null is to use an Optional (if you are using Java 8) :
Replace
result.getTitle()
with
Optional.ofNullable(result).map(RawProfileConstraint::getTitle).orElse("")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With