2

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?

james
  • 287
  • 3
  • 5
  • 17
  • I thought the default value for flagging nested if statements was 3, whereas your examples above only have 2 levels. Do you have any more loops or if statements around the code? – matt freake Sep 18 '14 at 09:12
  • Yes, there are more if statement around it but the rule was changed and the max allowed is only 1. What should I do to reduce it, should I refactor it? – james Sep 19 '14 at 06:51

2 Answers2

9

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.

Community
  • 1
  • 1
Joeblade
  • 1,735
  • 14
  • 22
4

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.

Kraal
  • 2,779
  • 1
  • 19
  • 36