Taco Jan Osinga
Taco Jan Osinga

Reputation: 3820

Why is it a code smell to add parenthesis on a single argument lambda?

On several websites/analyzers, like Baeldung and SonarQube, I see that wrapping a single argument of a lambda is considered a code smell. Now, I do understand without the parenthesis you'd save two characters, but i.m.h.o it also breaks consistency, looking at the other uses of arguments. To me, consistent use would even increase readability.

a = () -> doSomething();
a = x -> doSomething(x);                // <--- Ok?
a = (x) -> doSomething(x);              // <--- Code smell?
a = (x, y) -> doSomething(x, y);
a = (x, y, z) -> doSomething(x, y, z);

Are there other reasons, besides shorter code and personal preference, that parenthesis are considered bad when having one argument?

Upvotes: 0

Views: 178

Answers (1)

Konrad Rudolph
Konrad Rudolph

Reputation: 545588

“Why” questions always invite speculation but I think in this case the reason is fairly obvious: the two extra characters introduce unnecessary syntactic noise.

I’m not convinced by your consistency counter-argument, since you presumably also don’t use parentheses around all other expressions where they might appear, right? By the same argument, you’d be forced to write

int a = ((1) + (2));

instead of

int a = 1 + 2;

Upvotes: 2

Related Questions