7

Would it be considered worsening the future readability of the code if I used them throughout the code? For example using:

import static java.lang.Integer.*;

so I can use this code

int a = parseInt(scanner.nextLine());
The Law
  • 344
  • 3
  • 20
  • 11
    Beware. It might be useful for `parseInt` but isn’t for `valueOf`, `toString`, `min` or `max` (as there are tons of methods with these names). Same for the constants `SIZE`, `MIN_VALUE` and `MAX_VALUE`. Hence, you should not import `*` but rather `import static java.lang.Integer.parseInt;`. – Holger Sep 29 '15 at 18:36

2 Answers2

5

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)

For your case 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.

Link for more detail

Rohit Jain
  • 2,052
  • 17
  • 19
  • 1
    The later part also say "Used appropriately, static import can make your program more readable, by removing the boilerplate of repetition of class names." so basically the case of an import I want for parsing integers qualifies as improvement, does it not? Of course, importing something like `System` and then using only `out.printf` would be a bad idea and confusing. – The Law Sep 29 '15 at 18:34
  • Holger added the comment – Rohit Jain Sep 29 '15 at 18:39
0

The only time I think it's appropriate to use import static is when using a lot of Assert.assertXXX(...) when doing some testing (with JUnit, TestNG, etc.).

Every time I caught myself calling a lot of some static functions in a small amount of code, I better refactor to improve readability (instead of doing an import static).

Spotted
  • 4,021
  • 17
  • 33