Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Skip null object when returning with .equals()

Tags:

java

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?

like image 656
Kei Avatar asked Feb 27 '26 17:02

Kei


2 Answers

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 anything
  • true || anything == true, so there's no need to evaluate anything
like image 69
Andy Turner Avatar answered Mar 01 '26 06:03

Andy Turner


One 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("")
like image 23
Eran Avatar answered Mar 01 '26 07:03

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!