2015-11-13 44 views
-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_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() 

我還可以欣賞在處理這種類型的代碼重構,以消除這種一般類的代碼重複的問題更好的辦法的建議。

+0

這個問題不適合SO。 [代碼評論](http://codereview.stackexchange.com/)可能是一個更好的地方。 – That1Guy

+1

我投票結束這個問題作爲題外話題,因爲它是關於重構工作代碼。 – That1Guy

+0

這個問題對我來說似乎相當有效。在重構和代碼複製中存在SO標籤(出於我想的一個很好的理由)以及幾個類似的SO問題,並帶有相當有用的答案,例如, [本](http://stackoverflow.com/questions/28562765/deduplicating-code-in-slightly-different-functions)。 –

回答

0

建議,我發佈了這個問題Code Review,並得到了一個偉大的,詳細的答案。

您可以閱讀答案here