radon icon indicating copy to clipboard operation
radon copied to clipboard

Feature request: Cognitive complexity.

Open happy4upa opened this issue 6 years ago • 5 comments

Hi. First of all, thanks for your work. I wonder if anybody interested in implementing the calculation of Cognitive complexity alongside with Cyclomatic complexity. More info: https://www.sonarsource.com/docs/CognitiveComplexity.pdf

happy4upa avatar Jan 08 '19 12:01 happy4upa

@happy4upa Thanks for sharing the paper, it was an interesting read!

Currently I do not have time to implement a new metric. But if you want to give it a go, I'll be happy to review a PR. Essentially, what is needed is the following:

  • a new visitor in radon.visitors that correctly counts cognitive complexity
  • a new function in radon.cli.__init__ that implements the CLI for this metric
  • (possibly) an helper function in radon.complexity
  • tests for all the new code
  • a few paragraphs in the documentation about the new metric

rubik avatar Jan 26 '19 14:01 rubik

I'm very interested in implementing this metric. I do start working in my fork, but couldn't grasp the whole point of metric in relation to Python. If anyone want to collaborate, i'll be very appreciated.

tribals avatar Sep 17 '20 20:09 tribals

@tribals I think you can start by cloning the ComplexityVisitor and incrementing the cognitive complexity score on these elements:

  • if/elif/else
  • for/while
  • break/continue
  • try/except
  • recursion calls
  • mixed boolean operators

That should be reasonably easy and we could already add the basic tests. Then the final part needs to be implemented: the nesting increments. When any of the above statements is found, you don't just increase the score by 1, but also by the nesting level. Then we can also add tests similar to the paper examples.

Some things mentioned in the paper don't apply to Python (do-while loops, switch, goto, etc.), but I'd say the general idea is still extremely interesting. Intuitively, one can see that a function with many nested levels is more complicated than a plain one. While cyclomatic complexity focuses on the number of code paths, cognitive complexity is closely related to readability and maintainability and its rules are applicable to Python too.

rubik avatar Sep 18 '20 15:09 rubik

A python library to compute the cognitive complexity is available in: https://github.com/Melevir/cognitive_complexity

There is also a plugin for flake8: https://pypi.org/project/flake8-cognitive-complexity/

I am not sure if this should be incorporated into radon. or if that should be left to the above tools.

cleder avatar Oct 21 '20 08:10 cleder

Thanks @cleder. I think @tribals can incorporate some of those ideas into Radon.

rubik avatar Oct 21 '20 09:10 rubik