Monday, December 31, 2012

Questions from the Mailbag: On Static Imports

"Something I noticed today while I was looking over the Mockito API...they suggest importing the library statically. So I did, and I noticed JUnit was imported statically as well in Eclipse, but other classes/libraries in my Unit Test class were not. What I'm asking then is why do the static import, why does it seem to be important in testing, and when might one want to do it otherwise, if at all?"

 Excellent question! 
Static imports are basically used in Java to allow C/C++ style programming. I fucking hate them. Essentially, they are a feature that was added because programmers are lazy and hate to type. Rather than referencing the class a static method is pulled from, with a static import you can save yourself a few characters.
The argument against them is that they pollute your namespace and are not explicit. 
Polluting your namespace means that, if you have a method with the same name as a statically imported method, the compiler will get confused. This may not be a problem, depending on the class in question. For example, org.junit.Assert's assertEquals() is unlikely to appear in many places. But if you were writing the class OpinionatedCalculator, you may have a problem.
The bigger problem here is that namespace collision is obviously more likely with classes that have more methods. If I statically import something like org.apache.commons.lang.StringUtils  I'm more vulnerable to running into problems with a common word like "contains()."
One could argue this is because StringUtils is too large: in theory a static import on a small class, with relatively few methods (say 3) is "relatively safe."
I say fuck that theory. It's not that much more work to type Assert.assertEquals() than assertEquals(), and it saves me from having to look up at the top of the file to figure out where some magical global method comes from. In that sense, I say it's much more "explicit": The code is obvious the second you look at it.

You know I like my code like I like my porn:
Explicit is Better Than Implicit. 
http://www.python.org/dev/peps/pep-0020/
That said, if you browse through enough of my code on github, you'll find instances where I statically import JUnit. No one's perfect. Sometimes I flip on the opinion based on how lazy I feel like being that day, because I have the option to. Hence why I say it's a bad language feature, and I shouldn't have the option to.
Of course, opponents to that claim would say that code is longer and hence uglier with extra noise words. If the class name is unnecessary and it's clear that the static import makes sense, favor brevity. But if there's one thing you should know about me by now, it's that I like to go on...and on...and on.
Fuck static imports.

No comments:

Post a Comment