Java: Refactoring static constants

We are refactoring some code We developed a feature in one project and we want to use it in other projects We are extracting the basis of this function and making it a complete project, which can then be imported from its current project and other projects The job is relatively simple, but we have a headache

When we first developed the framework, we chose to define various constant values as static fields in a single class Over time, these static member lists grow, and this class is used in many places in our code In our current refactoring, we will promote some members of this class to our new framework, but leave others Our headache is to extract the basic members of this class to be used in our new project. More specifically, how should we solve these extracted members in existing code

We know that we can subclass the existing constants class into the constants class of the new project, and it will inherit all the static members of the parent This will allow us to implement changes without touching the code that uses these members to change class names on static references However, the tight coupling inherent in this choice does not 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, you can access all the above contents in the following ways:

ConstantsA.CONSTANT2

I would like to seek debate on whether this is "acceptable" and / or best practice

Solution

>Only classes with static fields are code smells This is not a class

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>