2

I've just started using SonarQube for improving my code quality and when I analyzed a JavaFx project that uses ControlsFX for validation I got this "code smell" error.

Replace this lambda with a method reference:

support.getValidationResult().getErrors().forEach(error -> 
    support.getValidationDecorator().applyValidationDecoration(error));

I'm unsure on how to refactor this since the ValidationSupport class does not have any static methods and my IDE is giving me this warning for most of what I'm tying to do:

The type ValidationSupport does not define getValidationDecorator(ValidationMessage) that is applicable here

For the time being I've just marked it down as a false positive in Sonar but that's not a good solution in the long run since it just hides it.

Brenin
  • 195
  • 1
  • 2
  • 16

2 Answers2

2

Method references don't have to be references to static methods, they can also be references to a method on a particular object. In this case you can use:

support.getValidationResult().getErrors().forEach( 
    support.getValidationDecorator()::applyValidationDecoration);

which is doing exactly the same thing as your original - calling applyValidationDecoration with the error parameter on the result of calling support.getValidationDecorator().

greg-449
  • 109,219
  • 232
  • 102
  • 145
  • Works perfectly, thank you. My error was in trying to use the "::" to early, i e support::getValidation. – Brenin Feb 20 '17 at 11:52
2

Method references introduced to shorthand lambda expressions. But only specific type of lambdas can be shorthanded using those method references.

If your lambda does not do anything except calling another method; you can use this short form(method references) to write that lambda.

In your case; your lambda expression is:

Consumer<Error> con = error -> 
                      support.getValidationDecorator().applyValidationDecoration(error);

You can see that error has just redirected to applyValidationDecoration method. Therefore; this is the perfectly valid scenario to use method references.

support.getValidationResult().getErrors()
.forEach(support.getValidationDecorator()::applyValidationDecoration);

Have a look at the Oracle tutorial if you have any doubts.

Anatoly Shamov
  • 2,608
  • 1
  • 17
  • 27
Jude Niroshan
  • 4,280
  • 8
  • 40
  • 62