Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sonar : lambda - Remove useless curly braces around statement

These code examples:

import java.util.Observer;

public class Main {
    public static void main(String[] args) {
        Observer observer = (o, arg) -> {
            if (arg != null) {
                System.out.println(arg);
            }
        };
    }
}

import java.util.Observer;

public class Main {
    public static void main(String[] args) {
        Observer observer = (o, arg) -> {
            try {
                String test = (String) arg;
                ...
            }
            catch (ClassCastException e) {
            }
        };
    }
}

are noncompliant with this sonarqube rule:

Lamdbas containing only one statement should not nest this statement in a block : Remove useless curly braces around statement

how can i fix it ?

like image 634
gontard Avatar asked Jun 23 '14 11:06

gontard


People also ask

Does Lambda require curly braces?

The body of the lambda expressions can contain any number of statements. If the body of the lambda expression has a single statement, the curly brackets are not mandatory but when there is more than one statement in the body then these must be enclosed in curly brackets.

What is the purpose of {} squiggly braces in Java?

Different programming languages have various ways to delineate the start and end points of a programming structure, such as a loop, method or conditional statement. For example, Java and C++ are often referred to as curly brace languages because curly braces are used to define the start and end of a code block.


1 Answers

The classification of these curly braces as “useless” is wrong.

You can omit curly braces around a single expression statement, that is, for example, a method invocation, a new expression, or x++, x+=y, etc.

Or you can transform a sole … -> { return x; } statement into an expression … -> x.

But you can’t omit curly braces around every single statement.

You can’t fix that. The only thing you can do is file a bug report.

By the way, even then, removing them is not necessarily a readability improvement. It depends…

like image 146
Holger Avatar answered Sep 22 '22 04:09

Holger