Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 392
Michal Kordas Avatar asked Dec 19 '18 16:12

Michal Kordas


2 Answers

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

like image 79
Hulk Avatar answered Oct 20 '22 08:10

Hulk


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

like image 29
rveach Avatar answered Oct 20 '22 10:10

rveach