Constants

What’s the best way to handle constants in an application?

Q: We frequently deal with constants, especially using LDAP security and retrieving attributes. Where should constants be defined, considering they can be either systemwide or applicationwide?

A:
Lately, I’ve been doing a lot of XML parsing. Before I start writing a parser, I declare an interface that contains a constant for each tag name and attribute. Declaring each tag name allows me to change the markup language without altering my parsing code — I can simply update the constants.

Each parser I write can then use those constants, either by implementing the interface or by referring to the constants directly through the interface. If the class implements the interface, it can use the constants directly. If not, it must access the constants by using the fully qualified Interface.CLASS_NAME.

Implementing the interface gives you a convenient shorthand. However, accessing the constant using the fully qualified interface name gives you a namespace-like mechanism and prevents naming clashes. Based on your application, you must decide which option to use. Since XML can employ namespaces, having a namespace-like constant mechanism is convenient.

When declaring constants, I always follow the convention of using caps and separating words with a “_” character. If you follow a naming convention, you always know when you are dealing with a constant.

I’d be interested to hear how others declare their constants and why. I can post your responses in a future Q&A.

Tony Sintes is a principal consultant at
BroadVision. Tony, a Sun-certified Java 1.1 programmer and Java
2 developer, has worked with Java since 1997.

Source: www.infoworld.com