减少循环复杂度,使用多个if语句

问题描述:

我有以下代码:

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对象的所有字段。根据SonarQube,此代码14的循环复杂性超过了授权的10个。关于如何减少圈复杂度的任何想法?

There are around 14 such checks and assignments. That is, except for a few, I need to modify all the fields of the oldFacility object. I'm getting a cyclomatic complexity of this code 14, which is "greater than 10 authorized" as per SonarQube. Any ideas upon how to reduce the cyclomatic complexity?

在程序中的某些时候,您将必须实现以下逻辑:

At some point in your program, you will have to implement the logic:


  • 如果定义了新设施,请相应地更新旧设施

  • ,如果没有,

在不对项目有全局了解的情况下,您可以做的是移动每个属性的设置器中的逻辑:

Without having a global look at your project, what you can do is to move that logic inside the setters of each property:

public class Facility {

    public void setSomething(String something) {
        if (something != null) {
            this.something = something;
        }
    }

}

,您的 update 方法将简单地是:

This way, your update method would simply be:

private Facility updateFacility(Facility newFacility, Facility oldFacility) {
    oldFacility.setSomething(newFacility.getSomething());
    // etc for the rest
}