以下代码初看感觉挺正常的,以前也写过类似的代码。但它违反了单一职责原则和开闭原则,每次添加新类型时,就必须要修改,最麻烦得是可能还有类似的结构,如isPayday(Employee e, Date date)等。解决方法:将这些代码封装到个抽象类Employee里,子类CommissionedEmployee,HourlyEmployee等实现掉,然后由一个工厂方法构造子类。调用工厂方法获得具体引用,再调用具体的calculatePay,isPayday等方法。switch最终只出现在抽象类的工厂方法里,而且在系统其它部分看不到。
public Money calculatePay(Employee e) throws InvalidEmployeeType {
switch (e.type) {
case COMMISSIONED:
return calculateCommissionedPay(e);
case HOURLY:
return calculateHourlyPay(e);
case SALARIED:
return calculateSalariedPay(e);
default:
throw new InvalidEmployeeType(e.type);
}
}
String listItemContent = match.group(3).trim();
// the trim is real important. It removes the starting
// spaces that could cause the item to be recognized
// as another list
new ListItemWidget(this, listItemContent, this.level + 1);
return buildList(text.substring(match.end()))