Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Constants

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

  • Digg
  • Reddit
  • SlashDot
  • Stumble
  • del.icio.us
  • Technorati
  • dzone

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 I'm not aware of any best practices in regard to constants. Before answering your question, I did a quick Web search but didn't turn anything up. So all I can do is tell you what works for me.

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.

About the author

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.
  • Digg
  • Reddit
  • SlashDot
  • Stumble
  • del.icio.us
  • Technorati
  • dzone
Comment
Login
Forgot your account info?
Add comment
Anonymous comments subject to approval. Register here for member benefits.
Have a JavaWorld account? Log in here. Register now for a free account.
Resources