pythonsonarquberefactoringcognitive-complexity

How to refactor this function to reduce its cognitive complexity issue for using of multiple if-elif-else statements in python?


My question is about how to refactor if-elif-else conditions in the code below.

Piece of code has been changed here due to new implementation.Here V, X, Y are numbers. This code is for generating a random strings.

def get_uid(type, key):

    if type == 'orange_fruit':
        if key == 'juice':
            uid = 'zofj' + uuidV().hex[:X]
        elif key == 'salad':
            uid = 'zofs' + uuidV().hex[:X]
        else:
            uid = 'zofx' + uuidV().hex[:X]
        return uid
    elif type == 'grape':
        if key == 'juice':
            uid = 'zzgj' + uuidV().hex[:X]
        elif key == 'salad':
            uid = 'zzgs' + uuidV().hex[:X]
        else:
            uid = 'zzgx' + uuidV().hex[:X]
        return uid
    elif type == 'kiwi_healthy':
        if key == 'juice':
            uid = 'zkij' + uuidV().hex[:X]
        elif key == 'salad':
            uid = 'zkis' + uuidV().hex[:X]
        else:
            uid = 'zkix' + uuidV().hex[:X]
        return uid
    elif type == 'anar_tasty':
        if key == 'juice':
            uid = 'zatj' + uuidV().hex[:X]
        elif key == 'salad':
            uid = 'zats' + uuidV().hex[:X]
        else:
            uid = 'yx' + uuidV().hex[:X]
        return uid
    elif type == 'apple':
        if key == 'juice':
            uid = 'zppj' + uuidV().hex[:X]
        elif key == 'salad':
            uid = 'zpps' + uuidV().hex[:X]
        else:
            uid = 'zppx' + uuidV().hex[:X]
        return uid
    elif type == 'cherry':
        if key == 'juice':
            uid = 'zchj' + uuidV().hex[:X]
        elif key == 'salad':
            uid = 'zchs' + uuidV().hex[:X]
        else:
            uid = 'zchx' + uuidV().hex[:X]
        return uid

    return uuidV().hex[:Y]

Thanks in advance.


Solution

  • Well, in terms of simplicity...

    def get_uid(my_env, my_type):
        i = my_env[-1]
        t = type[0:2]
        uid = f'z{t}t{i}z' + uuid4().hex[:6]
        
        return uid
    

    Btw I can't really understand the condition for the last return statement. You could Assign None to my_env and my_type and if anyone is None return it:

    def get_uid(my_env=None, my_type=None):
        if my_env == None or my_type == None:
            return uuid4().hex[:18]
        else:
            i = my_env[-1]
            t = type[0:2]
            uid = f'z{t}t{i}z' + uuid4().hex[:6]
        
            return uid