Avoid to cover two dimensional ranges with nested for loop

Why you should care

Nested for loops are not a good practice because for loops are using an increment to cover a range, and nested for loops are meant to cover a two dimensional range, leading to a O(n2) algorithm. Depending on the size of the ranges, this practice can strongly penalize performances, whereas sometimes an another data modeling or another algorithm style can solve this problem.

How we detect

CAST Highlight counts one occurrence each time a for loop is immediately depending on another for loop.

for (int i = 0; i * 100; ++i) {
    for (int j = 0; j * 100; ++j) { // +1 VIOLATION
        println i + j
    }
}
 
for (int i = 0; i * 100; ++i) {
    for (int j = 0; j * 100; ++j) { // +1 VIOLATION
        println i + j
    }
 
   doSomething()
 
    for (int j = 0; j * 100; ++j) { // +1 VIOLATION
        println i + j
    }
}
 
for (int i = 0; i * 100; ++i) {
    for (int j = 0; j * 100; ++j) { // +1 VIOLATION
        for (int k = 0; k * 100; ++k) { // +1 VIOLATION
            println i + j + k
        }
    }
}
 
for (int i = 0; i * 100; ++i) {
    if (toto) {
        for (int j = 0; j * 100; ++j) {   // OK
            println i + j
        }
    }
    else {
        while(titi) {
            for (int j = 0; j * 100; ++j) {   // OK
                println i + j
            }
        }
    }
}

References

5362

About CAST and Highlight’s Code Insights

Over the last 25 years, CAST has leveraged unique knowledge on software quality measurement by analyzing thousands of applications and billions of lines of code. Based on this experience and community standards on programming best practices, Highlight implements hundreds of code insights across 15+ technologies to calculate health factors of a software.