-1
我想通过移动公用代码到由两个可调用一个单独的方法,消除在以下两种方法的代码重复。注释表示在每种方法中具有不同实现的代码块。代码重构,以消除重复的代码在两个函数
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_h
和compute_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()
我还可以欣赏在处理这种类型的代码重构,以消除这种一般类的代码重复的问题更好的办法的建议。
这个问题不适合SO。 [代码评论](http://codereview.stackexchange.com/)可能是一个更好的地方。 – That1Guy
我投票结束这个问题作为题外话题,因为它是关于重构工作代码。 – That1Guy
这个问题对我来说似乎相当有效。在重构和代码复制中存在SO标签(出于我想的一个很好的理由)以及几个类似的SO问题,并带有相当有用的答案,例如, [本](http://stackoverflow.com/questions/28562765/deduplicating-code-in-slightly-different-functions)。 –