代码重构以消除两个函数中的代码重复

时间:2015-11-13 15:34:19

标签: python refactoring code-duplication code-design

我希望通过将公共代码移动到可由两者调用的单独方法来消除以下两种方法中的代码重复。注释表示在每种方法中具有不同实现的代码块。

def compute_totals_h(self, size, bad_codes):
    with open(self._in_file_path, self._FILE_READ_MODE) as f:
        # initialize reader
        reader = csv.reader(f)
        field_names = reader.next()
        for i, code in enumerate(field_names):
            code = code.strip(string.punctuation).upper()
            field_names[i] = code       
        for code in field_names:
            if (len(code) <= size) and (code not in bad_codes):
                self._totals[code] = 0

        for row in reader:
            # get totals
            for i, val in enumerate(row):
                code = field_names[i]
                if (code in self._totals):
                    self._totals[code] += string_utils.to_int(val)

    self._write_totals()

def compute_totals_v(self, code_field, est_field):
    with open(self._in_file_path, self._FILE_READ_MODE) as f:
        # initialize reader
        reader = csv.DictReader(f)

        for row in reader:
            # get totals
            code = row[code_field].strip(string.punctuation).upper()
            est = string_utils.to_int(row[est_field])
            if code in self._totals:
                self._totals[code] += est
            else:
                self._totals[code] = est

    self._write_totals()

我正在考虑一个解决方案,它有一个可以从compute_totals_hcompute_totals_v调用的通用抽象方法,每个方法都传递函数来处理它的实现。在正确传递每个实现的参数时,我无法弄清楚如何执行此操作。它看起来像是:

def compute_totals(self, initialize_reader, get_totals):
    with open(self._in_file_path, self._FILE_READ_MODE) as f:
        reader = initialize_reader(f)

        for row in reader:
            get_totals(row)

        self._write_totals()

我也很欣赏有关更好地处理此类代码重构的建议,以消除这类通用的代码重复问题。

1 个答案:

答案 0 :(得分:0)

据我所知,我在Code Review上发布了这个问题,并在那里得到了一个很好的答案。

您可以阅读答案here