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:

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

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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With