Java: refactoring static constants
Posted
by akf
on Stack Overflow
See other posts from Stack Overflow
or by akf
Published on 2009-07-02T02:47:26Z
Indexed on
2010/06/12
22:32 UTC
Read the original article
Hit count: 200
We are in the process of refactoring some code. There is a feature that we have developed in one project that we would like to now use in other projects. We are extracting the foundation of this feature and making it a full-fledged project which can then be imported by its current project and others. This effort has been relatively straight-forward but we have one headache.
When the framework in question was originally developed, we chose to keep a variety of constant values defined as static fields in a single class. Over time this list of static members grew. The class is used in very many places in our code. In our current refactoring, we will be elevating some of the members of this class to our new framework, but leaving others in place. Our headache is in extracting the foundation members of this class to be used in our new project, and more specifically, how we should address those extracted members in our existing code.
We know that we can have our existing Constants class subclass this new project's Constants class and it would inherit all of the parent's static members. This would allow us to effect the change without touching the code that uses these members to change the class name on the static reference. However, the tight coupling inherent in this choice doesn't feel right.
before:
public class ConstantsA {
public static final String CONSTANT1 = "constant.1";
public static final String CONSTANT2 = "constant.2";
public static final String CONSTANT3 = "constant.3";
}
after:
public class ConstantsA extends ConstantsB {
public static final String CONSTANT1 = "constant.1";
}
public class ConstantsB {
public static final String CONSTANT2 = "constant.2";
public static final String CONSTANT3 = "constant.3";
}
In our existing code branch, all of the above would be accessible in this manner:
ConstantsA.CONSTANT2
I would like to solicit arguments about whether this is 'acceptable' and/or what the best practices are.
© Stack Overflow or respective owner