Java重构示例五
关键字:Java 程序设计 重构 示例 技巧 原则 优化 方法
序言
本文通过Java示例代码片段展示了常用重构原则和技巧,供初级开发人员参考。精致的代码能够清楚传达作者的意图,精致的代码是最好的注释,精致的代码非常容易维护和扩展。程序员阅读精致的代码如同大众欣赏优美的散文一样享受。
21 使用类替换类型代码
21.1 重构前
public class LabelComparator implements Comparator, Serializable {
private static final long serialVersionUID = 1L;
public static final int ASC = 1;
public static final int DESC = 2;
private int sortType = ASC;
public LabelComparator() {
}
public LabelComparator(int sortType) {
this.sortType = sortType;
}
public int compare(Object o1, Object o2) {
if (o1 == null && o2 == null) {
return 0;
}
if (o1 == null) {
return -1;
}
if (o2 == null) {
return -1;
}
if (((Label) o1).getIndex() < ((Label) o2).getIndex()) {
return (sortType == ASC) ? -1 : 1;
} else if (((Label) o1).getIndex() > ((Label) o2).getIndex()) {
return (sortType == ASC) ? 1 : -1;
} else {
return 0;
}
}
}
21.2 重构后
public final class SortMode implements Serializable {
private static final long serialVersionUID = 1L;
private static final Map<String, SortMode> INSTANCES = new HashMap<String, SortMode>();
private final int type;
private final String name;
private SortMode(int type, String name) {
this.type = type;
this.name = name;
}
public String toString() {
return name;
}
public static final SortMode ASC = new SortMode(1, "ASC");
public static final SortMode DESC = new SortMode(2, "DESC");
static {<
Java重构示例五
最新推荐文章于 2023-06-10 15:45:58 发布