Nested Switch Statement

ID

java.no_nested_switch

Severity

high

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code Smell

Language

Java

Tags

code_smell, control-flow, switch

Description

Reports a switch statement or expression written inside another switch, at any nesting depth. The inner switch is what gets reported — it is the one to pull out into its own method.

Rationale

A nested switch forces the reader to track two independent selector values and two sets of case labels at once, and a break inside the inner switch reads as if it might fall through to the outer one. The code still runs exactly as written; the cost is entirely in how hard it is to follow.

A switch inside a lambda body, or inside an anonymous or local class body, that itself sits inside an outer switch is not reported: the lambda or class body is a separate unit of code the reader already considers on its own.

switch (region) {
  case NORTH:
    switch (tier) {   // Noncompliant -- two selectors to track at once
      case GOLD:
        applyDiscount();
        break;
      default:
        break;
    }
    break;
  default:
    break;
}

Remediation

Move the inner switch into its own method and call it from the case that needs it. Each switch then reads with a single selector in view.

switch (region) {
  case NORTH:
    applyTierDiscount(tier);
    break;
  default:
    break;
}

private void applyTierDiscount(Tier tier) {
  switch (tier) {
    case GOLD:
      applyDiscount();
      break;
    default:
      break;
  }
}

© 2026 Xygeni. All rights reserved