Practical Examples
3. Let's Get Our Hands Dirty with Code
Okay, enough theory. Let's look at some code examples and see how to calculate cyclomatic complexity in practice. Remember, we're aiming to keep things straightforward, so we'll start with simple examples and gradually increase the complexity.
Example 1: A Simple `if` Statement
function isPositive(number) { if (number > 0) { return true; } else { return false; }}
In this example, we have one `if` statement. This means there are two possible paths: one where `number > 0` is true, and one where it's false. Therefore, the cyclomatic complexity is 2 (or 1 + the number of decision points).
Example 2: An `if-else if-else` Statement
function compareNumbers(a, b) { if (a > b) { return "a is greater than b"; } else if (a < b) { return "a is less than b"; } else { return "a is equal to b"; }}
Here, we have one `if` and one `else if` statement, giving us three possible paths. The cyclomatic complexity is 3.
Example 3: A Loop
function sumArray(numbers) { let sum = 0; for (let i = 0; i < numbers.length; i++) { sum += numbers[i]; } return sum;}
This code contains a `for` loop, which introduces another decision point (the loop condition). Therefore the cyclomatic complexity is 2. One path would be that the array is empty, and the loop is never entered, and the other path is that the loop is entered, therefore adding a decision point.