Should I use static import?

This is a special case but also the perfect use case (and I use it in all my tests):

import static junit.framework.Assert.*;

Here, I find that this makes my tests more readable and it's obvious from where assertXXX come from. But this is an exception. In other situations, I find that static import make things more obscure, harder to read and I don't really use them.


I use static import when working with JUnit's assert (import static org.junit.Assert.*;) and also when I have an enum that is very tied to the class in question.

For example:

Enum file:

public enum MyEnum {
   A, B, C;
}

Class file:

import static MyEnum.*;

public class MyClass {
  MyEnum e;

  public setE(MyEnum newE) {
    if ( newE == A ) {
       // some verification
    }
    e = newE;
  }
}

Note how I was able to do newE == A, instead of newE == MyEnum.A. Comes in handy if you do a lot of these throughout the code.


As the docs say, use it sparingly. Look there for the justifications.

Tags:

Java

Import