Search code examples
javagroovystaticimportcodenarc

Static import statements which should never be after nonstatic imports


Codenarc is a framework that analyzes Groovy code for defects, bad practices, inconsistencies, style issues and more.

Is there a reason for this rule: MisorderedStaticImports Rule:

Checks for static import statements which should never be after nonstatic imports.

Examples of violations:

import my.something.*
import static foo.bar.*

public class MyClass{}

I don't understand the motivation or implications for this rule.


Solution

  • As Marko Topolnik says, the order of the imports is not relevant to the meaning of a program.

    I tried looking at the JLS for an explicit statement to that effect, but I couldn't find one. And the Java Tutorial doesn't mention import order either. However, the semantics of import are such that it makes no difference. If the imports result in any potential ambiguity due to import order, the JLS says it is a compilation error.

    Therefore, this is just a stylistic convention. (Indeed, if you look at the rule, it even gives you the option of putting the static imports first!)


    UPDATE

    @Eugene Stepanenkov points out this Q&A

    That was caused by an obscure bug in versions of the Oracle Java compiler prior to Java 8. It was (eventually) acknowledged as a bug and fixed.

    I guess, that means that the bug could have been part of the motivation for the Codenarc warning. However if you were using a Java compiler affected by the bug, then any code with the imports in the "wrong" order would not compile at all ... rendering the Codenarc warning moot.