所以我有一个非常不可读的if语句,有人建议我看看德摩根定律并重构它,这样它就会更干净和可读。我知道如何用简单而简短的语句来做到这一点,但我真的不知道如何重构我的代码。请注意,前两个是对象!感谢您的帮助!
if (!userTemplate.getFromAccount().equals(document.getDetails())
&& !userTemplate.getBenAccount().equals(document.getFromAccount())
&& !userTemplate.getDetails().equals(document.getBenAccount())
&& !userTemplate.getBenType().equals(document.getBenType())
&& !userTemplate.getAmount().equals(document.getCreditAmount()))
来自维基百科,德摩根定律可以用简单的术语解释为
不是(A或B(=不是A也不是B;
不是(A 和 B(= 不是 A 或不是 B
所以你目前的if
声明
if (!userTemplate.getFromAccount().equals(document.getDetails())
&& !userTemplate.getBenAccount().equals(document.getFromAccount())
&& !userTemplate.getDetails().equals(document.getBenAccount())
&& !userTemplate.getBenType().equals(document.getBenType())
&& !userTemplate.getAmount().equals(document.getCreditAmount()))
可以重构为
if (!(userTemplate.getFromAccount().equals(document.getDetails())
|| userTemplate.getBenAccount().equals(document.getFromAccount())
|| userTemplate.getDetails().equals(document.getBenAccount())
|| userTemplate.getBenType().equals(document.getBenType())
|| userTemplate.getAmount().equals(document.getCreditAmount())))
将所有这些条件提取到布尔值中也是一个好主意,也会使if
更具可读性。
boolean fromAccountCondition = userTemplate.getFromAccount().equals(document.getDetails());
boolean benAccountcondition = userTemplate.getBenAccount().equals(document.getFromAccount());
boolean detailsCondition = userTemplate.getDetails().equals(document.getBenAccount());
boolean benTypeCondition = userTemplate.getBenType().equals(document.getBenType());
boolean amountCondition = userTemplate.getAmount().equals(document.getCreditAmount()))
然后
if (!(fromAccountCondition || benAccountcondition
|| detailsCondition || benTypeCondition || amountCondition)) {
...
}
注意:我实际上更愿意将否定放在布尔值本身中,即:
boolean fromAccountCondition = !userTemplate.getFromAccount().equals(document.getDetails());
boolean benAccountcondition = !userTemplate.getBenAccount().equals(document.getFromAccount());
boolean detailsCondition = !userTemplate.getDetails().equals(document.getBenAccount());
boolean benTypeCondition = !userTemplate.getBenType().equals(document.getBenType());
boolean amountCondition = !userTemplate.getAmount().equals(document.getCreditAmount()))
然后
if (fromAccountCondition && benAccountcondition
&& detailsCondition && benTypeCondition && amountCondition)) {
...
}
<</div>
div class="one_answers"> 也许我错过了一些东西,但你的 if 语句说!A*!B*!C*!D
等于 !(A+B+C+D)
.
De Morgan定律说(用Java语言编写(:
(!A && !B && !C && ...) == !(A || B || C || ...)
因此,您可以重写代码(为了清楚起见,我缩短了冗长的表达式(:
if (!A && !B && !C && !D && !E)
自
if (!(A || B || C || D || E))