Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use static import?

Tags:

java

import

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

like image 676
javaguy Avatar asked May 07 '10 22:05

javaguy


People also ask

Should I use static imports?

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). In other words, use it when you require frequent access to static members from one or two classes.

Is static import good in Java?

by Joshua Bloch.) This is considered bad Java programming practice because when a class implements an interface, it becomes part of the class's public API. Implementation details, such as using the static members of another class, should not leak into public APIs.

What is the use of static import in Java?

Static import is a feature introduced in the Java programming language that allows members (fields and methods) which have been scoped within their container class as public static , to be used in Java code without specifying the class in which the field has been defined.

What a static import is and what the pitfalls of using this are?

import static is used to import static members of a class, you can import a specific member of class or import en masse. Used sparingly and in case of importing static members of one or two classes, static import in Java can increase readability of a program by removing the boilerplate of repetition of class names.


2 Answers

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

like image 135
Jherico Avatar answered Oct 31 '22 09:10

Jherico


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.

like image 36
Pascal Thivent Avatar answered Oct 31 '22 09:10

Pascal Thivent