5 exercises — master the vocabulary of code complexity: cyclomatic and cognitive complexity, maintainability index, Halstead metrics, and using complexity as a risk proxy.
0 / 18 completed
1 / 18
A tech lead reviews a pull request and opens SonarQube, pointing at a result: "This function has a cyclomatic complexity of 15." What does cyclomatic complexity measure, and what does a score of 15 signify?
Cyclomatic complexity is the most widely adopted code complexity metric in the industry — understanding it precisely is essential for code review and quality discussions.
How it is calculated (McCabe, 1976):
M = E − N + 2P
where E = edges (control-flow transitions), N = nodes (code blocks), P = connected components (usually 1 per function).
In practice: M = number of decision points (if, else if, for, while, switch case, catch, &&, ||, ternary) + 1
Score
Risk
Interpretation
1–10
Low
Simple, well-structured; easy to test
11–20
Medium
Moderately complex; coverage harder to achieve
21–50
High
Error-prone; refactoring recommended
>50
Very High
Practically untestable; urgent refactoring needed
Score of 15 — what it means operationally:
• Requires a minimum of 15 unit test cases to achieve full branch coverage
• Statistically correlated with higher defect density (Basili et al., NASA research)
• SonarQube flags complexity >10 as a code smell requiring refactoring or justified exception
Key vocabulary:
• Cyclomatic complexity — the number of linearly independent paths through code
• Decision point — any branch in the control flow (if, for, while, case, &&, ||)
• Defect density — the ratio of known defects to a unit of code size or complexity
2 / 18
A senior engineer runs a static analysis scan and says: "The cyclomatic complexity is only 8, but the cognitive complexity is 24 — this code is still a maintenance problem." What is cognitive complexity, and how does it differ from cyclomatic complexity?
Cognitive complexity was introduced by SonarSource specifically because cyclomatic complexity can underestimate how hard deeply nested code is to read and maintain.
How cognitive complexity is scored:
• +1 for each structural break to linear flow: if, else if, else, for, while, do-while, switch, catch
• +1 additional for each extra level of nesting beyond the first (nesting penalty)
• +1 for each sequence of logical operators (&& / ||) — consecutive same operators count as one
• 0 for helper method calls (rewards extraction into smaller functions)
Why the example is informative:
A function can have few decision points (cyclomatic = 8) but deeply nest them, forcing a developer to mentally "unwind" multiple context levels simultaneously. Cognitive complexity captures that reading difficulty.
Metric
Measures
Penalises nesting?
Cyclomatic
Testability — minimum test cases
No
Cognitive
Human readability effort
Yes — multiplier applied per depth level
Key vocabulary:
• Cognitive complexity — a measure of how hard code is for a human to read and understand
• Nesting penalty — the additional complexity score applied for deeply nested structures
• Structural break — any construct that interrupts sequential program flow
3 / 18
A SonarQube report shows a maintainability index of 38 for a critical module. The tech lead says: "This is solidly in the red zone." What does the maintainability index measure, what range defines the red zone, and what should the team do?
The maintainability index is a composite code quality metric that aggregates multiple dimensions of complexity into a single actionable number.
Formula (Microsoft Visual Studio / SonarQube variant):
MI = MAX(0, (171 − 5.2 × ln(Halstead Volume) − 0.23 × Cyclomatic Complexity − 16.2 × ln(Lines of Code)) × 100 / 171)
Score
Rating
Recommended action
85–100
🟢 High (Green)
No action needed
65–84
🟡 Moderate (Yellow)
Monitor; refactor opportunistically
0–64
🔴 Low (Red)
Actively refactor; add to sprint backlog
Score of 38 — corrective actions:
① Identify which sub-metric is driving the low score (usually cyclomatic complexity or function length)
② Extract private methods to reduce function length and decision-point density
③ Split large classes into smaller, focused units with a single responsibility
④ Create a tech debt backlog story with measurable acceptance criteria (e.g. "MI ≥ 70 before next release")
Key vocabulary:
• Maintainability index — composite 0–100 metric combining Halstead volume, cyclomatic complexity, and LOC
• Red zone — code with MI below 65, considered high-risk for safe modification
• Hotspot — a module combining high complexity and high change frequency; top refactoring priority
4 / 18
During a code quality review, a developer says: "This module has a Halstead volume of 842 and a Halstead difficulty of 29." What do these Halstead metrics actually measure?
Halstead metrics (Maurice Halstead, 1977) are derived purely from counting operators and operands in source code, providing objective complexity and implementation effort estimates without running the code.
Symbol
Meaning
η₁
Number of distinct operators
η₂
Number of distinct operands
N₁
Total occurrences of operators
N₂
Total occurrences of operands
N = N₁+N₂
Program length (total tokens)
η = η₁+η₂
Vocabulary (total distinct tokens)
Volume (V = N × log₂η):
Measures the information content — how many bits are theoretically needed to represent the program. Volume 842 is high for a single function; well-factored functions typically have V < 500. Higher volume correlates with longer implementation and review time.
Difficulty (D = (η₁/2) × (N₂/η₂)):
Measures how error-prone the implementation is; a high ratio of repeated operands relative to distinct operands signals that the same variables are used in many ways, increasing the chance of misuse. Difficulty 29 means the developer must manage complex operand reuse at each of 29 conceptual steps, raising bug likelihood.
Key vocabulary:
• Halstead volume — information size of a program derived from operator/operand token counts
• Halstead difficulty — measure of how error-prone the code is to write and understand
• Halstead effort (E = D × V) — estimated total mental effort to implement or comprehend the code
5 / 18
A senior engineer says: "We're using complexity as a proxy for risk when prioritising technical debt in our backlog." What does this mean in practice, and which metrics best support this approach?
Using complexity as a proxy for risk is a data-driven approach to technical debt prioritisation, validated by empirical software engineering research.
The key insight — complexity alone is insufficient:
A complex module that is never modified represents dormant risk. The highest-risk files combine:
• High complexity — hard to understand, hard to modify correctly, hard to test thoroughly
• High churn — changed frequently; every change is an opportunity to introduce a defect
Hotspot analysis methodology (Adam Tornhill, "Software Design X-Rays"):
① Extract complexity scores for all files from SonarQube or CodeScene
② Extract churn data — number of commits per file over the last 6–12 months (git log)
③ Plot the intersection: files with both high complexity AND high churn = hotspots
④ Prioritise refactoring the top 10% of hotspots before adding new features to those areas
Research backing:
• Microsoft Research (Nagappan & Ball): files in the top 10% of complexity have 3–5× higher defect density
• Google engineering studies: reducing complexity in a small fraction of files predicts the majority of bug reduction
Key vocabulary:
• Proxy metric — an indirect measurable indicator used to estimate an unmeasurable quantity
• Hotspot — the intersection of high complexity and high churn; highest-priority refactoring target
• Churn — the frequency of code changes in a file over a given time period
• Defect density — the ratio of defects to a unit of code size or complexity
6 / 18
Sarah is reviewing a pull request for a new user authentication service. The lead developer points out: "The code has a high 'maintainability index' of 52. I'm concerned about this; it suggests the module is difficult to understand and modify, potentially leading to future bugs." Sarah asks, "What does this 'maintainability index' actually represent?"
The maintainability index is a composite metric that attempts to quantify how easy it is to understand, modify, and debug a piece of code. It typically considers factors like code complexity (like cyclomatic complexity), the number of branches in control flow, and the overall structure of the module. A low score signals potential problems with readability and maintainability, indicating increased risk of future issues or difficulty for developers working on the codebase.
7 / 18
During a code review discussion about a recently submitted pull request for a new API endpoint, a developer raises a concern: 'The SonarQube report shows a high 'cognitive complexity' score of 18 for this function. Should we refactor it?' What is *primarily* being indicated by this metric, and why might a high value be problematic?
Cognitive complexity is concerned with *how easy it is for a human to understand* the logic within a code block. It's not about lines of code or execution speed; instead, it assesses how many different paths of execution exist – essentially, how convoluted and difficult it is to follow the flow of control. A high score signals that the function's structure makes it harder for developers to reason about its behavior, increasing the risk of errors during maintenance and modification.
8 / 18
Sarah is reviewing a pull request for a new user authentication service. The lead developer points out: "The code has a high 'maintainability index' of 52. I'm concerned about this; it suggests the module is difficult to understand and modify, potentially leading to future bugs." Sarah asks, "What does this 'maintainability index' actually represent?"
The maintainability index is a composite metric that attempts to quantify how easy it is to understand, modify, and debug a piece of code. It typically considers factors like code complexity (like cyclomatic complexity), the number of branches in control flow, and the overall structure of the module. A low score signals potential problems with readability and maintainability, indicating increased risk of future issues or difficulty for developers working on the codebase.
9 / 18
During a code review discussion about a recently submitted pull request for a new API endpoint, a developer raises a concern: 'The SonarQube report shows a high 'cognitive complexity' score of 18 for this function. Should we refactor it?' What is *primarily* being indicated by this metric, and why might a high value be problematic?
Cognitive complexity is concerned with *how easy it is for a human to understand* the logic within a code block. It's not about lines of code or execution speed; instead, it assesses how many different paths of execution exist – essentially, how convoluted and difficult it is to follow the flow of control. A high score signals that the function's structure makes it harder for developers to reason about its behavior, increasing the risk of errors during maintenance and modification.
10 / 18
Sarah is reviewing a pull request for a new user authentication service. The lead developer points out: "The code has a high 'maintainability index' of 52. I'm concerned about this; it suggests the module is difficult to understand and modify, potentially leading to future bugs." Sarah asks, "What does this 'maintainability index' actually represent?"
The maintainability index is a composite metric that attempts to quantify how easy it is to understand, modify, and debug a piece of code. It typically considers factors like code complexity (like cyclomatic complexity), the number of branches in control flow, and the overall structure of the module. A low score signals potential problems with readability and maintainability, indicating increased risk of future issues or difficulty for developers working on the codebase.
11 / 18
During a code review discussion about a recently submitted pull request for a new API endpoint, a developer raises a concern: 'The SonarQube report shows a high 'cognitive complexity' score of 18 for this function. Should we refactor it?' What is *primarily* being indicated by this metric, and why might a high value be problematic?
Cognitive complexity is concerned with *how easy it is for a human to understand* the logic within a code block. It's not about lines of code or execution speed; instead, it assesses how many different paths of execution exist – essentially, how convoluted and difficult it is to follow the flow of control. A high score signals that the function's structure makes it harder for developers to reason about its behavior, increasing the risk of errors during maintenance and modification.
12 / 18
Sarah is reviewing a pull request for a new user authentication service. The lead developer points out: "The code has a high 'maintainability index' of 52. I'm concerned about this; it suggests the module is difficult to understand and modify, potentially leading to future bugs." Sarah asks, "What does this 'maintainability index' actually represent?"
The maintainability index is a composite metric that attempts to quantify how easy it is to understand, modify, and debug a piece of code. It typically considers factors like code complexity (like cyclomatic complexity), the number of branches in control flow, and the overall structure of the module. A low score signals potential problems with readability and maintainability, indicating increased risk of future issues or difficulty for developers working on the codebase.
13 / 18
During a code review discussion about a recently submitted pull request for a new API endpoint, a developer raises a concern: 'The SonarQube report shows a high 'cognitive complexity' score of 18 for this function. Should we refactor it?' What is *primarily* being indicated by this metric, and why might a high value be problematic?
Cognitive complexity is concerned with *how easy it is for a human to understand* the logic within a code block. It's not about lines of code or execution speed; instead, it assesses how many different paths of execution exist – essentially, how convoluted and difficult it is to follow the flow of control. A high score signals that the function's structure makes it harder for developers to reason about its behavior, increasing the risk of errors during maintenance and modification.
14 / 18
Mark is discussing a complex function with his team. He says: 'This code has a high Cyclomatic Complexity score of 12. It suggests the control flow is highly branched and potentially hard to understand.' What does a high Cyclomatic Complexity score typically *indicate* about the code's design?
Cyclomatic Complexity measures the number of independent paths through a program's source code. A high score signifies that there are many potential branches and decision points, making it harder to trace execution, test thoroughly, and understand the function's behavior. Options A and D misinterpret the metric; a high score doesn't relate to efficiency or design paradigms.
15 / 18
During a Slack conversation, a developer named David asks: 'The SonarQube report flagged this module with a high Maintainability Index of 68. What does that index *specifically* measure in terms of the code's quality?'
The Maintainability Index is a composite metric that attempts to quantify how easy it is to understand, modify, and fix code. It doesn't directly measure lines of code (which is reflected in other metrics) but rather aggregates factors relating to complexity and documentation. Option A is incorrect; the index is about quality, not size. Options B and D are tangential.
16 / 18
In a daily standup meeting, Alex reports: 'We're using Code Complexity scores as a key factor when prioritizing technical debt in our sprint backlog. High complexity is seen as a major risk.' What does this approach *primarily* aim to achieve?
This approach uses complexity scores (like Cyclomatic Complexity) as a proxy for risk. High complexity often indicates convoluted logic that is prone to errors and harder to maintain – therefore, it's prioritized for remediation before it becomes a significant impediment. Option A focuses on standards; B describes the *result* of high complexity, not its purpose; C relates to productivity metrics, and D is an automation task.
17 / 18
During a code review, Emily highlights: 'This class has a Halstead Volume of 458. It suggests the code is relatively dense and potentially difficult to fully understand.' What does the Halstead Volume metric *primarily* attempt to measure?
The Halstead Volume is calculated based on the number of operators and operands within a piece of code. A higher volume generally indicates greater complexity because it suggests more opportunities for different execution paths. Options A and D are incorrect; they represent different aspects of code analysis. Option B is closest to the definition, but 'tokens' is the key term.
18 / 18
A developer writes in a PR description: 'We're using complexity metrics as an indicator of potential future maintenance burden.' What does this statement *imply* about the relationship between code complexity and long-term development costs?
This statement reflects a common principle in software development: complex code tends to be more expensive to maintain over time. The greater the number of branches and dependencies, the harder it becomes for developers to understand, debug, and modify the code, leading to higher costs for future maintenance activities. Options A and D are misleading; C ignores a critical factor.
What does the "Code Complexity Metrics" exercise practise?
Practice the English vocabulary of code complexity metrics: cyclomatic complexity, cognitive complexity, maintainability index, and Halstead metrics. 5 exercises.
How many questions are in this exercise?
This exercise has 18 questions, each multiple-choice with a full explanation shown after you answer.
What English level is this exercise for?
This exercise is tagged Advanced. If the vocabulary feels difficult, browse the Code Quality & Metrics category page for an easier module to start with.
Is this exercise free to use?
Yes. Every exercise on CoderSlingo, including this one, is free with no account, sign-up, or paywall.
Do I get feedback if I answer incorrectly?
Yes — whichever option you choose, right or wrong, you'll immediately see an explanation clarifying the correct term and why the other options don't fit.
Can I retry this exercise?
Yes — once you finish all the questions, a "Try again" button on the results screen resets the exercise so you can practise as many times as you like.
Do I need an account to track my progress?
No account is required. Your progress bar and score for this session are tracked in the browser as you go, but nothing is saved once you leave the page.
Is "Code Complexity Metrics" part of a larger series?
Yes — it's one exercise in the Code Quality & Metrics category on CoderSlingo. See the category page for the full list of related exercises on similar terminology.
Can I link directly to this exercise?
Yes — this exercise has its own permanent URL, so you can bookmark it or share the link directly with a colleague or study partner.
Where can I find more exercises like this one?
See the Code Quality & Metrics category page for related exercises, or browse the main Exercises hub for other IT English topics.