Question

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.

Was it helpful?

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.

OTHER TIPS

A style issue. There will be just one, two static imports, but which have a great impact on the understandability like introducing function names. Hence placing them at the top (for reading) might be considered good style. The IDE collapsing "[+]" support might have been taken in consideration too.

I think they wanted the static imports to be separated from the other ones.

Choosing the order of imports (static and non-static) may produce a problem in a such edge case as in example.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top