前言
在开发过程中,经常会有需要填写返回码来作为返回值的情况,最经典的场景便是请求接口的返回码,例如返回Result:
public class MyResult extends Result {
private Object data;
public Result(ResponseCode responseCode, Object data) {
super(responseCode.getCode());
this.data = data;
setTimestamp(System.currentTimeMillis());
}
}
如果我们要根据不同的处理结果,返回不同的code码以及data,例如:
成功:
return new MyResult(1, "返回成功");
失败:
return new MyResult(-1, "返回失败");
在这种情况下,使用数字1,-1这种形式存在一个问题,若后续需要将成功码返回改成2,便需要把所有的返回成功的场景改为2,明显是可扩展性很差的代码,因此很多处理方式就是将返回码抽成常量,例如:
private static final CODE_SUCCESS = 1;
private static final CODE_FAILURE = -1;
这时候就可以这样子进行使用:
成功:
return new MyResult(CODE_SUCCESS , "返回成功");
失败:
return new MyResult(CODE_FAILURE , "返回失败");
若有多个场景下,便可以使用相同的常量来进行返回,同时还可以很方便的进行修改返回码的值。
这种方法看起来已经很合适了,但是存在一个问题:
在后期随着返回码的场景增加、返回码的数量增加,很容易出现在使用过程中要从多个码中来获取某个码,出现获取错误的情况,例如,有以下Code:
private static final CODE_SUCCESS_UPGRADE = 1;
private static final CODE_SUCCESS_UPDATE = 2;
private static final CODE_SUCCESS_DOWNLOAD = 3;
private static final CODE_SUCCESS = 1;
.......
在使用的过程中就容易出现错误。
那么有没有方法可以更加优雅的实现返回code的统一呢?
这时候就可以通过在类中使用Enum来做常量的保存来进行优化了。
步骤
1、在类中创建内enum
public class Result {
// 添加enum
public enum ResponseCode {
}
private int code;
private long timestamp;
public Result() {
}
public Result(int code) {
System.out.println("code : " + code);
this.code = code;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}
2、给enum设置定义好的值
public enum ResponseCode {
Success(0),
Failure(-1),
AuthenticationFailed(401),
TokenFailed(404);
private int code;
public int getCode() {
return code;
}
ResponseCode(int code) {
this.code = code;
}
}
给每个值设置好良好的变量名,并且给定code,用该code来进行返回。
3、构造函数中修改为传入enum值,替换返回码,将其他构造函数设置为private
public class Result {
public enum ResponseCode {
Success(0),
Failure(-1),
AuthenticationFailed(401),
TokenFailed(404);
private int code;
public int getCode() {
return code;
}
ResponseCode(int code) {
this.code = code;
}
}
private int code;
private long timestamp;
public Result() {
}
public Result(ResponseCode responseCode) {
this.code = responseCode.getCode();
}
}
在使用的时候就可以使用内部定义的code来进行传入。
这样子做有几个好处:
- 在类内部定义好传入规范,避免引用外部常量或者变量时因为外部修改导致错误发生,降低与外界耦合性,增加内聚性。
- 调用时规范用户返回码,避免用户传入异常的码,用户只能够传入内部enum所定义好的code,规范用户传入形式,增加代码稳健性。
- 保证编译时的类型安全,不会因为用户传入非法的类型而导致运行时错误。