Chitika

Wednesday, September 08, 2004

constant classes

Many approaches have been taken toward how should constant values are implemented in Java. In the early days, some developers used to put constant values in an interface, instead of a class.
For example,

public interface Constants {
  public static final Double ZERO = new Double (0.0);
}

But this practice soon becomes less popular, since the OOP experts find that most developers using the interface approach abuse that interface, thus violating what should be the concepts of interface-inheritance. Interface was designed for the main purpose of giving a certain identity or marking that the implementing classes have that ability. While on the other hand, implementing an interface containing constant values just for the sake of lazy coding might beat those initial purposes.

Hence, most developers start taking the final class approach..
For example,

public final class Constants {
  private Constants () { }
  public static final Double ZERO = new Double (0.0);
}

This approach has become more or less de facto standard for defining constant values.

As we grow more and more, code more and more, we learn that it would be better to place as many literal values as possible into constant values within a constant class. If we're talking about a small application, that shouldn't raise any eyebrow. But when we're talking about an enterprise application with more than 10,000 classes, this could trigger a possible refactoring.

AFAIK, there are two refactoring approaches when dealing with a constant class having more than 20 constant values..
We can group the related constant values into nested classes, naming them with the appropriate namespace, or we can create one or more separate (non-nested) constant class(es), assuming that the constant values can be grouped or categorized into two (or more).

I currently don't know which is best..
But I may opt to go with the combination of both approaches whenever possible..

No comments:

Post a Comment