【代码规范】公共常量封装:接口、枚举还是普通类
1. 背景
虽然项目组定义了软件开发规范,包括了技术选型、接口规范等,但是在实际执行中还是存在一些不足。本文所记录的常量封装就是其中一个问题,目前项目中关于常量的封装存在3种形式,比较混乱。通过查阅相关资料,对使用目的、各封装形式的优缺点进行分析,给出常量封装的推荐使用规范。
2. 3种封装形式
- 普通类
public class ErrorCodeConstant {
public final static String PARAMTER_ERROR = "10001";
public final static String URL_IS_EMPTY = "10002";
}
使用final static来修饰公用常量,直接通过类名.变量名
的形式访问
- 接口
public interface ErrorCodeConstant {
String PARAMTER_ERROR = "10001";
String URL_IS_EMPTY = "10002";
}
接口的变量默认是public final static
修饰的,所以使用接口来封装常量,看起来比较简洁,也用很多开源项目使用接口来封装公用常量,如阿里巴巴的fastjson。但很多人认为这是Bad-Practice,一种反模式的实践,因为接口一般是一类方法的抽象,需要通过实现类来实现功能,用来封装常量不符合设计初衷。
- 枚举
在java 1.5中引入了枚举类,提供了一种更好的封装公用常量的形式。跟接口和普通量相比,枚举类不仅能定义常量,而且能定义相关方法,使用常量的使用更加灵活。
枚举类基础可参考链接:https://blog.****.net/testcs_dn/article/details/78604547
3. 应用场景
“任何脱离实际应用场景的分析都是瞎扯淡” -- 佚名
正如某位大师所说,我们分析问题需要从根源出发,根据我们的使用场景来选择合适的常量封装形式。
使用常量的场景:
- 简单的公有常量定义,如系统常量标识,则直接使用枚举类
public enum SystemEnum {
HIK(1,"hik_"),
DAHUA(2,"dahua_");
private int code;
private String label;
private SystemEnum(int code,String label) {
this.code = code;
this.label = label;
}
public String getLabel() {
return label;
}
}
- 复杂系统的错误码定义等,则推荐使用普通类内定义枚举类来实现。
public class ErrorCodeConstant {
//系统错误
public enum SystemError{
UNKNOW_EXCEPTION(10001, "未知异常"),
PARAM_ERROR(10002, "参数错误");
private int code;
private String label;
private SystemError(int code,String label) {
this.code = code;
this.label = label;
}
public String getLabel() {
return label;
}
}
//数据库错误
public enum DataBaseError{
UNKNOW_EXCEPTION(20001, "未知异常"),
CONNECT_ERROR(20002, "连接错误");
private int code;
private String label;
private DataBaseError(int code,String label) {
this.code = code;
this.label = label;
}
public String getLabel() {
return label;
}
}
}
}