Sonar: Control flow statements “if”, “for”, “while”, “switch” and “try” should not be nested too deeply

Anil Thirunagari
1 min readJan 27, 2021

Fixing “Refactor this code to not nest more than 3 if/for/while/switch/try statements.”

Sonar: Control flow statements “if”, “for”, “while”, “switch” and “try” should not be nested too deeply
JAVA: NestedIfDepth
Nested if, for, while, switch and try statements is a key ingredient for making what’s known as “Spaghetti code”. Such code is hard to read, refactor, and therefore maintain.

Noncompliant Code Example

The following code snippet illustrates this rule with the default threshold of 3.

bool conditionA = executeStepA();
if (conditionA){ // Compliant — depth = 1
bool conditionB = executeStepB();
if (conditionB){ // Compliant — depth = 2
bool conditionC = executeStepC();
if (conditionC){ // Compliant — depth = 3, not exceeding the limit

Solution:

bool conditionA = executeStepA();
if (!conditionA) return;

bool conditionB = executeStepB();
if (!conditionB) return;

bool conditionC = executeStepC();
if (!conditionC) return;

--

--