Nested Conditionals CS Thinking Example 4

Follow the full solution, then compare it with the other examples linked below.

Example 4

hard
The 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. 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. 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. 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