Nested Conditionals CS Thinking Example 4
Follow the full solution, then compare it with the other examples linked below.
Example 4
hardThe following deeply nested code is hard to read. Refactor it to be clearer: IF a > 0 THEN: IF b > 0 THEN: IF c > 0 THEN: OUTPUT 'All positive'. ELSE: OUTPUT 'c not positive'. ELSE: OUTPUT 'b not positive'. ELSE: OUTPUT 'a not positive'.
Solution
- 1 Step 1: Use guard clauses โ check and handle failures first: IF a <= 0 THEN OUTPUT 'a not positive' and EXIT. IF b <= 0 THEN OUTPUT 'b not positive' and EXIT. IF c <= 0 THEN OUTPUT 'c not positive' and EXIT. OUTPUT 'All positive'.
- 2 Step 2: Alternatively, use a combined condition: IF a > 0 AND b > 0 AND c > 0 THEN OUTPUT 'All positive'. But this loses the specific error messages.
- 3 Step 3: Guard clauses flatten the nesting from 3 levels to 1, making the code much easier to read and maintain.
Answer
Use guard clauses: check each negative case and exit early, leaving the 'happy path' at the end. This eliminates deep nesting.
Deep nesting makes code hard to read and maintain. Guard clauses (early returns for failure cases) are a widely-used refactoring pattern that flattens nested conditionals.
About Nested Conditionals
Conditional statements placed inside other conditional statements, creating multiple levels of decision-making. The inner condition is only evaluated when the outer condition is true, allowing programs to model complex, multi-step decisions.
Learn more about Nested Conditionals โMore Nested Conditionals Examples
Example 1 easy
Trace the following code when age = 15 and hasTicket = TRUE: IF age >= 12 THEN: IF hasTicket THEN: O
Example 2 mediumRewrite this nested IF as a single condition using AND: IF temperature > 20 THEN: IF NOT raining THE
Example 3 mediumWrite nested conditionals for a cinema discount: Seniors (age >= 65) get 50% off. Children (age < 12