尽量简洁
重构前
f ( flag == 1 ){
return true;
}
else{
return false;
}
重构后
return flag == 1;
使用三位运算符
重构前
if ( "Male".equals(gender) ) {
return "Mr.";
}
else{
return "Mrs.";
}
重构后
return "Male".equals(gender) ? "Mr." : "Mrs.";
常量代替硬编码
重构前
for (int i = 0; i < 12; i++) {
this.getDays(i);
//skip...
}
重构后
nt YEAR_MONTHS = 12;
for (int month = 0; month < Month.YEAR_MONTHS; month++) {
this.getDays(month);
//skip...
}
抽象方法
重构前
public boolean isStartAfter(Date date) {
Calendar calendar = BusinessCalendar.getCalendar();
calendar.setTime(date);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
return ( (hour<fromHour)
|| ( (hour==fromHour)
&& (minute<=fromMinute)
)
);
}
public boolean includes(Date date) {
Calendar calendar = BusinessCalendar.getCalendar();
calendar.setTime(date);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
return ( ( (fromHour<hour)
|| ( (fromHour==hour)
&& (fromMinute<=minute)
)
) &&
( (hour<toHour)
|| ( (hour==toHour)
&& (minute<=toMinute)
)
)
);
}
重构后
private boolean tailGreatHead(int headHour, int headMinute, int tailHour,
int tailMinute, boolean includeEqual) {
boolean tailGreatHeadHour = (headHour < tailHour);
boolean tailEqualHeadHour = (headHour == tailHour);
boolean tailGreatHeadMinute = (headMinute < tailMinute);
boolean tailEqualHeadMinute = (headMinute == tailMinute);
boolean tailGreatEqualHeadMinute = tailGreatHeadMinute || includeEqual
&& tailEqualHeadMinute;
return (tailGreatHeadHour || (tailEqualHeadHour && tailGreatEqualHeadMinute));
}
private boolean tailGreatHead(int headHour, int headMinute, int tailHour,
int tailMinute) {
return tailGreatHead(headHour, headMinute, tailHour, tailMinute, false);
}
private boolean tailGreatEqualHead(int headHour, int headMinute,
int tailHour, int tailMinute) {
return tailGreatHead(headHour, headMinute, tailHour, tailMinute, true);
}
public boolean isStartAfter(Date date) {
Calendar calendar = BusinessCalendar.getCalendar();
calendar.setTime(date);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
return this.tailGreatEqualHead(hour, minute, fromHour, fromMinute);
}
public boolean includes(Date date) {
Calendar calendar = BusinessCalendar.getCalendar();
calendar.setTime(date);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
return this.tailGreatEqualHead(fromHour, fromMinute, hour, minute) &&
this.tailGreatEqualHead(hour, minute, toHour, toMinute);
}
尽早结束非正常逻辑
重构前
int count = 0;
if(taskList != null && !taskList.isEmpty()){
//skip...
return count;
}
else {
return count;
}
重构后
nt count = 0;
if(taskList == null || taskList.isEmpty()){
return 0;
}
//skip...
return count;