简体   繁体   English

如何降低环复杂度?

[英]How can I reduce Cyclomatic complexity?

I have a method like below. 我有下面的方法。 Please help to avoid Cyclomatic complexity. 请帮助避免循环复杂性。

private double getSum(Data data) {
    double total = 0;

    if(parameters.getParam1())
      total += data.getParam1();

    if(parameters.getParam2())
      total += data.getParam2();

    if(parameters.getParam3())
      total += data.getParam3();

    if(parameters.getParam4())
      total += data.getParam4();

    if(parameters.getParam5())
      total += data.getParam6();

    if(parameters.getParam6())
      total += data.getParam6();

    if(parameters.getParam7())
      total += data.getParam7();

    if(parameters.getParam8())
      total += data.getParam8();

    return total;
}

I would create a method like this: 我将创建这样的方法:

double doubleOrZero(boolean condition, double value) {
    return condition ? value : 0.0;
}

Then call it for each paramX , like this: 然后为每个paramX调用它,如下所示:

private double getSum(Data data) {
    double total = 0.0;

    total += doubleOrZero(parameters.getParam1(), data.getParam1());
    total += doubleOrZero(parameters.getParam2(), data.getParam2());
    // ...

As other mentioned, you will be better of to rewrite your Parameter and Data class, to uses them like this: 如前所述,您最好重写ParameterData类,以如下方式使用它们:

double total=0; 
for (int i=1; i<=8;i++)
    if (parameters.hasParam(i))
        total+ = data.getParam(i);
return total;

For the given code sample, it is only possible the reduce boilderplate by using reflection, like this: 对于给定的代码示例,只能通过使用反射来简化化石板,如下所示:

double total=0; 
for (int i=1; i<=8;i++)
    if (parameters.getClass().getMethod("getParam"+i).invoke(parameters)==Boolean.TRUE)
        total+ = (double)data.getClass().getMethod("getParam"+i).invoke(data);
return total;

Here's a hint. 这是一个提示。 Consider the following code: 考虑以下代码:

for (int i = 0; i < 8; i++) {
  if (paramGetters[i].get(parameters)) {
    total += paramGetters[i].get(data);
  }
}

UPDATE1 UPDATE1

Some more hints how this can be made to compile: 还有更多提示如何进行编译:

paramGetters is an array of objects of some type that have an overloaded get method: get(paramters) returns a boolean , get(data) returns a number . paramGetters是具有重载get方法的某种类型的对象数组: get(paramters)返回一个booleanget(data)返回一个number Also, each object calls one of the specific getParam method. 同样,每个对象都调用特定的getParam方法之一。

UPDATE2 UPDATE2

The following lines set the first element of the array: 以下各行设置数组的第一个元素:

paramGetters[0] = new ParamGetter() {
    boolean get(Parameters p) { return p.getGame(); }
    double get(Data d) { return d.getGameValue(); }
}

This is based on OP's comment about the actual methods to be called. 这基于OP关于要调用的实际方法的评论。 I will leave it you to define the class, the array, and the rest of the elements in the array. 我将留给您定义类,数组以及数组中其余元素的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM