Skip to main content

Are you using static import?

Posted by cayhorstmann on August 6, 2009 at 10:00 PM PDT

I am rewriting a Java book for beginners, and it seems to make so much sense
to use

import static java.lang.System.out;

public class Greeting
{
   public static void main(String[] args)
   {
      out.println("Hello, World!");
   }
}

static.jpg

I would no longer have to
dissect the awful System.out.println("Hello, World!") expression.
(Ok, boys and girls. System is a class. System.out is
a static field of type PrintStream. That's another class. What is
static, you ask? It's what a TV set makes when it doesn't get a signal. No,
it's what you don't want in your dryer. Ok, whatever it is, you don't ever want
to do it in your code, unless it is also final. That means, you
can't change it. Oh, you spotted

href="http://java.sun.com/javase/6/docs/api/java/lang/System.html#setOut(java.io.PrintStream)">System.setOut
.
Next question?)

Ditto with mathematical expressions. Doesn't

sin(angle * PI / 180)

look so much nicer than

Math.sin(angle * Math.PI / 180)

Ok, at least to that tiny fraction of the population who knows
trigonometry...

The fact is, I don't recall ever seeing anyone using static import outside
JUnit 4, where it is justifiably popular to import
org.junit.Assert.*.

I made a Google search, only to find a href="http://www.davidflanagan.com/blog/000028.html">sensible blog whose
comments were filled with rants that static imports are the work of the
antichrist, something on href="http://blogs.msdn.com/ericgu/archive/2004/07/01/171141.aspx">static
imports in C#, a href="http://www.javapractices.com/topic/TopicAction.do?Id=195">recommendation
to use it rarely, and the usual certification garbage ( href="http://www.ucertify.com/article/what-is-static-import.html">here and
href="http://books.google.com/books?id=YH8UbBTEaOQC&pg=PA96&lpg=PA96&dq=static+import&source=bl&ots=0umb9u9rER&sig=t4dLIZVjEuf3zfRM9zgOz69oGYU&hl=en&ei=P657StOXJJDgswOunbXvCg&sa=X&oi=book_result&ct=result&r">here).

I am trying to get the reaction of the average Java coder here. Have you
switched from System.out to out with a static import?
Would you think it weird to look at other people's code that did that? Or would
you welcome it?

Related Topics >>

Comments

For me dkarr summed it up very nicely. I don't like looking at something like out("hello, world"); and having to hunt through the code to figure out whose "out" that is. I want my language to help me with code maintenance and such. Along the same line I recently changed my eclipse settings so that it prefixes all class field references with this. so that I can tell what belongs to the class versus what's local to the method.

If you're literally showing students "hello, world" on the first day, they're not going to understand concepts like "class" and "static" no matter which way you teach it. I'd prefer leaving out static imports - it's just one more concept for them to absorb, and not a trivial one. Better to just say: sin() is a 'function' - a tool that computes a sin for us, and it comes in a 'class' called "Math" - a toolbox that holds tools. And we'll go into a lot more detail later. Then, months or years later, if someone hates typing, can't figure out how to get his IDE to do the typing for him, and hates being very explicit, he'll find static imports on his own. And he'll be disliked by the majority of his peers who feel that being cryptic is best left to teenagers using thumbs on cellphones. :)

I am using the static import feature for certain libraries that I use like 'lwjgl'. It is a OpenGL library wrapper that is primarily composed of static functions. I do this so the code I write looks similar to 'C' OpenGL code and it makes it easy for me and older developers to read and write. As to the question at hand, I think that you should be very careful about using this in your book for beginners, while I think that you should probably mention this feature and clearly state that it is not available on older jvm's.

Actually, I would prefer less of an emphasis of statics in general. If you are using statics so much that you are importing them often, I do believe that your usage of the java language is not a prime example for teaching the language at all. It is a small convenience that should be a rarity in most java source files. This is just my opinion though. I am a die-hard fan of interfaces and polymorphism. I have also found joy in dependency injection. This is where the focus needs to be. There are 1000 books and mega-hit results for tutorials on java on Google. But, authors rarely focus on the concepts and how truly advanced these m just odern languages, and supporting libraries/frameworks are. If we treat them [languages] like C, things don't advance. Doesn't anyone want to get knee deep into it and write some real OO code? I sure as heck do. Hah, enough ranting.

I find it very useful if I'm writing the code (I use gvim most of the time). But if I have to read someone else's code with a bunch of static imports, then I'll advise against it.

kirillcool wrote: "Implementation of fluent APIs rely a lot on the static imports to start the fluent chain." +1 PS- This blog/forum software, Collabnet?, sucks, badly, as in unforgivably bad. It's really too bad there aren't any web developers around here.

I once used a static import to simplify an example, most of the comments were to point out that I had made a mistake, so it does confuse people...at least those who aren't familiar with the technique.

@scotty69: That's a good question. Since it is, to say the least, a challenge to explain public static void main(String[] args) on day one, we tell the students that the structure of a Java program is don't worry about this stuff { }} The static import now becomes part of "don't worry about this stuff", and I can just use out.println(...), which looks to the students exactly like str.length() and all the other method calls they encounter.

I rarely used static import in my code - I think sun hits the nail with its recommended use for static imports -http://www.j2ee.me/j2se/1.5.0/docs/guide/language/static-import.html Shortening System.out.println to out println really does not seem a big improvement - specially in my IDE where I have configured it to expand SOP to System.out.println :)!

How does the static import solve your problem (having to explain what System.out.println is all about)? It's still there, prominently in the first line, and now you have to explain "import static" as well ;-)

Well in C++, I usually include the line of code, "using namespace std", in every source file so I can code: cout << "C++" << endl; instead of std::cout << "C++" << std::endl;

I use them moderately, mainly to shorten some enum literals (that often are declared as inner public classes). I agree that their peruse is probably harmful, but as usual the savvy men stays in the middle ;-) I would not use that for an introductory class - right or wrong, 99.99% of the code your student will see has got the full System.out.println() and perhaps is better that in the introductory class they see common stuff (of course, with the exclusion of bad pratices).

Upon my first reading of the description of the static import feature, I found it disturbing. I think when static import is not used, we can assume implicit information about "where something comes from" that is very helpful in understanding code. The more static import is used, the harder it is to tell where things are coming from. The first time I noticed it used with JUnit 4, I thought "that is just weird". I would be perfectly happy with that being the only time I see it used. Would I be happier if "System.out.println" took a few less characters? Maybe. Does it matter? No. Everyone knows what it means, and the vast majority of people enter that with "sysoutC-sp" and never even think about it. I would be more concerned if someone used static import for that, as that would imply to me that a mechanism to override the output stream has been implemented.

Static imports as well as star imports are pure horror if you need to maintain code written by others. In my company the only static import we are allowing is "package.Class.log". If I encounter anything else I shoot the developer.

I like the idea of static imports, though I have so far only used them with JUnit. I introduced the notion to my company, and we have all setup Eclipse's "favorites" to suggest and do static imports for Assert.* and org.hamcrest.Matchers.*.

I dont find it odd to use static imports, however, not having to use the word System or Logger or whatever is not such a big improvement in productivity, especially with IDEs being so good with code assistance. However, features provided by a library such as http://functionaljava.org/ are super useful when integrated with java.

I just use scala: println("hello") But if you are teaching with java to help them get jobs with java, then just stick with what 99.9% of java developers use: System.out.println

@ricky_clarkson import sys; sys.stdout.write("Is Python really that shorter?\n") # ;-) I've used both `Assert.assertThat` and `assertThat` and am still not sure which I like better. In Unittests using assert* without the namespacing class is OK IMO. If all your class does is computations I would import functions from Math statically but not if you use just one function from Math in a class full of SQL queries. Concerning System.out: I think you should show it as System.out and later on tell your students to avoid using it directly but using a PrintStream parameter or Logging instead ;-).

I've started the process of implementing some hints to support Static Imports in Netbeans. There is an early look in the Experimental Java Hints package, which you need to manually add to your plugin list. More details here, please comment or vote on issues:- http://www.netbeans.org/issues/show_bug.cgi?id=71249 http://www.netbeans.org/issues/show_bug.cgi?id=89258 http://www.netbeans.org/issues/show_bug.cgi?id=164487 http://www.netbeans.org/issues/show_bug.cgi?id=164490

avoid to optimize too early.. :) Just teach the regular concepts and show this little tricks are they are "little optional tricks".. Then the students can decide by themselves if they follow the basics of the language or try a more hacky tricks.... Other point is: 99% of all literacture out there will show to your students System.out.println, so soon or later they will nedd to be familiar with both notations.. IMO: is not the teacher the one to decide what is the best code style.. even for begginner students.. just expose them to the knowledge, they will be smart enough to find the most productive path following their mood....

I always use the following explanation: "System.out is an object that represents the console window. It has various methods to print to it. The object is special because it has a . in its name, which is normally not the case" I do not mention its class. In that way I don't need to say anything about static fields, which would be disastrous in the first lecture. So, I don't see System.out as a problem. The disadvantage of your solution is that any Java snippet that students encounter outside the book/lectures will surprise them. I agree that sin looks nicer than Math.sin, but it's not worth the effort of introducing yet another construct, the static import (btw currently not in the paper version of your book). Moreover, I think Math.sin makes practicing with static methods easier. I'd rather use *less* static stuff: static non-final fields are always a source of confusion for my students, despite the fine explanation in your book (and my lecture). I am considering to drop this topic in coming year's teaching.

Static imports are just as useful as ordinary imports. They remove noise, such as the class name, which for static methods can be quite arbitrary (FooUtility, etc.). bharathch said: "I'd prefer to read the method invocation through the fully qualified identifier". What, java.lang.System.out.println("I wish I'd taken Python instead."); ?

I have nothing against static imports in general, but in this case I'd prefer to read the method invocation through the fully qualified identifier. I'd not want to scroll up the page to know if "out" is System.out or some writer that logs to a file. As for "hiding" System.out to avoid explaining it to students, how would you explain the appearance (out of thin air) of the phantom "out" in the out.println ? You'd still have to tell them what "import static java.lang.System.out" is? Or address questions like "but why do we have to explicitly say java.lang? It is the java lang, isn't it?"

I designed JSR-310 (such as it is) to use static imports for dates/time and so on. Its a difficult choice. IDEs help to some extent (different colour/font) but less so for the initial coding (in Eclipse you have to configure certain classes to be the source of static imports, and that has other negative consequences).

Personally, I use static imports a lot and don't see any reason why I or textbook shouldn't make use of it. P.S. The only thing sometimes bugs me is that my IDE (netbeans) doesn't fill in static imports, which kind of breaks my programming flow ;-)

Implementation of fluent APIs rely a lot on the static imports to start the fluent chain. For example, in FEST the main class is Assertions and it has a bunch of assertThat methods. You would usually use the static import and then have the fluent chain start with assertThat(...) instead of Assertions.assertThat(...) This covers the vast majority of static import usages that i've seen in Java blogosphere over the past couple of years.