Java Junk             ThinkGeek

Monday, November 28, 2005

Constants.java

Utilizing a single class for constants is simply a poor practice and a non robust J2EE approach to application development. In a very short amount of time, you end up with a single class comprised of constants from all areas of the application. This makes maintenance a nightmare, circumnavigates compile time checking, and allows a illegal and accidental/invalid substitutions. For example if all constants are basic types such as ints or strings then a simple fat fingering could leave you wasting cycles debugging a runtime error which could have been caught at compile time.

Those of you who may be saying; "Yeah that's right so what am I to use instead? How do I trade up my single constants class approach for an enterprise level solution?"

Well the answer,unless you are fortunate enough to be using Tiger, lies in the type safe enum pattern. Chapter fifteen of Effective Java has a complete example which is both Serializable and extensible :
Type Safe Enum Pattern

With a little customization this pattern can be augmented with a regex parse() method for resolving from string/int representations and optimized with a simple cache lookup.

0 Comments:

Post a Comment

<< Home