Home > Software design >  "Optional value should only be accessed after calling isPresent()" although checked in if
"Optional value should only be accessed after calling isPresent()" although checked in if

Time:12-16

I receive a Customer object which contains lastName and firstName. In the conversion I check if both values are not empty and then pass them into the DTO:

if (customer.getFirstName().isPresent() && customer.getLastName().isPresent()) {
      final String firstName = customer.getFirstName().get();
      final String lastName = customer.getLastName().get();
      // do assignment
}

But I still get the Sonar message Optional value should only be accessed after calling isPresent().

Am I missing something here or is this a false positive?

CodePudding user response:

How about using ifPresent :

customer.getFirstName().ifPresent(name1->
  customer.getLastName().ifPresent(name2->
      final String firstName = name1;
      final String lastName = name2;
  );
);
  • Related