1

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?

Apollo
  • 1,296
  • 2
  • 11
  • 24
  • 1
    What if, `getFirstName` returns something different the second time you call it? – Sweeper Dec 16 '21 at 10:11
  • 1
    Using `ifPresent` with `get` defeats the purpose of using an `Optional`. A null check is clearer to read in this case. – Abhijit Sarkar Dec 16 '21 at 10:13
  • Good points. In this case it is not possible to return something else, but I get the point. – Apollo Dec 16 '21 at 10:18
  • `Optional` should not be used as a property type. See https://stackoverflow.com/questions/23454952/uses-for-optional which has an authoritative answer on this subject. – VGR Dec 16 '21 at 15:52
  • If I'm just passing it around, there is no benefit in unpacking it when I have to do the null checks or packing it in Optional later again. But this has nothing to do with my question above. Thanks. – Apollo Dec 17 '21 at 08:27

1 Answers1

2

How about using ifPresent :

customer.getFirstName().ifPresent(name1->
  customer.getLastName().ifPresent(name2->
      final String firstName = name1;
      final String lastName = name2;
  );
);
DEV
  • 1,607
  • 6
  • 19