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

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;

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store