According to Wikipedia (https://en.wikipedia.org/wiki/Cyclomatic_complexity):
Cyclomatic complexity is a software metric used to indicate the complexity of a program. It is a quantitative measure of the number of linearly independent paths through a program’s source code. It was developed by Thomas J. McCabe, Sr. in 1976.
As the definition states, this is the number of linearly independent paths. Consider the following code:
1 2 3 4 5 6 7 |
func switchAppearance(isDarkMode: Bool) { if isDarkMode { showDarkUI() } else { showDefaultUI() } } |
What is the cyclomatic complexity of this code? We can see that the code has two paths, or more quickly 1 (if) + 1 = 2.
Let’s try another example:
1 2 3 |
func switchAppearance(isDarkMode: Bool) { isDarkMode ? showDarkUI() : showDefaultUI() } |
What is the cyclomatic complexity of this code? It is again 2. The ternary operator creates two paths.
Let’s try another one:
1 2 3 4 5 |
func calculateAmountToPay() -> Double { let totalProductAmount = calculatProductsAmount() let discountAmount = calculatDiscountAmount() return totalProductAmount - discountAmount } |
What is the cyclomatic complexity of this code? It is 1 because there is only one path.