Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SonarQube - Nested If Depth

Tags:

sonarqube

I'm getting this violation on sonarqube Nested If Depth

 if (some condition){
     some code;
     if (some condition) {
         some code;
     }
 }

and also here:

for (some condition) {
     if (some condition) {
          some code;
     }
}

how can I reduce the depth?

like image 269
james Avatar asked May 31 '26 01:05

james


2 Answers

Answer is already accepted, but doesn't answer the actual question. So for completeness sake I want to add my 2 cents. For reference see This question here

The example you list looks like it is dealing with guard conditions. Things like "only run this method if ...." or "only perform this loop iteration if ...."

In these cases, if you have 3 or 4 groups of guards you might end up indenting very deeply, making the code harder to read.

Anyways the way to fix this code to be more readable is to return early. instead of

if (some condition) {
    // some code
    if (some other condition) {
        // some more code
    }
}

You can write

if (!some condition) {
    return;
}

// some code   

if (!some other condition) {
    return;
}

// some more code

You now only every have 1 level of nesting and it is clear that you do not run this method unless 'some condition' has been met.

The same goes for the loop, using continue:

for (some condition) {
    if (some other condition) {
        // some code;
    }
}

becomes

for (some condition) {
    if (!some other condition) {
        continue;
    }
    // some code
}

What you would state here is that unless 'some other condition' is met, you skip this loop.

like image 161
Joeblade Avatar answered Jun 02 '26 15:06

Joeblade


The real question is why is the max depth set to 1 ? It's overkill.

This kind of rule is meant to keep your code readable. More than 2 nested blocks can make the code unreadable, but 1-2 will always be readable.

If you decide to keep the max depth set to 1, you need to refactor your code and put every 2nd condition check inside a separate method. No offense, but unless you have a very specific and good reason to do it, it looks like a bit stupid.

like image 37
Kraal Avatar answered Jun 02 '26 15:06

Kraal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!