Enum Lesson I Learned

来源:互联网 发布:3位字母未注册域名 编辑:程序博客网 时间:2024/05/17 04:10

Current situation: we have several service providers for our business, each of them has different values for a specific enum, for example, SegmentNo, V may have a value set {0,1}, whereas M may have {1,2}, further, our system defines our own enumerations to a unified object, like {10, 20} for the SegmentNo. The question is: How many enums do we need? Our current situation is 3 enums, worse that our team still prefer passing integer type for SegmentNo, rather than Enum, which forms a enum hell, we often pass a wrong value and boring to debug this again and again, developers often confused by the passed value, really unpleasant.

/* We often pass wrong parameter for this kind of API. Don't do this. */public void doSomeBusiness(int vSegmentNo){}
Improvement:
1. Encapsulate the mapping in a single enum if they have same semantic, only differ by value.

public enum SegmentNo {FT(10, 0), H1(20, 1), ET(30, -1);private int id;private int vSegmentNo;SegmentNo(int id, int vSegmentNo) {this.id = id;this.vSegmentNo = vSegmentNo;}public int getId() {return this.id;}public int getvSegmentNo() {return this.vSegmentNo;}}
2. Refactor the API, pass enums instead of integers, fetch the right integer if and only if necessary.

public void doSomeBusiness(SegmentNo sn){int vsn = sn.getvSegmentNo();}
If we code in this manner, unlikely to pass incorrect value between methods. I believe this practice is much better.


原创粉丝点击