This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Originally posted by Paul Sturrock: Both are bad, neither are typesafe. Use an enum.
Enums aren't applicable to all constants, are they? For instance, would you use enums for a set of diverse mathematical or physical constants? (Note: this really is a question, because I have hardly any experience of using enums).
Where enums are unavailable, I think an interface is a bit nicer. But don't be tempted to declare any class as implementing that interface; that's a well-known anti-pattern. [ August 07, 2007: Message edited by: Peter Chase ]
Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Joined: Jul 24, 2003
Hi Peter, I am agree with you.because most of the time we need to make string constant. Is there any performance,memory issue with these two approaches.
Enums aren't applicable to all constants, are they? For instance, would you use enums for a set of diverse mathematical or physical constants?
You are, of course, right Peter. My (overly short) answer is based on the inference that Vijay's example describes an enumerated type, rather than a set of "real world" constants. If they don't describe that situation my preference would also be for a final class with a bunch of public static attributes precisely so it can be extended or implemented.
Joined: Jul 24, 2003
Hi Paul & Peter I really appreciate your quick reply could you please clarify that is there any performance,memory issue with these two approaches.
Use static because there's no point in making a copy of these things in every instance of the class. I wouldn't go so far as to call it a performance issue as much as just being tidy and more correct in the semantic meaning.
Use final to make it clear to all readers (and the compiler) that you don't intend for these to ever change.
Using an interface depends. If this class is the primary or only consumer of the constants, I'd be happy to put them there. A "Constants" class for the whole system is not appealing. I'd try to keep them close to where you really use them.
Think about whether THREE should equal "2". I assume that was a quick typo.
Another design that works well:
This is not an exact replacement for your Strings. You could compare your Strings against some user-entered String. But if you want people to call your method with one of several values you provide, this will do it. The type on the method argument tells them what they're dealing with where String does not. [ August 07, 2007: Message edited by: Stan James ]
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi