rubik / radon

Various code metrics for Python code
http://radon.readthedocs.org/
MIT License
1.75k stars 118 forks source link

Feature request: Cognitive complexity. #163

Open happy4upa opened 5 years ago

happy4upa commented 5 years ago

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

rubik commented 5 years ago

@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:

tribals commented 4 years ago

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.

rubik commented 4 years ago

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

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.

cleder commented 4 years ago

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.

rubik commented 4 years ago

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