减少循环复杂度,使用多个if语句 [英] Reducing the cyclomatic complexity, multiple if statements

查看:263
本文介绍了减少循环复杂度,使用多个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
}

这篇关于减少循环复杂度,使用多个if语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆