This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Java in General and the fly likes interface constants Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "interface constants" Watch "interface constants" New topic
Author

interface constants

Somu Sundaram
Greenhorn

Joined: Apr 13, 2004
Posts: 7
Hi,
Why would one define a constant in interface. Why not in the implemented classes. Is there any special purpose for doing so.

I was asked this qn in an interview long back. Somebody pl clarify it.



Thanks and Regards,
S Somu
Chandra Sekhar
Ranch Hand

Joined: Sep 26, 2003
Posts: 90
When you have two or more classes that need to share some constant value(s), but you want the classes to be independent of each other, define the constant values in an interface. You can then implement the interface in both classes .
This is better way of coding than using static variables.

public class One {
public static String CONST= "XYZ";
}

public class Two {
public Two() {
System.out.println(One.CONST);
}
}

Here the issue is that Class One and Two are not independent. Both may be completely unrelated class.This makes class Two less portable.Since it requires class One to function.But when you define constant in an interface it will be something like

public interface Constant {
public static String CONST= "XYZ";
}

public class One implements Constant {
public One() {
System.out.println(CONST);
}
}

public class Two implements Constant {
public Two() {
System.out.println(CONST);
}
}

Interface can exist alone just to provide the classes with constant values.
This technique enhance portability of the classes.Since there are no dependencies on external classes.

Any comments?? Plz correct me if i'm wrong

Rgds
Chandrasekhar S.
SCJP


"Luck is when opportunity meets preparation"
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
Anyone that condones that horrible practice should be shot.
If I were to ask that kind of question in an interview, I'd expect an answer related to the many significant pitfalls in doing such a nasty thing.

If you want an enumeration, use a type-safe enum.
If you need constant String values, define them in a ResourceBundle.

Data members do not belong in an interface.


Tony Morris
Java Q&A (FAQ, Trivia)
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Originally posted by Tony Morris:
Anyone that condones that horrible practice should be shot.


You better be quick on the draw, Tony.

My take is that a strong objection to this practice (as championed by Josh Bloch) is an affectation by folks who haven't tried to see all sides of the issue.

I'll grant you that if there were a class called, say, java.lang.MathConstants that included PI and E and such, implementing that interface to get at the constants could be bad style. But imagine that the Color constants in java.awt.Color were instead defined in a ColorConstants interface. Implementing that interface would, indeed, put the colors into the API of a class. But what if that class was a widget that could appear in various colors? Then the constants are useful both inside and outside the class, and indeed, may belong in the Widget API; they provide a convenient list of color choices to the users of Widget.

Another example, perhaps slightly weaker but no less convincing to me, is a set of constants used by a class as possible method arguments, result codes, or even used internally. A unit test claas may want to use many of these constants too. The unit test class has no relevant public API. It exists to implement tests, not to be consumed by clients. If those constants are defined in a class, the unit test class has to qualify all the names. If they're in an interface, the unit test class can implement it. This may make the test code significantly clearer.

So while I understand Tony and Josh's arguments, I think they don't apply universally. They're a guide in certain circumstances, at best.


[Jess in Action][AskingGoodQuestions]
Warren Dew
blacksmith
Ranch Hand

Joined: Mar 04, 2004
Posts: 1332
    
    2
Not sure exactly which horrible practice we're talking about here. I agree that Ernest provides valid reasons to define constants in a class at times. On the other hand:

When you have two or more classes that need to share some constant value(s), but you want the classes to be independent of each other, define the constant values in an interface. You can then implement the interface in both classes .

This practice doesn't fit into those categories. If you just want to use the constants, there's no need to implement the interface; like Math.E and Math.PI, just use the class name along with the constant name in your code.
[ June 20, 2004: Message edited by: Warren Dew ]
John Smith
Ranch Hand

Joined: Oct 08, 2001
Posts: 2937
Not sure exactly which horrible practice we're talking about here.

The "horrible practice" refers to the anti-pattern of using the so-called constant interfaces, i.e the interfaces consisting solely of static final fileds. As EFH notes, Joshua Bloch advocates against this in his well respected Effective Java. Essentially, the argument is that the interface should be used as a type that can be used to refer to the instances of the class, and any other use of an interface would be inappropriate. Joshua Bloch cites many practical reasons to avoid the use of the constant interfaces.

I agree that Earnest provides valid reasons to define constants in a class at times.

No one objects to defining canstants in a class. After all, this is where the implementation detail can be exposed. The argument here is about defining the constants in the interface. I see no reason to deviate from purity of the interfaces and subject them to the hardship of the implementation detal, such as the constants. The EFH's counterexamples are somewhat unconvincing to me. Perhaps a code example would help.
[ June 20, 2004: Message edited by: Eugene Kononov ]
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

Originally posted by Tony Morris:
Anyone that condones that horrible practice should be shot.


While I'm not a fan of black-and-white decisions, I'm close to this too.

My experience is related to an example where a whole collection of bad coding practices were mixed together and the 'constants interfaces' was just one, but it did manage to create almost unmaintainable code where it was a significant effort to find the interface where a constant was defined.

The short story is that classes exhibit single inheritance, giving you a nice tree stucture. If there is something that exists in the current class but is not defined in the current class, you check the parent classes until you find the implementation.

Interfaces can have multiple inheritance, so instead having a nice heirarchy converging on java.lang.Object, interface definitions can diverge. In our case, the initial developers didn't understand interfaces, and they layers of empty interfaces, extensions that added a single method or constant and all sorts of other nasty habits. To find the definition of a constant (not using Eclipse at the time ), it was easier to search the file system than try to step through the code.

While 'constant interfaces' weren't directly responsible, there wouldn't have been anywhere near the problems if they weren't used.
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608

My take is that a strong objection to this practice (as championed by Josh Bloch) is an affectation by folks who haven't tried to see all sides of the issue.


Without trying to sound nasty, my immediate response is "quite the contrary!". I can only assume that you (and others) have not experienced the dire consequences of (usually other developers) violating this "rule".

Once upon a time, I would have almost* agreed with your reasoning, but today (after learning), I say that reasoning is weak in contrast to the potential pitfalls.

almost*
I certainly do not agree with:

a set of constants used by a class as possible method arguments, result codes, or even used internally. A unit test claas [sic] may want to use many of these constants too. The unit test class has no relevant public API.


An interface members are implicitly public - this seems like a contradiction of requirements when you want something that is internal but you (implicit or not) declare it public.
sever oon
Ranch Hand

Joined: Feb 08, 2004
Posts: 268
I can't resist--I just have to jump in here. :-)

I concede EFH's point that there are valid OO uses for constants in classes and even, yes, interfaces. On the other hand, after working on several enterprise Java projects, one must take into account that once a particular practice shows up in the codebase, any subtle distinctions between proper and improper usage will be ignored. At my last job, for example, if I used a constants interface in a JUnit test class, within a week or two I could expect constant interfaces to start showing up in every conceivable circumstance.

It bothers me that sometimes an exceptional, proper approach must be avoided to cater to the "lowest common denominator". It's a fact, though...too often I've found myself mired in discussions of why when I did something it was fine, but it's not fine for a slightly different circumstance. These sort of discussions almost always end the same way--even if the person to whom the explanation was given sees the point and agrees with it, they still see the drawing of what they consider subtle distinctions as some kind of code Nazi-ism on your part. In my own experience, in this case the constant interface is misused more often than not, and I eschew it even in cases where it would be valid from an OOD standpoint for fear that someone will try to repeat it elsewhere.

Regardless, though, to address the original poster's question (which is something I try to do when I post here :-)), I would say don't use them. The good people at Sun would not have gone to all the trouble of introducing no less than two new language features (static imports and enumerations) in the next major Java release, Tiger, to avoid the constant interface anti-pattern if they thought it was a fine practice.

sev
David Hibbs
Ranch Hand

Joined: Dec 19, 2002
Posts: 374
Originally posted by David O'Meara:

The short story is that classes exhibit single inheritance, giving you a nice tree stucture. If there is something that exists in the current class but is not defined in the current class, you check the parent classes until you find the implementation.


Or, if you follow the common coding convention of ALWAYS prefixing a constant with its class name, it is also easy to find. Self-documenting, one might say.


The problem with interfaces this way is that, as was discussed, you can slap an interface on any class to get access to the constant WITHOUT proper prefixing. Then you can have collision issues, etc, etc etc.


I'm not above the use of constants as such. There are frequent uses for them. However, the best place for them is in a final class with only private constructors so as to FORCE the user to prefix them properly.


"Write beautiful code; then profile that beautiful code and make little bits of it uglier but faster." --The JavaPerformanceTuning.com team, Newsletter 039.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: interface constants