我可以删除第二个条件以检查课程是否已满并提高可读性?
...
if (course.isFull()) {
attemptStudentCapacityIncrease(course);
if (course.isFull()) {
// could not increase course student capacity
return;
}
}
// course is not full
...
答案 0 :(得分:2)
创建函数,使其在失败时返回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;
}
}
但请记住仅在特殊情况下使用例外;)。
答案 1 :(得分:0)
或者,如果您无法更改API:
int attempts = 3;
while (attempts-- && course.isFull())
attemptStudentCapacityIncrease(course);
if (attempts == 0)
return;
答案 2 :(得分:0)
您也可以抛出自定义异常。
if (course.isFull()) {
try {
attemptStudentCapacityIncrease(course);
} catch (IncreaseCourseException ice) {
return;
}
}
我认为它比在attemptStudentCapacityIncrease中返回布尔值更好,但效率较低,因此它取决于在实践中调用方法的频率(以及您认为看起来更好的方式)