What is a good use case for static import of methods?

Another reasonable use for static imports is with JUnit 4. In earlier versions of JUnit methods like assertEquals and fail were inherited since the test class extended junit.framework.TestCase.

// old way
import junit.framework.TestCase;

public class MyTestClass extends TestCase {
    public void myMethodTest() {
        assertEquals("foo", "bar");
    }
}

In JUnit 4, test classes no longer need to extend TestCase and can instead use annotations. You can then statically import the assert methods from org.junit.Assert:

// new way
import static org.junit.Assert.assertEquals;

public class MyTestClass {
    @Test public void myMethodTest() {
        assertEquals("foo", "bar");
        // instead of
        Assert.assertEquals("foo", "bar");
    }
}

JUnit documents using it this way.


This is from Sun's guide when they released the feature (emphasis in original):

So when should you use static import? Very sparingly! Only use it when you'd otherwise be tempted to declare local copies of constants, or to abuse inheritance (the Constant Interface Antipattern). ... If you overuse the static import feature, it can make your program unreadable and unmaintainable, polluting its namespace with all the static members you import. Readers of your code (including you, a few months after you wrote it) will not know which class a static member comes from. Importing all of the static members from a class can be particularly harmful to readability; if you need only one or two members, import them individually.

(https://docs.oracle.com/javase/8/docs/technotes/guides/language/static-import.html)

There are two parts I want to call out specifically:

  • Use static imports only when you were tempted to "abuse inheritance". In this case, would you have been tempted to have BusinessObject extend some.package.DA? If so, static imports may be a cleaner way of handling this. If you never would have dreamed of extending some.package.DA, then this is probably a poor use of static imports. Don't use it just to save a few characters when typing.
  • Import individual members. Say import static some.package.DA.save instead of DA.*. That will make it much easier to find where this imported method is coming from.

Personally, I have used this language feature very rarely, and almost always only with constants or enums, never with methods. The trade-off, for me, is almost never worth it.