user3222372
user3222372

Reputation: 382

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;
}

Upvotes: 1

Views: 644

Answers (4)

user180100
user180100

Reputation:

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:

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

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

Upvotes: 1

Miserable Variable
Miserable Variable

Reputation: 28752

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

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. Also, each object calls one of the specific getParam method.

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. I will leave it you to define the class, the array, and the rest of the elements in the array.

Upvotes: 0

Chriss
Chriss

Reputation: 5629

As other mentioned, you will be better of to rewrite your Parameter and Data class, to uses them like this:

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

Upvotes: 1

Chriss
Chriss

Reputation: 5629

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;

Upvotes: 0

Related Questions