Skip to content

return; } if (condition) { #2

Description

@bkdotcom

https://blog.sonarsource.com/cognitive-complexity-because-testability-understandability
https://www.sonarsource.com/docs/CognitiveComplexity.pdf

I'd like your thoughts on the computed cognitive complexity of these two functions

// cognitive complexity: 5
function contrivedExample()
{
    foreach ($things as $thing) {     // +1
        if ($thing === 'box') {       // +2
            return;   // (or break, or continue)
        }
        if ($thing === 'hole') {      // +2
            return;
        }
        // ...
    }
    // ...
}

// cognitive complexity: 4
function contrivedExample2()
{
    foreach ($things as $thing) {     // +1
        if ($thing === 'box') {       // +2
            return;
        } elseif ($thing === 'hole') {   // +1
            // using an else if after a return / continue / break is dumb!
            //   but cyclometric complexity encourages it
            return;
        }
        // ...
    }
    // ...
}

from the paper:

an early return can often make code much clearer,

I agree

I feel like this common "pattern"

if (condition) {
    return;  // or break, or continue
}
if (condition) {

should be computed just the same as an if ... else if

thoughts?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions