Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional ifPresent to call an object method

I have to call a procedure with the following signature:

private Optional<Address> getAddress()

And I use it to fill a client's record on my system. So, I made the following code to set the address of the record (if it exists).

Optional<Address> address = getAddress();
if (address.isPresent())
  record.setAddress(address.get());

However, I get the following notification:

Can be replaced by ifPresent

Reports conditions like if Optional.isPresent() which could be rewritten in functional style.

So I thought great, I'm going to use this cool ifPresent stuff to simplify my code. Then I came up with this line:

getAddress().ifPresent(x -> record.setAddress(x));

and thought nice, 3 lines into one. But then I got the following message from SonarLint

Replace this lambda with a method reference

and I thought why should I need to create a method just to set a single variable?

Anyway, since I'm kind of new to the use of Optional, I might be misunderstanding something here... So, how should I make this simple piece of code, according to the recommendations and best practices?

like image 945
Leonardo Alves Machado Avatar asked Jan 30 '23 21:01

Leonardo Alves Machado


1 Answers

You shouldn't create a new method just to set a single variable. SonarLint just recommends that it is better to use method reference instead of a lambda expression.

You could read about method references in Java 8 at Oracle's website: The Java Tutorials - Method References.

For your case - SonarLint just wants you to replace that line with this:

Record record = ...;
getAddress().ifPresent(record::setAddress);
like image 100
Vadym Pechenoha Avatar answered Feb 02 '23 11:02

Vadym Pechenoha