如何降低我的方法的圈复杂度

How to reduce Cyclomatic Complexity of my method

下面的代码给出了 35 的圈复杂度。

public void updateGUIInProgress(StatusLabelDTO statusLabelDTO) {
    Display.getDefault().asyncExec(new Runnable() {

        @Override
        public void run() {
            label1.setText(statusLabelDTO.getIterationStr());
            label2.setMaximum(statusLabelDTO.getTotalCount());
            label3.setSelection(statusLabelDTO.getExeIndex());
            label4.setText(statusLabelDTO.getStepStr());
            label5.setText(statusLabelDTO.getPassStr());
            label6.setText(statusLabelDTO.getFailStr());
        }
    });
}

我尝试将所有设置行移动到一个方法中。但是它对我不起作用。如何降低复杂性?

在不知道为您计算圈复杂度的工具的情况下,这真的很难。最后,您的代码没有做太多。

可以像这样重构它:

someDisplayYouAcquiredPreviously.asyncExec(new SpecificRunnable());

显然,这样做需要您之前存储该 Display 对象,并且还需要您使用不同的命名 class 而不是匿名内部 class。

但真正的答案是:查看您的工具。维基百科告诉我们 cyclomatic complexity:

The cyclomatic complexity of a section of source code is the number of linearly independent paths within it. For instance, if the source code contained no control flow statements (conditionals or decision points), the complexity would be 1, since there would be only a single path through the code.

您的代码中只有 一条 路径,因此该值应该是 1,而不是 35。

换句话说:您的工具似乎计算出了错误的数字,可能它不理解 java 语法。因此,真正的答案是退后一步,看看您正在使用的设置/工具。

是的,我发现用户 Hulk 很可能是正确的,您应该将您的工具升级到更新的版本,因为这可能是 "sourcecode monitor" 应用程序中的错误 199

并提示:您知道要退后一步并检查环境中所有其他工具的版本。对更新保守是一回事,但使用 7 年前的旧版本不再 "conservative",这是严重的疏忽。