According to the basic rules of cyclomatic complexity, the below code should have a complexity of 2 (only one branch point - the for loop).
function SumArray(array_to_sum) {
var sum = 0;
for (var i = 0; i < array_to_sum.length; i++) {
sum += array_to_sum[i];
}
return sum;
}
Many modern frameworks and so on provide data mapping functions, such as jQuery.each()
or most methods in the Underscore.js
framework. Consider the following code:
function SumArray(array_to_sum) {
var sum = 0;
jQuery.each(array_to_sum, function(index, value) {
sum += value;
});
return sum;
}
By typical rules of cyclomatic complexity, the second example has a CC measure of 1. The work is exactly the same, the human complexity of the function has not changed at all. All I did was exchange one means of looping data for a different means of looping data.
Likewise consider this contrived example where we wrap the internals of our original function in a single self-calling closure, producing a cyclomatic complexity of 1 for the outer method while not actually changing how the method works:
function SumArray(array_to_sum) {
return (function() {
var sum = 0;
for (var i = 0; i < array_to_sum.length; i++) {
sum += array_to_sum[i];
}
return sum;
})();
}
Should true measures of cyclomatic complexity include considerations for data mapping/reduction methods such as jQuery.each()
particularly when using an anonymous local closure?
Perhaps closures should export their complexity to the closing parent. Also perhaps methods in general should be able to define an export complexity that is added to the complexity of any function that calls it - for example perhaps jQuery.each()
should have an export complexity of 1 so that using this in place of a normal loop counts complexity the same.