73 lines
2.3 KiB
Plaintext
73 lines
2.3 KiB
Plaintext
This rule raises an issue when a lambda expression uses block notation while expression notation could be used.
|
|
|
|
== Why is this an issue?
|
|
|
|
The right-hand side of a lambda expression can be written in two ways:
|
|
|
|
1. Expression notation: the right-hand side is as an expression, such as in `(a, b) -> a + b`
|
|
2. Block notation: the right-hand side is a conventional function body with a code block and an optional return statement,
|
|
such as in `(a, b) -> {return a + b;}`
|
|
|
|
By convention, expression notation is preferred over block notation.
|
|
Block notation must be used when the function implementation requires more than one statement.
|
|
However, when the code block consists of only one statement (which may or may not be a `return` statement),
|
|
it can be rewritten using expression notation.
|
|
|
|
This convention exists because expression notation has a cleaner, more concise,
|
|
functional programming style and is regarded as more readable.
|
|
|
|
== How to fix it
|
|
|
|
|
|
* If the code block consists only of a `return` statement, replace the code block with the argument expression from the `return` statement.
|
|
* If the code block consists of a single statement that is not a `return` statement, replace the code block with that statement.
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,java,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
(a, b) -> { return a + b; } // Noncompliant, replace code block with expression
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,java,diff-id=1,diff-type=compliant]
|
|
----
|
|
(a, b) -> a + b // Compliant
|
|
----
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,java,diff-id=2,diff-type=noncompliant]
|
|
----
|
|
x -> {System.out.println(x+1);} // Noncompliant, replace code block with statement
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,java,diff-id=2,diff-type=compliant]
|
|
----
|
|
x -> System.out.println(x+1) // Compliant
|
|
----
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
Remove the useless curly braces around this statement[ and then remove useless return keyword]. [(sonar.java.source not set. Assuming 8 or greater.)]
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
=== on 21 Feb 2014, 16:03:58 Freddy Mallet wrote:
|
|
Is implemented by \http://jira.codehaus.org/browse/SONARJAVA-453
|
|
|
|
endif::env-github,rspecator-view[]
|