简体   繁体   中英

Should I use static import?

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

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

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.

I would say, never use wildcard static imports.

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

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

如果您使用的是 IDE,则首选使用static import

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 ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM