Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CognitiveComplexity should count else if and else as +1 complexity #5447

Closed
sanggggg opened this issue Oct 19, 2022 · 0 comments · Fixed by #5458
Closed

CognitiveComplexity should count else if and else as +1 complexity #5447

sanggggg opened this issue Oct 19, 2022 · 0 comments · Fixed by #5458

Comments

@sanggggg
Copy link
Contributor

sanggggg commented Oct 19, 2022

Expected Behavior

Count else if or else as +1 complexity.

Current Behavior

Currently else if is assessed as nested if, so it counted as +1 +nesting level complexity, and else is not counted as complexity.

    @Test
    fun `else should counts as complexity`() {
        val code = compileContentForTest(
            """
            fun test(condition: Boolean) {
                if (condition) {
                    // do something
                } else {
                    // do something
                }
            }
            """.trimIndent()
        )
        assertThat(CognitiveComplexity.calculate(code)).isEqualTo(2) // was: 1
    }
    @Test
    fun `else if should counts as 1 complexity`() {
        val code = compileContentForTest(
            """
            fun test(condition: Boolean) {
                if (condition) {
                    // do something
                } else if (condition) {
                    // do something
                }
            }
            """.trimIndent()
        )
        assertThat(CognitiveComplexity.calculate(code)).isEqualTo(2) // but was: 3
    }

Context

According to paper of Cognitive Complexity, else if or else should be counted as +1 code complexity.

It assesses hybrid increments for:
● else if, elif, else, …
No nesting increment is assessed for these structures because the mental cost has already been paid when reading the if.

Not including else affects the accuracy of complexity, and the explanation of why else if should be counted as +1 seems to be logical, so it would be good to follow the implementation of the paper.

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

Successfully merging a pull request may close this issue.

2 participants