我可以删除第二个条件来检查课程是否已满和提高可读性?如何重构发生两次的条件语句?
...
if (course.isFull()) {
attemptStudentCapacityIncrease(course);
if (course.isFull()) {
// could not increase course student capacity
return;
}
}
// course is not full
...
我可以删除第二个条件来检查课程是否已满和提高可读性?如何重构发生两次的条件语句?
...
if (course.isFull()) {
attemptStudentCapacityIncrease(course);
if (course.isFull()) {
// could not increase course student capacity
return;
}
}
// course is not full
...
使该函数能够在失败时返回false,成功时返回true。
if (course.isFull()) {
if (!attemptStudentCapacityIncrease(course)) {
// could not increase course student capacity
return;
}
}
您也可以考虑修改功能故障时抛出异常,然后您可以处理这样的:
if (course.isFull()) {
try {
attemptStudentCapacityIncrease(course);
} catch (Exception ex) {
// could not increase course student capacity
return;
}
}
但要记住使用异常只为特殊情况下)。
或者,如果你不能改变的API:
int attempts = 3;
while (attempts-- && course.isFull())
attemptStudentCapacityIncrease(course);
if (attempts == 0)
return;
你也可以引发自定义异常。
if (course.isFull()) {
try {
attemptStudentCapacityIncrease(course);
} catch (IncreaseCourseException ice) {
return;
}
}
我认为这是比返回在attemptStudentCapacityIncrease一个布尔vlaue更好,但效率不高,所以它取决于方法调用频率在初步实践(和你的想法看起来更好)
是的,我不喜欢布尔与方法名称,因为它是,你觉得重命名方法doIncreaseStudentCapacity你怎么看? – Andrew 2012-01-26 23:56:49
我想我可能需要改变方法名称doIncreaseStudentCapacity,如果我要使用这种方法... – Andrew 2012-01-26 23:54:40
我会建议。好的命名是编程imho中最重要的事情。在功能名称中使用“尝试”通常是一件多余的事情。只是增加学生能力可能会更整洁:)。 – clime 2012-01-26 23:59:06
我喜欢为返回布尔值的方法添加诸如“do”之类的词,因为它清楚地表明该方法的结果是否发生了该操作。如果我要使用increaseStudentCapacity,那么看起来这个函数应该“正常工作”,如果它不是这个例外。 – Andrew 2012-01-27 00:05:04