This week's book giveaway is in the General Computing forum.
We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line!
See this thread for details.
The moose likes Java in General and the fly likes Best practice: static import Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Best practice: static import" Watch "Best practice: static import" New topic
Author

Best practice: static import

Joyce Lee
Ranch Hand

Joined: Jul 11, 2003
Posts: 1392
Hi,

I refer to the past thread regarding static import in Tiger and I feel that this feature compromise readability.

Though we're warned to use it sparingly, do you think we should even bother to use it at all?

Joyce
[ October 20, 2004: Message edited by: Joyce Lee ]
Simon Baker
Ranch Hand

Joined: Sep 09, 2004
Posts: 57
It seems to be a common practise for people to use interfaces to define constants (refer to "Effective Java" by Josh Bloch, Item 17 for further info). The import static should make it easier for the definition and use of constants without resorting to the spurious use of interfaces for the purpose. Thus, I think it's a worthwhile little addition to the language.
Brett McLaughlin
author
Ranch Hand

Joined: Sep 01, 2004
Posts: 30
I think there's a balance that has to occur. It is indeed a nice feature, but can easily create more confusion. For example, I point out in my book that this can create all sorts of -additional- confusion (p. 126), although that's easy with regular imports as well.

In general, I only use static imports if:

1. I'm working with enum values -a lot- in my code

AND

2. The enum value names are -clear-.

If these two cases aren't true, I personally don't get into static import much. But, it's nice to have, for that odd occasion :-)

Thanks
Brett


Series Editor, Head First<br />Author of <a href="http://www.amazon.com/exec/obidos/ASIN/0596102259/newinstance-20" target="_blank" rel="nofollow">Head Rush Ajax</a> and <a href="http://www.amazon.com/Head-First-Object-Oriented-Analysis-Design/dp/0596008678/ref=pd_bbs_sr_1/104-5348268-5670331?ie=UTF8&s=books&qid=1192568453&sr=8-1/newInstance-20" target="_blank" rel="nofollow">Head First OOA&D</a>
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
In some cases, I think static imports could be quite useful. For example, if you're writing a block of code that heavily relies upon a few static methods defined within Math, there's little reason to constantly write Math.whatever in your code. In fact, if you do it too much, code because long and difficult to read. Which of the following is easier to read?



Although these lines of code are quite contrived, I feel that the second line is more readable than the first. I would, of course, implore that appropriate documentation was included and that the programmer imported only the static method(s) needed and no more, to avoid namespace pollution.

But, in some instances, I think this could be an excellent benefit to Java.


SCJP Tipline, etc.
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608

It seems to be a common practise for people to use interfaces to define constants (refer to "Effective Java" by Josh Bloch, Item 17 for further info).


I assume you meant "common and poor practice" instead of just "common practice"?

Item 17 makes this clear:
"The constant interface pattern is a poor use of interfaces" - most informed people, including myself, concur with Bloch.

The better solution is Item 21, the Typesafe Enum Pattern.
The J2SE 5.0 enum keyword is merely a shortcut to writing such a construct.

Just thought I'd clarify.


Tony Morris
Java Q&A (FAQ, Trivia)
Jeff Langr
author
Ranch Hand

Joined: May 14, 2003
Posts: 758
I've effectively used static imports in a JUnit test class, where the code contains assertions using static constants defined in the target class. In this case the context is very clear.

-Jeff-


Author, Agile Java, Essential Java Style. Agile in a Flash. Contributor, Clean Code.
Jeanne Boyarsky
internet detective
Marshal

Joined: May 26, 2003
Posts: 26496
    
  78

Originally posted by Tony Morris:


I assume you meant "common and poor practice" instead of just "common practice"?

Item 17 makes this clear:
"The constant interface pattern is a poor use of interfaces" - most informed people, including myself, concur with Bloch.

The better solution is Item 21, the Typesafe Enum Pattern.
The J2SE 5.0 enum keyword is merely a shortcut to writing such a construct.

Just thought I'd clarify.

Tony,
So does that make me uninformed

I agree that it isn't good to implement a class just to get the interfaces or use constants to represent types. But I don't see what's wrong with putting real constants in an interface and refering to them as MyConstants.MINUTES_PER_HOUR. I could see static imports being useful (and pretty clear) for this sort of thing.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
Jeanne,
I meant that in a nice way.
Nobody knows everything


But I don't see what's wrong with putting real constants in an interface and refering to them as MyConstants.MINUTES_PER_HOUR


Well, Item 34 of Bloch makes it very apparant as to why this practice is general poor form. I have seen a lot of arguments that try to go against Bloch's suggestion, but in my opinion, they have all been arguments that are based on misinterpretation of Item 34 or failure to understand the consequences (e.g. dismissing them as academic).

This might help:
http://java.sun.com/docs/books/effective/
[ October 20, 2004: Message edited by: Tony Morris ]
Jeff Langr
author
Ranch Hand

Joined: May 14, 2003
Posts: 758
Mr Bloch, who had a lot to do with the definition of J2SE 5.0, specifically intended for static import to replace the constant interface antipattern: see http://java.sun.com/features/2003/05/bloch_qa.html and http://www.theserverside.com/blogs/showblog.tss?id=JDK15
.

-j-
Ko Ko Naing
Ranch Hand

Joined: Jun 08, 2002
Posts: 3178
Originally posted by Corey McGlone:



Although these lines of code are quite contrived, I feel that the second line is more readable than the first. I would, of course, implore that appropriate documentation was included and that the programmer imported only the static method(s) needed and no more, to avoid namespace pollution.


Just to share my point of view on it, I feel like for those who just start to learn Java, they won't know that Math class contains round(), cos() and random()... And they need to go back to the import statements above and figure it out...

But the first code provides with the class name "Math". In this case, they don't need to go back to the import statements above to know about the class... This kinda of "easy to read and understand" matters as well...

Just sharing my opinion...


Co-author of SCMAD Exam Guide, Author of JMADPlus
SCJP1.2, CCNA, SCWCD1.4, SCBCD1.3, SCMAD1.0, SCJA1.0, SCJP6.0
Simon Baker
Ranch Hand

Joined: Sep 09, 2004
Posts: 57
Indeed I did mean "common and poor practise". I know it to be common through industrial experience, and to be poor through common sense and education. The reference to Bloch was intended as a reference to the best discussion of why this is poor practise that I have seen. I would encourage anyone who hasn't done so to read "Effective Java" - it will improve what you do badly and cement what you do well. We can all learn something, particularly from someone who is so knowledgable and such a good author.
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
Originally posted by Ko Ko Naing:

Just to share my point of view on it, I feel like for those who just start to learn Java, they won't know that Math class contains round(), cos() and random()... And they need to go back to the import statements above and figure it out...

But the first code provides with the class name "Math". In this case, they don't need to go back to the import statements above to know about the class... This kinda of "easy to read and understand" matters as well...


Notice that I did include, in my original post, the fact that I would expect such lines of code to be documented. For example, the programmer could write "Static methods, such as rand(), cos(), and min() have been imported from java.lang.Math." That way, if any "new" Java programmers look at the code, the associated comments would point them in the right direction.

As I would expect most uses of statically imported methods/constants to be commented explicitly, I think I'd tend to use them in small groups, to make certain pieces of code more readable, rather than scattered out throughout my code.
Jeff Langr
author
Ranch Hand

Joined: May 14, 2003
Posts: 758
Originally posted by Ko Ko Naing:
Just to share my point of view on it, I feel like for those who just start to learn Java, they won't know that Math class contains round(), cos() and random()... And they need to go back to the import statements above and figure it out...

But the first code provides with the class name "Math". In this case, they don't need to go back to the import statements above to know about the class... This kinda of "easy to read and understand" matters as well...


I happen to be a huge proponent of readability in code, as I feel it has a significant impact on the cost of software development. But I would never promote cluttering code for the benefit of someone who doesn't have basic understanding of the Java language.

The Math class is a given; that's why it's in java.lang. Anyone having to do advanced mathematics (really, any Java developer) should certainly be aware of its existence and should have a rough idea of the methods it contains. Also, any decent IDE will quickly tell you where the method is defined.

Having said that, I think java.lang.Math class is the rare exception. Static imports of any other classes should be used sparingly and only where it helps "unclutter" the code.

A comment might or might not be prudent, given the nature of the code. But from my standpoint, if you feel compelled to add a comment to explain a static import, then it's an inappropriate use of static import.

-J-
Jeanne Boyarsky
internet detective
Marshal

Joined: May 26, 2003
Posts: 26496
    
  78

It seems to be a common practise for people to use interfaces to define constants (refer to "Effective Java" by Josh Bloch, Item 17 for further info).

But I don't see what's wrong with putting real constants in an interface and refering to them as MyConstants.MINUTES_PER_HOUR


I'm confused now. The server side link Jeff posted states:
Static Imports

Clients must qualify static members with class name (Math.PI). To avoid this, some programmers put constants in an interface and implement it. BAD - "Constant Interface Antipattern"

This says you should not implement the interface with constants, not that you shouldn't put constants in an interface to begin with. (In my example, I refered to it as MyConstants.MINUTES_PER_HOUR.)
Simon Baker
Ranch Hand

Joined: Sep 09, 2004
Posts: 57
Or perhaps that you should not implement constants with an interface
Eusebio Floriano
Ranch Hand

Joined: Mar 07, 2004
Posts: 235
Hi folks,

Is static import when you use a fully path of a class, and so, you don�t need to import it ?
Like


Regards,


SCJP 1.4 / 5.0 - SCBCD 1.3 - SCWCD 1.4 - IBM 484
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
Originally posted by Vinicius Boson:
Hi folks,

Is static import when you use a fully path of a class, and so, you don�t need to import it ?
Like


Regards,


Vinicus, there are a couple different imports you can do with that statement.

First of all, you can do a normal import so that you don't need to prepend java.lang to String, like this:



Of course, the entire java.lang package is automatically imported for you in every Java program, but you get the idea.

Additionally, Java 1.5 will allow you to import a static field or method so that you don't even need to prepend the class name to the method invocation or field reference, like this:



As you can see, the resultant code makes it appear as if charAt is defined within the class in which it is being invoked (or otherwise visible via inheritance). Of course, that's not the case, but that's what it looks like. Obviously, there's some discussion as to whether or not this is a good thing.

With regards to the "interface defining constants" thing, I think you really just need to use common sense. If a constant value has to do with a specific interface, I think it does belong within the interface declaration. Say, for example, you've created a Circle interface. You might have various other objects implement that interface, such as SolidCircle, DashedCircle, etc. Here's some possible code:



Yeah, it's a contrived example (and I realize PI is already defined in Math), but this is a case in which the constant has to do with the interface and, therefore, I see no problem with defining it within the interface. I have, however, seen interfaces that look like this:



The interface is useless - it contains no methods. Yet any class can implement it and instantly have access to all of these constants. This is an example of the anti-pattern folks are talking about.
Eusebio Floriano
Ranch Hand

Joined: Mar 07, 2004
Posts: 235
Originally posted by Corey McGlone:
This is an example of the anti-pattern folks are talking about.


Corey,
I got exactly your point.

Thx,
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Best practice: static import
 
Similar Threads
static declaration in main
easier way to extract int from string?
Creating my First Object
SCJP 1.5
please help figure out why the standard deviaion is not giving the correct output