Avoiding Wildcard imports in Java/Kotlin with IntelliJ

What is a wildcard import or a star import?

When you want to import multiple classes from the same package like this:

import com.example.exception.CustomerNotFoundExcetpion
import com.example.exception.ProductNotFoundExcetpion
import com.example.exception.ProductOutOfStockException
import com.example.exception.AdressNotFoundException

Java has an option to combine them into a single line using wildcard imports:

import com.example.exception.*

Is it bad?

Performance-wise, no. Using a wildcard import doesn’t actually import all the classes in the package. When your code is compiled, only the classes used from this package are added to the bytecode. So there is zero performance difference between wildcard import and explicit imports.

Then why should we avoid it?

  • Explicit imports clearly states what external classes the current class is directly using, provided that you don’t leave redundant imports in your code.
  • If there are two classes with the same name from different packages, it can introduce collision when using wildcard imports.
  • When multiple people are working in a project, wildcard imports can create confusion as to which classes are actually imported

Many large Java projects that I have worked with, have a checkstyle rule to disallow wildcard imports for the above reason.

Now that we have understood why explicit imports are better than implicit imports, let’s see how we can make IntelliJ always use explicit imports.

By default, IntelliJ will convert implicit imports into wildcard imports when it sees 5 import statements from the same package.

This setting can however by set to a large value like 99 to prevent the automatic wild card imports.

Goto Preferences -> Editor -> Code Style -> Java (or Kotlin) -> Update the following two values to 99:

  • Class count to use import with ‘*’
  • Names count to use static import

Also remove all the entries from the “Packages to Use Import with ‘*’” table.

Click ‘Apply’ and close the dialog. Now do ‘Optimize Imports’ again to remove the wildcard imports automatically now and in the future.

More ‘Import’ options can be customized with IntelliJ. Follow this link for more customizations: https://www.jetbrains.com/help/idea/creating-and-optimizing-imports.html

The default Sun & Google’s Checkstyle rules also recommend avoiding star import by throwing this exception:

(imports) AvoidStarImport: Using the '.*' form of import should be avoided

To add this rule to your checkstyle configuration, add this line:

<module name="AvoidStarImport"/>

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *