【发布时间】:2018-10-09 18:57:18
【问题描述】:
我想问一下,基于下面的布尔条件,有许多 else if 语句是否是一种好方法?
public void borrowItem() throws IOException {
boolean ableToBorrow = isUserAbleToBorrow(cardID);
boolean isDemand = checkDemand(title, authorNumber);
boolean userExists = checkIfUserExists(cardID);
if(ableToBorrow && isDemand && userExists) {
//lots of code....
}else if(!ableToBorrow && isDemand && userExists) {
System.out.println("User limit exceeded");
}else if(!ableToBorrow && !isDemand && userExists) {
System.out.println("User limit exceeded and no book demand");
}else if(ableToBorrow && !isDemand && userExists) {
System.out.println("No book demand");
}else if(ableToBorrow && !isDemand && !userExists) {
System.out.println("No book demand and user does not exists");
}else if(ableToBorrow && isDemand && !userExists) {
System.out.println("Unrecognized user!");
}
}
这是一个好方法还是在java中有更好的想法来做到这一点?
【问题讨论】:
-
什么是“好”?只要你的代码可读,多个 if-else 没有错。
-
您可以以分层方式对其进行分段,例如
if (ableToBorrow)和if (isDemand)内部以及if (userExists)内部。可能有更好的方法,我现在看不到。 -
不,不好。很难阅读代码,也很难理解每个条件的作用以及是否涵盖了真/假的所有可能组合。
-
@Maroun 啊,不。根本没有。冗长的 if-else 链(几乎)从来都不是一件好事。尽可能避免它们。
-
@GhostCat 除非你是研究人员 ;) 说真的,有时过度 OOPing 会导致代码错误。如果是一堆 4-5 的 if-else,我可以轻松忍受。
标签: java if-statement conditional sentence