javacheckstylepmdsonarlinterrorprone

Prohibit brackets after method signature in Java code


In my project recently I've encountered code that compiles perfectly fine, however is very surprising to any reader and should not pass static analysis.

class BracketsAfterMethodSignature {
  Object emptyArray()[] {
    return new Object[]{};
  }
}

We use Checkstyle, PMD, ErrorProne and SonarLint but none of these tools complains on such construct. Is there any rule that could be enabled or tool that can be used to prevent such code?

Apparently Checkstyle's ArrayTypeStyle doesn't include such case.

EDIT

I was running static analysis on a file with .groovy extension and SonarLint said that this code is fine. After changing extension to .java it detected the issue. And indeed after update to 8.18 Checkstyle also spots it correctly.


Solution

  • Sonar has the rule squid:S1195 Array designators "[]" should be located after the type in method signatures

    This rule is enabled by default in the "Sonar way" quality profile for Java and classifies this as "Code Smell", default severity "minor".

    SonarLint should therefore highlight the code in the question - in my test, the eclipse-plugin "SonarLint for Eclipse" version 4.0.0.201810170711 correctly placed a marker at the opening bracket after the method declaration (in a project without a configured SonarQube server connection). Eclipse version was 2018-09 (4.9.0).