7

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.

Michal Kordas
  • 10,475
  • 7
  • 58
  • 103
  • If you cannot find an appropriate rule. Consider writing your own regex rule [RegexpSinglelineJavaCheck](http://checkstyle.sourceforge.net/apidocs/com/puppycrawl/tools/checkstyle/checks/regexp/RegexpSinglelineJavaCheck.html) – Yurii Bondarenko Dec 19 '18 at 16:29
  • @Hulk indeed! I was using SonarLint in a wrong way. Please post your comment as an answer and I'll accept it. – Michal Kordas Dec 19 '18 at 18:17
  • @MichalKordas mind telling us what you did wrong when using SonarLint (perhaps you can help out someone else) – Roy Shahaf Dec 19 '18 at 18:36
  • 2
    I made an issue to add support to checkstyle with https://github.com/checkstyle/checkstyle/issues/6301 – rveach Dec 19 '18 at 22:15
  • 3
    @RoyShahaf Silly mistake: I was running it on a file with .groovy extension and SonarLint said that this code is fine. After changing extension to .java it detected the issue – Michal Kordas Dec 19 '18 at 22:25
  • 1
    Error Prone [does check for this](http://errorprone.info/bugpattern/MixedArrayDimensions), but the severity is SUGGESTION. Perhaps you could increase the severity? – Andy Turner May 07 '19 at 10:13
  • I would change the severity to PUKE. – MC Emperor May 07 '19 at 10:45

2 Answers2

4

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).

Hulk
  • 6,399
  • 1
  • 30
  • 52
1

Checkstyle's ArrayTypeStyle will support printing violations on method definitions where brackets are placed on the method name instead of the return type starting with version 8.18.

See https://github.com/checkstyle/checkstyle/issues/6301

rveach
  • 2,081
  • 15
  • 25