views:

698

answers:

9

Just got a review comment that my static import of the method was not a good idea. The static import was of a method from a DA class, which has mostly static methods. So in middle of the business logic I had a da activity that apparently seemed to belong to the current class:

static import some.package.DA.*;
class BusinessObject {
  void someMethod() {
    ....
    save(this);
  }
}

The reviewer was not keen that I change the code and I didn't but I do kind of agree with him. One reason given for not static-importing was it was confusing where the method was defined, it wasn't in the current class and not in any superclass so it too some time to identify its definition (the web based review system does not have clickable links like IDE :-) I don't really think this matters, static-imports are still quite new and soon we will all get used to locating them.

But the other reason, the one I agree with, is that an unqualified method call seems to belong to current object and should not jump contexts. But if it really did belong, it would make sense to extend that super class.

So, when does it make sense to static import methods? When have you done it? Did/do you like the way the unqualified calls look?

EDIT: The popular opinion seems to be that static-import methods if nobody is going to confuse them as methods of the current class. For example methods from java.lang.Math and java.awt.Color. But if abs and getAlpha are not ambiguous I don't see why readEmployee is. As in lot of programming choices, I think this too is a personal preference thing.

Thanks for your response guys, I am closing the question.

+3  A: 

Static imports are the only “new” feature of Java that I have never used and don’t intend to ever use, due to the problems you just mentioned.

Bombe
Thanks Bombe. Well, I do believe they make better sense that to have to extend and interface that just contains a bunch of static finals.
Hemal Pandya
+3  A: 

I agree that they can be problematic from a readability perspective and should be used sparingly. But when using a common static method they can actually increase readability. For example, in a JUnit test class, methods like assertEquals are obvious where they come from. Similarly for methods from java.lang.Math.

Joel
And what's so bad about seeing Math.round(d) versus round(d)?
Steve Kuo
+1 String.format is also nice to import statically
Bent André Solheim
A: 

They're useful to reduce verbiage, particularly in cases where there are a lot of imported methods being called, and the distinction between local and imported methods is clear.

One example: code that involves multiple references to java.lang.Math

Another: An XML builder class where prepending the classname to every reference would hide the structure being built

kdgregory
A: 

I use them when ever I can. I have IntelliJ setup to remind me if I forget. I think it looks much cleaner than a fully qualified package name.

Javamann
You're thinking of regular imports. Static imports let you refer to members of a class without qualifying them with a classname, e.g. static import java.lang.system.out; out.println("foo"); // instead of System.out.println("foo");
sk
Now this is a very good explanation of static imports... too bad I can't +1 a comment
Ubersoldat
+1  A: 

I use it for Color a lot.

static import java.awt.Color.*;

It is very unlikely that the colors will be confused with something else.

jjnguy
you mean `static import java.awt.Color.*`?
Hemal Pandya
+9  A: 

This is from Sun's guide when they released the feature (emphasis in original):

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). ... If you overuse the static import feature, it can make your program unreadable and unmaintainable, polluting its namespace with all the static members you import. Readers of your code (including you, a few months after you wrote it) will not know which class a static member comes from. 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.

(http://java.sun.com/j2se/1.5.0/docs/guide/language/static-import.html)

There are two parts I want to call out specifically:

  • Use static imports only when you were tempted to "abuse inheritance". In this case, would you have been tempted to have BusinessObject extend some.package.DA? If so, static imports may be a cleaner way of handling this. If you never would have dreamed of extending some.package.DA, then this is probably a poor use of static imports. Don't use it just to save a few characters when typing.
  • Import individual members. Say static import some.package.DA.save instead of DA.*. That will make it much easier to find where this imported method is coming from.

Personally, I have used this language feature very rarely, and almost always only with constants or enums, never with methods. The trade-off, for me, is almost never worth it.

Ross
Agreed. I've used static imports veeery occasionally where they've actually made the code significantly easier to follow.
Neil Coffey
A: 

You need to use them when:

  • you wish to use a case statement with enum values
  • you wish to make your code difficult to understand
davetron5000
This is not true. (1) You can use enum constants perfectly well without a static import of them. (2) Static imports of, say, JUnit Assert class methods are clear as a bell. "assertTrue(...)" is just as readable as "Assert.assertTrue(...)", perhaps moreso.
Alan Krueger
if you have 5 static imports in a 500 line class, it is very hard to tell where methods come from.
davetron5000
+1 for when you wish to make your code difficult to understand :)
Hemal Pandya
+2  A: 

Effective Java, Second Edition, at the end of Item 19 notes that you can use static imports if you find yourself heavily using constants from a utility class. I think this principle would apply to static imports of both constants and methods.

import static com.example.UtilityClassWithFrequentlyUsedMethods;

public class MyClass {
    public void myMethod() {
        int foo = UtilityClassWithFrequentlyUsedMethods.myMethod();
        // can be written less verbosely as
        int bar = myMethod();
    }
}

This has advantages and disadvantages. It makes the code a bit more readable at the expense of losing some immediate information about where the method is defined. However, a good IDE will let you go to the definition, so this isn't much of an issue.

You should still use this sparingly, and only if you find yourself using things from the imported file many, many times.

Edit: Updated to be more specific to methods, as that's what this question is referring to. The principle applies regardless of what's being imported (constants or methods).

Rob Hruska
My question is about static-importing *methods*, not fields.
Hemal Pandya
+4  A: 

Another reasonable use for static imports is with JUnit 4. In earlier versions of JUnit methods like assertEquals and fail were inherited since the test class extended junit.framework.TestCase.

// old way
import junit.framework.TestCase;

public class MyTestClass extends TestCase {
    public void myMethodTest() {
        assertEquals("foo", "bar");
    }
}

In JUnit 4, test classes no longer need to extend TestCase and can instead use annotations. You can then statically import the assert methods from org.junit.Assert:

// new way
import static org.junit.Assert.assertEquals;

public class MyTestClass {
    @Test public void myMethodTest() {
        assertEquals("foo", "bar");
        // instead of
        Assert.assertEquals("foo", "bar");
    }
}

JUnit documents using it this way.

Rob Hruska
I'd agree. Simplifying test cases is one place where the intent is unlikely to be misunderstood.
Bill Michell