Python片段重构

时间:2016-05-22 14:12:51

标签: python refactoring

我有一些小代码片段,我考虑重构。由于DRY原则和代码清晰度,我真的不喜欢sort_paths_by_date方法的一部分:

from os.path import getctime, getmtime

class Endpoint(object):
    def __init__(self, define_path_by, paths):
        self.define_path_by = define_path_by
        self.paths = paths

    def sort_paths_by_date(self):
        if self.define_path_by == 'ctime':
            self.paths = sorted(
                self.paths,
                key=lambda cur_path: getctime(cur_path.path),
            )
        elif self.define_path_by == 'mtime':
            self.paths = sorted(
                self.paths,
                key=lambda cur_path: getmtime(cur_path.path),
            )

我这样做:

from os.path import getctime, getmtime

class Endpoint(object):
    def __init__(self, define_path_by, paths):
        self.define_path_by = define_path_by
        self.paths = paths

    def sort_paths_by_date(self):
        def sort_with_func(func):
            return sorted(
                self.paths, 
                key=lambda cur_path: func(cur_path.path)
            )

        if self.define_date_by == 'ctime':
            self.paths = sort_with_func(getctime)
        elif self.define_date_by == 'mtime':
            self.paths = sort_with_func(getmtime)

但是现在我不确定方法中的函数定义,而且代码清晰度再次让我感到困惑。所以我将非常感谢你在这里的重构经验。

1 个答案:

答案 0 :(得分:2)

你的功能似乎有点不必要的复杂。它可能就是这样:

def sort_paths_by_date(self):
    if self.define_path_by in ('ctime', 'mtime'):
        fn = getctime if self.define_path='ctime' else getmtime
        self.paths = sorted(self.paths, key=lambda cur_path: fn(cur_path.path))