Contraindications to static import?

3

I'm analyzing a code and I found the class Constantes , which, as its name suggests, has this structure:

public final class Constantes {
    public static final String PREFIJO = "prefijo_";
}

In another class I saw this import :

import static mi.paquete.Constantes.*;

So, by using the attributes of the constant class it does it directly by its 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 clean code, as long as:

  • Your application is well structured
  • Use with head
  • Do not create confusion because you know where the constants come from.

But:

  • Is there any contraindication when using this technique?
asked by Jordi Castilla 11.04.2016 в 13:14
source

2 answers

3

This feature is available from Java 6 and supports code reduction and readability. Just be careful if 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 from and would throw a compilation error. Here is an example:

package edu.ltmj.clases;
public class Prueba {
    public static final int X = 10;
}
package edu.ltmj.interfaces;
public interface Demo {
    int X = 20;
}
package  edu.ltmj.main;
import static edu.ltmj.clases.Prueba.X;
import static edu.ltmj.interfaces.Demo.X;

public class Main {
    public static void main (String[] args) {
        int x = X; //error de compilación 
    }
}

For these cases, it is solved using the class and name of the field to be used. For the case above, a possible solution is:

//se agrega el import de la clase a utilizar
import edu.ltmj.interfaces.Demo;

//se llama al campo relevante 
int x = Demo.X;

Another very important point is when showing snippets or code snippets to your colleagues or online where you use static fields, be sure to add the necessary import static , especially when displaying code from libraries that are not as well known or for the documentation of how to use a library that you have created.

    
answered by 11.04.2016 / 15:14
source
2

As far as I know, there is no contraindication whatsoever, I think it is a clear improvement for reading the code, for example with the Guava library, use of Preconditions :

Preconditions.checkArgument(valor!=null);

against

checkArgument(valor!=null);

I think it is much more readable.

    
answered by 11.04.2016 в 13:42