I am analyzing a code and I have found the class Constantes
, which, as its name indicates, has this structure:
public final class Constantes {
public static final String PREFIJO = "prefijo_";
}
In another class I have seen this import
:
import static mi.paquete.Constantes.*;
So when using the constant class attributes you do so directly by name,
String nombreFichero = PREFIJO + nombre;
No need to reference the class as with normal imports:
String nombreFichero = Constantes.PREFIJO + nombre;
I did not know the technique of import static
and it seems quite interesting to me to clean code, as long as:
- Your application is well structured
- used with head
- Don't create confusion by knowing where the constants come from.
But:
- Are there any contraindications when using this technique?
This feature is available since Java 6 and supports a lot of code reduction and readability. Just be careful in case you statically import two or more classes that have static elements (field or method) with the same name since the compiler will not know which class to choose and will throw a compilation error. Here an example:
For these cases, it is resolved using the class and name of the field to use. For the case above, a possible solution is:
Another very important point is when showing snippets or code fragments to your colleagues or online where you use static fields, make sure you add the
import static
necessary ones, especially when showing code from libraries that are not as well known or for the documentation of how to use one. library you have created.As far as I know there is no contraindication, I think it is a clear improvement for reading the code, for example with the Guava library, use of Preconditions :
against
I think it's much more readable.