Melevir / cognitive_complexity

Library to calculate Python functions cognitive complexity via code.
MIT License
39 stars 7 forks source link

Incorrect counting for break and continue #14

Closed pkolbus closed 4 years ago

pkolbus commented 4 years ago

According to the Cognitive Complexity specification, a fundamental increment is assessed for "goto, and break or continue to a label." (page 7 and section B1; emphasis mine). Simple break and continue do not receive an increment, as illuminated by the example for addVersion() in Appendix C, and by the justification that early exit tends to improve readability (page 7). (Further, the break in linear flow is already accounted for in the if, as break and continue only make sense within a conditional.)

The implementation assesses a structural increment for these constructs, causing complexity scores to be inflated. For example, test_break_and_continue() should be:

assert get_code_snippet_compexity("""
def f(a):
    for a in range(10):  # +1
        if a % 2:  # +2
            continue  # no increment
        if a == 8:  # +2
            break  # no increment
""") == 5
pkolbus commented 4 years ago

I have a patch to fix this, but it touches ast.py within a few lines of #15 -- to avoid merge conflicts, I'll wait until that merges before creating the PR.

Melevir commented 4 years ago

This is actually a huge surprise for me, but it seems like you're right. Thanks again!