Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reduce Cognitive Complexity in this Python method

I am faced with a challenge.

I have an Python method implemented and the SonarLint plugin of my PyCharm warns me with the message: "Refactor this function to reduce its Cognitive Complexity from 19 to the 15 allowed." but I can't see how to reduce the complexity.

My Python method is:

def position(key):
    if key == 'a':
        return 0
    elif key == 'b':
        return 1
    elif key == 'c':
        return 2
    elif key == 'd':
        return 3
    elif key == 'e':
        return 4
    elif key == 'f':
        return 5
    elif key == 'g':
        return 6
    elif key == 'h':
        return 7
    elif key == 'i':
        return 8
    elif key == 'j':
        return 9
    elif key == 'k':
        return 10
    elif key == 'l':
        return 11
    elif key == 'm':
        return 12
    elif key == 'n':
        return 13
    elif key == 'ñ':
        return 14
    elif key == 'o':
        return 15
    elif key == 'p':
        return 16
    elif key == 'q':
        return 17
    else:
        logger.info('error')

And the warning of SonarLint is:

enter image description here

And if I click on show issue locations it gives me the explanation of how the Cognitive Complexity is calculated: enter image description here

I can't see how to reduce the complex of this function. I know that I can implement another method with the same behaviour using things like the ascii code, but it's not the point of this question.

The summary of the question is how can I follow the suggestion of SonarLint, I mean, how can I reduce the Cognitive Complexity from 19 to the 15 of this particular method.

Something I've noticed is that if I remove elif statements until I have only 14 characters cases, the warning magically disappears.

like image 321
Manuel González Costa Avatar asked Apr 29 '26 12:04

Manuel González Costa


1 Answers

You can refactor this to look some thing like this:

def position(key):
     values ="abcdefghijklmnñopq"
     try:
         return values.index(key)
     except Exception as e:
         print(e) #you can use logger here if you want
>>> position("a")
0
>>> position("z")
substring not found
like image 122
Bendik Knapstad Avatar answered May 02 '26 02:05

Bendik Knapstad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!