首页 > 解决方案 > 当唯一改变的是方法时重构 Python 代码?

问题描述

需要一些关于如何重构这种代码的建议,正如你所看到的,所有的基本代码,左,右都是一样的,所有改变的是 .strip(), .lstrip(), .rstrip(),是否有可能以“美丽”的方式重构它?

def clean_whitespaces(input, mode='all', ):
    result = None
    modes = (None, 'all', 'left', 'right')
    if mode not in modes:
        raise ValueError('clean_whitespaces: mode must be one of {}.'.format(modes))

    if mode == None:
        mode = 'all'

    if mode == 'all':
        if isinstance(input, str):
            result = input.strip()
        else:
            input = list(input)
            result = [entry.strip() for entry in input]
        return result

    elif mode == 'left':
        if isinstance(input, str):
            result = input.lstrip()
        else:
            input = list(input)
            result = [entry.lstrip() for entry in input]
        return result

    elif mode == 'right':
        if isinstance(input, str):
            result = input.rstrip()
        else:
            input = list(input)
            result = [entry.rstrip() for entry in input]
        return result

标签: pythonrefactoring

解决方案


您可以为此使用字典:

modes_to_func = {'all': str.strip, 'left': str.lstrip, 'right': str.rstrip}

这样,您可以避免迭代modes

def clean_whitespaces(input, mode='all', ):
    modes = (None, 'all', 'left', 'right')
    modes_to_func = {'all': str.strip, 'left': str.lstrip, 'right': str.rstrip}
    if mode not in modes:
        raise ValueError('clean_whitespaces: mode must be one of {}.'.format(modes))

    if mode is None:
        mode = 'all'

    if isinstance(input, str):
        result = modes_to_func[mode](input)

    else:
        input = list(input)
        result = [modes_to_func[mode](entry) for entry in input]
    return result

推荐阅读