我有以下代码:
private Facility updateFacility(Facility newFacility, Facility oldFacility) {
if (newFacility.getCity() != null)
oldFacility.setCity(newFacility.getCity());
if (newFacility.getContactEmail() != null)
oldFacility.setContactEmail(newFacility.getContactEmail());
if (newFacility.getContactFax() != null)
oldFacility.setContactFax(newFacility.getContactFax());
if (newFacility.getContactName() != null)
oldFacility.setContactName(newFacility.getContactName());
// ......
}
大约有14种这样的检查和分配。也就是说,除了少数几个,我需要修改oldFacility对象的所有字段。我得到了这段代码14的圈复杂度,根据SonarQube,它“大于10被授权”。关于如何减少圈复杂度的任何想法?
最佳答案
在程序的某个时刻,您将必须实现以下逻辑:
如果新设施定义了属性,请相应地更新旧设施
如果不是,则不要覆盖旧工具中的先前值。
无需全局查看项目,您可以做的是在每个属性的设置器中移动该逻辑:
public class Facility {
public void setSomething(String something) {
if (something != null) {
this.something = something;
}
}
}
这样,您的
update
方法将简单地是:private Facility updateFacility(Facility newFacility, Facility oldFacility) {
oldFacility.setSomething(newFacility.getSomething());
// etc for the rest
}