我正在使用Sonar并向我提出建议"Expressions should not be too complex"
如何更好地表达以下代码?
代码
if (eDelivery != null && Boolean.parseBoolean(eDelivery.getReceiveConfirmationElectronically()) &&
!Boolean.parseBoolean(eDelivery.getInvalidEmailAddress()) && !Boolean.parseBoolean(eDelivery.getEmailUndeliverable()) &&
eDelivery.getUserEmailAddress() != null && !eDelivery.getUserEmailAddress().isEmpty()) {
// Implementation code
}
答案 0 :(得分:3)
这些条件都与eDelivery
对象有关,因此请在此处理。
首先,问题是你为什么要对所有这些parseBoolean
调用的属性进行调查,看起来它们应该是布尔值。但好吧,让我们假设你不能改变它。很好,所以添加第二种方法:
public class EDelivery {
public boolean isReceiveConfirmationElectronically() {
return Boolean.parseBoolean(getReceiveConfirmationElectronically())
}
// &etc...
已经大大清理了它:
if (eDelivery != null && eDelivery.isReceiveConfirmationElectronically() &&
!eDelivery.isInvalidEmailAddress() && !eDelivery.isEmailUndeliverable() &&
eDelivery.getUserEmailAddress() != null && !eDelivery.getUserEmailAddress().isEmpty()) {
// Implementation code
但这并未解决条件的数量。所以现在:
// in EDelivery class
public boolean isEmailGood() {
return !isInvalidEmailAddress() && !isEmailUndeliverable() &&
getUserEmailAddress() != null && !getUserEmailAddress().isEmpty())
}
现在我们来了:
if (eDelivery != null && eDelivery.isReceiveConfirmationElectronically() &&
eDelivery.isEmailGood()) {
// Implementation code
此时您已满足要求,但如果您想更进一步:
// in EDelivery class
public boolean canSendElectronicConfirmation(){
return isEmailGood() && isReceiveConfirmationElectronically();
}
这会将您原来的if
声明减少为
if (eDelivery != null && eDelivery.canSendElectronicConfirmation()) {
// Implementation code