4

Scenario

I need to check if my $type_id variable is one of a certain set of IDs.

For no reason other than readability, I went with

switch($type_id) {
    case Type::SOME_TYPE:
    case Type::SOME_OTHER_TYPE:
    ...
        //do stuff

where most of them cascade down to a common case.

But this increases the cyclomatic complexity to the point where PHPMD starts whining.

So I figured, let's just use in_array() instead.

if (in_array($type_id, [
    Type::SOME_TYPE,
    TYPE::SOME_OTHER_TYPE,
    ...
    ])) {
    //do stuff
}

Question

At this point PHPMD stops complaining, but isn't the cyclomatic complexity still there, just hidden behind the in_array() function?

Alec
  • 1,986
  • 4
  • 23
  • 47

1 Answers1

3

Yes. But the PHPMD rule is for CC inside a single method/function. It doesn't apply the CC across the entire callgraph. In general, you can solve any PHPMD CC warning by extracting a branch into it's own method.

On a side note: consider to replace the conditional with polymorphism.

Gordon
  • 312,688
  • 75
  • 539
  • 559
  • Does that mean that CC is only considered "mess" due to unreadability? – Alec Oct 19 '17 at 12:47
  • @Alec No, it doesn't necessarily mean hard to read. Its more about being able to grasp or reason about a method/function. If there are many possible branches through a piece of code, it gets more difficult to say for this input x, the output will be y. This in turn has direct implications for the number of unit-tests you will need to cover the function. The Wikipedia article is quite thorough: https://en.wikipedia.org/wiki/Cyclomatic_complexity – Gordon Oct 19 '17 at 13:22