[Java] Lambda should not be too complex or too long

Description
A very large Lambda can make it difficult to follow the logic surrounding it. It also makes the code more difficult to maintain.

NonCompliant

  list.forEach(number -> IntStream.range(0, number).forEach(j -> System.out.println(number * j)));

Compliant

  for (Integer number : list) {
  	for (int j = 0; j < number; j++) {
  		System.out.println(number * j);
  	}
  }

Type
Codesmell

Hi,
In order for us to consider this suggestion we would need a bit more information.
Could you give a bit more details about the reasoning behind this suggestion ?
Why is the noncompliant example “bad” ?

Moreover, could you give a little more detail about what could be the threshold to raise an issue ? what would it take for the lambda to be “too long or too complex” ? What is the criteria ?

Thanks

Hi Nicolas,

The idea behind this rule is to avoid the overused of lambdas and streams. In this non-compliant example,
it’s easy overlook that this one is nested. In a even more complicated case, it will only get harder to understand.

About that threshold, it really depends on which intermediate stream operations are used. For example filter(...) and map(...) are quite easy to follow up, if the conditions or method are kept simple (lambdas should be short as possible, ideally a method reference). On the other hand using flatmap(...) will make it much more harder to follow.

Since we aren’t really expert in this field, maybe you could try to figure out when this certain threshold is reach. For example using filter() with a simple lambda condition gives 1 point. Using filter() with a more complex lambda gives 3 Points. After reaching a certain number of points you could raise an issue.

Regards

Hi,

I believe this feature is already partly covered by https://rules.sonarsource.com/java/RSPEC-1188 and its configuration.