jshint: High cyclomatic complexity on switch statements

Currently, every case in a switch block increments the cyclomatic complexity regardless of whether or not it falls through.

This has a complexity of 4:

function(someVal) {
    switch (someVal) {
        case 1:
        case 2:
        case 3:
            doSomething();
            break;
        default:
            doSomethingElse();
            break;
    }
}

This has a complexity of 2 while being logically equivalent:

function(someVal) {
    if (someVal === 1 || someVal === 2 || someVal === 3) {
        doSomething();
    } else {
        doSomethingElse();
    }
}

I’m not an expert in cyclomatic complexity by any means, so I’m honestly not sure if this is correct or not. Even if this is the expected behavior, it seems like it would be nice to at least have a flag which could make these two function calculate the same cyclomatic complexity.

About this issue

  • Original URL
  • State: closed
  • Created 11 years ago
  • Reactions: 9
  • Comments: 37 (25 by maintainers)

Commits related to this issue

Most upvoted comments

Thanks for the heads-up, Gustavo! It would be a shame for that money to go back to Bountysource, especially when Luke contributed a fix almost five years ago. I’ve merged the fix, resolving the conflicts that have been introduced in a half-decade of development.

@lukeapage: your $25 is waiting.

Yes, and for future reference I should avoid commenting or reviewing issues on days that I’m playing video games or otherwise not focusing on the subject at hand.

Why && doesn’t increase cyclomatic complexity count ?

function functionWithCyclomaticComplexityDueToAndOperator_1(a, b) {
  return a && b;
}
// => jshint return complexity 1

function functionWithCyclomaticComplexityDueToOrOperator_2(a, b) {
  return a || b;
}
// => jshint return complexity 2

function functionWithCyclomaticComplexityDueToNegativeAndOperator_1(a, b) {
  return !(!a && !b);
}
// => jshint return complexity 1

Looks strange…

I can increase the complexity of the code without be warned ?

The original cyclomatic complexity counted the number of decision points, which exclude && and ||. The concept of extended cyclomatic complexity includes Boolean operators to attempt to also convey the complexity of the decisions themselves.

The question here isn’t which one is right, but rather which one JSHint is attempting to follow. Perhaps both?

Google “extended cyclomatic complexity” for verification.