Code complexity is a measure of how complex a piece of code is. The factors that influence the nature of code and its complexity are plenty. Here are two pieces of code to help demonstrate code complexity:
Example (a):
def bar():
x = 1
if x == 2:
print("Success")
Example (b):
def foo():
evens = [2, 4, 6, 8, 10]
odds = [1, 3, 5, 7, 9]
for x in evens:
for y in odds:
product = x * y
If product % 2 == 0:
print “Product result is even”
If product % 5 == 0:
print “Product is divisible by 5”
If product % 3 == 0:
print “Product is divisible by 3”
Example (a) has a much simpler logic when compared to (b).
Quantifying the complexity of example (b) would have to take into account the number of iterations and the number of decisions to be made in each iteration. This means, even though (b) has only one decision statement, its complexity will be exponentially higher given its position under two loops.
Code complexity can be measured in a few different ways and hence it is to be taken into consideration with broader observations and personal experience. It is also important to understand the business critical reasons for measuring code complexity and the reasons behind higher values of the metric.
Why does code complexity matter?
Reading and code maintenance
High code complexity could imply that the code is harder to read and its functionality is harder to understand even with proper documentation in place. This has significant repercussions for engineers and managers - Readable code helps avoid repetition of similar methods thus encouraging code reusability. It is less prone to errors as it is easy to discern, and is faster to improve or fix any bugs.
Additionally, complex code that’s harder to read can directly impact the review times resulting in an increase in the overall cycle time. These issues therefore make it a matter of business concern to observe and optimize code complexity.