detekt icon indicating copy to clipboard operation
detekt copied to clipboard

CognitiveComplexMethod false positive: returning anonymous object is complex

Open TWiStErRob opened this issue 3 years ago • 4 comments

Expected Behavior

Anonymous objects are ignored, same as https://github.com/detekt/detekt/issues/1037.

Observed Behavior

image

> Task :checkstyle:detektMain FAILED
checkers\checkstyle\src\main\kotlin\net\twisterrob\gradle\checkstyle\CheckStyleTaskCreator.kt:22:15: The function taskConfigurator appears to be too complex based on Cognitive Complexity (complexity: 17). Defined complexity threshold for methods is set to '15' [CognitiveComplexMethod]

Steps to Reproduce

Implement an interface or base class with an anonymous object literal, and return it from a function.

Context

It seems that the requirements changed, or the split (#5542) regressed #1037; or maybe the cognitive complexity was never supportive of this complexity. When I look at a function that suddenly too complex I look at the first line to get context, at this point (after the initial scare), it's really easy to understand that there's a class declaration in the function. At this point the individual functions inside that class are not relevant for complexity as they're adding to the complexity of the class/object and not the enclosing function.

cc @arturbosch @sanggggg

Your Environment

  • Version of detekt used: 1.22.0
  • Version of Gradle used (if applicable): 7.5.1
  • Gradle scan link (add --scan option when running the gradle task):
  • Operating System and version: Windows 10
  • Link to your project (if it's a public repository): https://github.com/TWiStErRob/net.twisterrob.gradle/blob/0a9c9efa8d3430c2b5b161871bc9f53f053d77af/checkers/checkstyle/src/main/kotlin/net/twisterrob/gradle/checkstyle/CheckStyleTaskCreator.kt#L22-L72

TWiStErRob avatar Nov 22 '22 21:11 TWiStErRob

This issue is stale because it has been open 90 days with no activity. Please comment or this will be closed in 7 days.

github-actions[bot] avatar Feb 26 '23 02:02 github-actions[bot]

This issue was closed because it has been stalled for 7 days with no activity.

github-actions[bot] avatar Mar 05 '23 02:03 github-actions[bot]

@arturbosch @cortinico thoughts on this? I ran into it again, can we reopen with "help wanted"?

TWiStErRob avatar Apr 08 '23 15:04 TWiStErRob

Yes, I do think this was an oversight in the cognitive complexity implementation (I think the rule came much later than the visitor implementation).

Something like in CyclomaticComplexity:

    override fun visitNamedFunction(function: KtNamedFunction) {
        if (!isInsideObjectLiteral(function)) {
            complexity++
            super.visitNamedFunction(function)
        }
    }

    private fun isInsideObjectLiteral(function: KtNamedFunction) =
        function.getStrictParentOfType<KtObjectLiteralExpression>() != null

arturbosch avatar Aug 14 '23 19:08 arturbosch