Use static imports rarely

Static imports allow the static items of one class to be referenced in another without qualification. Used indiscriminately, this will likely make code more difficult to understand, not easier to understand.

Example


import java.util.*;
import static java.util.Collections.*;

public final class StaticImporter {

  public static void main(String... aArgs){
    List<String> things = new ArrayList<>();
    things.add("blah");

    //This looks like a simple call of a method belonging to this class:
    List<String> syncThings = synchronizedList(things);

    //However, it actually resolves to :
    //List<String> syncThings = Collections.synchronizedList(things);
  }
} 


An example in which a static import is likely acceptable is a constants class. For example, a scientific or engineering application might make wide use of Math.PI. A static import of java.lang.Math.* would allow a class to replace Math.PI with PI.

More generally, a business application might define a constants class, and import it statically. This would allow Consts.NEW_LINE to be referenced as NEW_LINE, for example.

See Also :
Class for constants
Uncommon classes need explicit imports
Interface for constants
Would you use this technique?
Yes   No   Undecided   
© 2014 Hirondelle Systems | Source Code | Contact | License | RSS
Individual code snippets can be used under this BSD license - Last updated on September 21, 2013.
Over 2,000,000 unique IPs last year - Built with WEB4J.
- In Memoriam : Bill Dirani -