java - 降低圈复杂度,多个if语句java

标签 java complexity-theory reduce

我还有很多没有包含的 else-if 条件。我如何重构它以降低圈复杂度?

if (ONE.equalsIgnoreCase(eachTag.getNodeName()))
{
    myclassDto.setOne(formatter
            .getElementValueAfterNullCheckWithTrim((Element) eachTag));
}
else if (TWO.equalsIgnoreCase(eachTag.getNodeName()))
{
    myclassDto.setTwo(formatter
            .getElementValueAfterNullCheckWithTrim((Element) eachTag));
}
else if (THREE.equalsIgnoreCase(eachTag.getNodeName()))
{
    myclassDto.setThree(formatter
            .getElementValueAfterNullCheckWithTrim((Element) eachTag));
}
else if (FOUR.equalsIgnoreCase(eachTag.getNodeName()))
{
    myclassDto.setFour(formatter
            .getElementValueAfterNullCheckWithTrim((Element) eachTag));
}
else if (FIVE.equalsIgnoreCase(eachTag.getNodeName()))
{
    myclassDto.setFive(formatter
            .getElementValueAfterNullCheckWithTrim((Element) eachTag));
}
else if (SIX.equalsIgnoreCase(eachTag.getNodeName()))
{
    myclassDto.setSix(formatter
            .getElementValueAfterNullCheckWithTrim((Element) eachTag));
}

如何在 java 中降低此函数的圈复杂度?

最佳答案

你的代码会更容易阅读,同时它也同样“复杂”(虽然实际上并没有那么复杂),如果你:

  • 使用 switch 语句
  • 预先提取 getNodeName() 的值
  • 预先提取getElementValueAfterNullCheckWithTrim()返回的值

    String value = formatter.getElementValueAfterNullCheckWithTrim((Element) eachTag);
    String nodeName = eachTag.getNodeName();
    
    switch (nodeName) {
        case ONE:
            myclassDto.setOne(value);
            break;
        case TWO:
            myclassDto.setTwo(value);
            break;
        ...
    }
    

编辑: 您可能想要重构 DTO 以使其更易于使用,例如

  myclassDto.setValue(nodeName, value)

关于java - 降低圈复杂度,多个if语句java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47905958/

相关文章:

Java Selenium 错误 : NoClassDefFoundError: org/openqa/selenium/HasAuthentication

regex - 正则表达式中的反向引用如何要求回溯?

algorithm - 计算序列的余弦

javascript - JS 包含字符串和字符串数字的数组的平均值

set - 查找集合列表中的所有超集

java - 使用改造转换 json 数组?

java - 如何停止Java中的音频?

javascript - 如何使用reduce()来构建一个对象而不循环多次迭代

java - 比较已存储为对象的数组

c - 我的 LCM 程序的复杂性是多少?