Propose new sonar rule for usage of Optional.orElse/orElseGet

58 views
Skip to first unread message

erik.l...@gmail.com

unread,
Jun 26, 2017, 6:26:15 AM6/26/17
to SonarQube
Hello,

Recently a colleague of mine encountered some strange behaviour when unittesting some code. Using a lambda stream with findFirst().orElse(method-call), shows that het method-call is ALWAYS executed, even if findFirst() returns a value.

Optional<Foo> opt = ...
Foo x = opt.orElse( new Foo() );
Foo y = opt.orElseGet( Foo::new );

If opt doesn't contain a value, the two are equivalent.
But if opt does contain a value, the orElse will create new Foo(), where the orElseGet won't.

orElse takes a value, thus the new Foo will be created when calling the orElse method. orElse will determine that a value is present in opt, ignoring the newly created Foo.
orElseGet takes a Supplier wich can create a new Foo, but will not when optcontains a value.

In my opinion the Optional.orElse should never be used with a method call, and I think it should be added as a sonarrule. When using orElse with a method call, the sonar rule could advice to use Optional.orElseGet.

Does anyone agree, or object? Any other perspective on this matter?

Kind Regards,
Erik Loosman

G. Ann Campbell

unread,
Jun 27, 2017, 11:34:18 AM6/27/17
to SonarQube, erik.l...@gmail.com
Hi Erik,

Thanks for sharing. I've created a new rule specification:

  1. RSPEC-4064
  2. "orElseGet" should be preferred

Ann
Reply all
Reply to author
Forward
0 new messages