java:S3824 exception for long code?

Rule java:S3824 (SonarSource Code Analyzers Rules Explorer) is one of those “use this new Java feature because it beats the old way” smell rules. Basically, if your code checks if a key is in a Map, and creates a new entry if it’s not, Java 8+ has a nice all-in-one method that can make things more compact (its second arg is a lambda which is invoked, when necessary, to create the new entry).

It could be useful for us, but unfortunately, the nice compact example in the rule description (where the new value is created with “value = V.createFor(key);”) isn’t like our code in many cases. Instead, we might have 3 or 4 lines of code used for constructing and populating the new value that gets added to the Map. So, if we were to replace our code with computeIfAbsent() as recommended, the second arg would end up being a very clunky lambda expression that would be just as hard to understand as the original code (if not harder).

Perhaps there could be a parameter N (default 1) whereby if the code for creating the value has more than N lines (or statements), then the rule is not flagged.

(This is on SQ 8.6 but the current documentation of this rule doesn’t mention any exceptions other than null, which leads me to believe this feature hasn’t been added.)

Hey @MisterPi,
How about putting the code of the lambda in a static method and using a method reference in computeIfAbsent?

I neglected to mention that in our code, the part for creating the new element is different in each place. Otherwise, the devs would already have made a common method (well, at least one would hope…). So we would need more or less one static method for each place where this occurs.

So for someone looking at the code, there’s the benefit of not having the boilerplate for the computeIfAbsent functionality, but also the hassle of having to go somewhere else to read the static method (even with IDE support), rather than having it right there.