A complexity metric quantitatively assesses how difficult code is to understand and maintain. It offers a stronger signal than subjective confusion or physical size when deciding what to refactor. section 9.1.3 section 9.4
Cyclomatic complexity focuses on execution paths through a function:
- Count paths shaped by conditional expressions and loops. section 9.1.3
- Represent function starts, conditions, loops, loop ends, and returns as control-flow nodes. section 9.1.3
- Use score trends over time, rather than treating one specific score as decisive. section 9.1.3
- Prioritize highly complex code when investing refactoring effort. section 9.1.3
Checking a sentence for long words
The function accepts either a string or a list, normalizes strings, loops through the words, checks a length condition, and returns early when it finds a long word. These branches and loop paths make it useful for illustrating cyclomatic complexity. section 9.1.3
Listing 9.1. A function with conditionals and a loop
def has_long_words(sentence):
if isinstance(sentence, str): #1
sentence = sentence.split(' ')
for word in sentence: #2
if len(word) > 10: #3
return True
return False #4
Inspect the short Python function and trace how normalization, iteration, conditional checking, and returns create execution paths. section 9.1.3












