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
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.
Learn more about this topic
- Want more? See the Java Q&A index for the full Q&A catalog
- For over 100 insightful Java tips from some of the best minds in the business, visit JavaWorld's Java Tips index
- Speak out in the Java Beginner discussion
- Receive weekly Java programming tips by subscribing to our free Java Tutor newsletter