魔法值定义

在代码中直接出现的数值,只有在这个数值记述的那部分代码中才能明确了解其含义。

if ("0".equals(vipFlag)) { // 0 is a magic value
// do 1
} else if ("1".equals(vipFlag)) { // 1 is a magic value
// do 2
}

magic value is not good for maintaining code.

public enum UserVipEnum {
VIP("1","会员"),
NOT_VIP("0","非会员"),:;

private String code;
private String desc;

UserVipEnum(String code, String desc) {
this.code = code;
this.desc = desc;
}
}

if(UserVipEnum.NOT_VIP.getCode.equals(userInfo.getVipFlag)){
//非会员,提示去开通会员
tipOpenVip(userInfo);
}else if(UserVipEnum.VIP.getCode.equals(userInfo.getVipFlag)){
//会员,加勋章返回
addMedal(userInfo);
}

a) Use ENUM to resolve the magic value issue.

b) static final define constant value

static final int VIP = 1;
static final int NON_VIP = 0;