1、使用卫语句
重构前:
public void doSomething(DomainA a) {
if (a != null) {
assignAction;
if (a.getB() != null) {
otherAction;
if (a.getB().getC() instanceof DomainC) {
doSomethingB();
doSomethingA();
doSomthingC();
}
}
}
}
重构后:
public void doSomething(DomainA a) {
if (a == null) {
return ; //log some errorA
}
assignAction;
if (a.getB() == null) {
return ; //log some errorB
}
otherAction;
if (!(a.getB().getC instanceof DomainC)) {
return ;//log some errorC
}
doSomethingA();
doSomethingB();
doSomthingC();
}
2、异常逻辑处理型重构方法实例
重构前:
double getPayAmount() {
double result;
if(_isDead) {
result = deadAmount();
} else {
if(_isSeparated) {
result = separatedAmount();
} else {
if(_isRetired) {
result = retiredAmount();
} else {
result = normalPayAmount();
}
}
}
return result;
}
重构后:
double getPayAmount(){
if(_isDead)
return deadAmount();
if(_isSeparated)
return separatedAmount();
if(_isRetired)
return retiredAmount();
return normalPayAmount();
}
3、异常逻辑处理型重构方法实例
重构前:
public double getAdjustedCapital(){
double result = 0.0;
if(_capital > 0.0 ){
if(_intRate > 0 && _duration >0){
resutl = (_income / _duration) *ADJ_FACTOR;
}
}
return result;
}
重构后:
public double getAdjustedCapital(){
if(_capital <= 0.0 ){
return 0.0;
}
if(_intRate > 0 && _duration >0){
return (_income / _duration) *ADJ_FACTOR;
}
return 0.0;
}
4、异常逻辑处理型重构方法实例
重构前:
/* 查找年龄大于18岁且为男性的学生列表 */
public ArrayList<Student> getStudents(int uid) {
ArrayList<Student> result = new ArrayList<Student>();
Student stu = getStudentByUid(uid);
if (stu != null) {
Teacher teacher = stu.getTeacher();
if(teacher != null) {
ArrayList<Student> students = teacher.getStudents();
if(students != null) {
for(Student student : students) {
if(student.getAge() > = 18 && student.getGender() == MALE) {
result.add(student);
}
}
} else {
logger.error("获取学生列表失败");
}
} else {
logger.error("获取老师信息失败");
}
} else {
logger.error("获取学生信息失败");
}
return result;
}
重构后:
/* 查找年龄大于18岁且为男性的学生列表 */
public ArrayList<Student> getStudents(int uid) {
ArrayList<Student> result = new ArrayList<Student>();
Student stu = getStudentByUid(uid);
if (stu == null) {
logger.error("获取学生信息失败");
return result;
}
Teacher teacher = stu.getTeacher();
if(teacher == null) {
logger.error("获取老师信息失败");
return result;
}
ArrayList<Student> students = teacher.getStudents();
if(students == null) {
logger.error("获取学生列表失败");
return result;
}
for(Student student : students) {
if(student.getAge() > 18 && student.getGender() == MALE) {
result.add(student);
}
}
return result;
}