Quick Cyclomatic Complexity Question
Should’ve known better to ask this question on Twitter. Let it not be said that there are no downsides to always poking fun our tendency to take things too seriously.
Here’s some code:
function void Process( Job job ) { for ( var i = 0; i < 5; i++ ) { switch ( job.status ) { case ( JOB_STATUS.NEW ): ProcessNewJob( job ); break; case ( Job_STATUS.CANCELLED ): CancelJob( job ); break; default: UpdateJob( job ); break; } } }
The question is: What is the cyclomatic complexity of this code?
Cyclomatic complexity is a measure of the number of paths through your code. So my first intuition was that the answer is 15. One for each case statement, plus the default, and multiplied by 5 for each time through the loop.
Then it was pointed out to me by someone who has actually used it in practice that the for loop counts as 1 regardless of what’s inside it. This is confirmed here. Which would make the answer 4. This actually does make some sense to some degree because even though we are looping through five times, we aren’t actually adding any new paths through the code. I think. Maybe.
A quick Twitter poll seemed to lean toward 4 as well (after discounting answers that amounted to “it depends”). But I’d like to get some more thoughts on it before calling the matter closed.
Having said that, the most accurate answer was provided by my dear and loving cousin, who I can always count on to put things in perspective: I think the answer is you need to up your medication. That question didn’t even make sense on the metaphysical level.
Kyle the Ontological