20

How important it is to convert all my import to static import? Why are people still reluctant to use static import?

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
javaguy
  • 4,404
  • 10
  • 32
  • 35
  • possible duplicate of [What is a good use case for static import of methods?](http://stackoverflow.com/questions/420791/what-is-a-good-use-case-for-static-import-of-methods) – Ingo Mar 19 '13 at 18:08

7 Answers7

17

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

vcovo
  • 336
  • 1
  • 3
  • 16
Jherico
  • 28,584
  • 8
  • 61
  • 87
9

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.

Pascal Thivent
  • 562,542
  • 136
  • 1,062
  • 1,124
  • Before I switched to using Spock, I went 1 step further: `public class MyTestClass extends junit.framework.Assert { ... }`. Easy peasy. – Bohemian May 19 '23 at 08:19
5

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.

Joao Coelho
  • 2,838
  • 4
  • 30
  • 36
1

I would say, never use wildcard static imports.

Without wildcarding, on the as needed basis, I think it does reduce the clutter.

Alexander Pogrebnyak
  • 44,836
  • 10
  • 105
  • 121
1

I use a static import only in the most glaringly obvious situations. Remember: concise code is not always the same thing as readable code.

dbyrne
  • 59,111
  • 13
  • 86
  • 103
0

Use of static import is preferred if you are using an IDE.

fastcodejava
  • 39,895
  • 28
  • 133
  • 186
0

It's not at all important to convert existing working code, in fact it's just a needless cost and risk.

You can consider using it for new code, if you can find a compelling use for it. I haven't yet, but I may ...

user207421
  • 305,947
  • 44
  • 307
  • 483