2016-09-19 21 views
0

什麼是重構這個最好的方法,所以我沒有太多的重複代碼?我主要有一個方法模板,並且只有一個部分針對所有單獨的方法進行了更改。我認爲有一種重構的方式。重構,也許使用塊?或Proc?如何運行大多數的方法,但改變一小部分

步驟1需要運行

def method1 (title,field2) 
    t=title.to_s 
    field2.each do |f| 
     field_name =f.to_s 
      sub_method1(t,field_name) 
    end 
end 

步驟2需要下一個

def method2 (title,field2) 
    t=title.to_s 
    field2.each do |f| 
     field_name =f.to_s 
      sub_method2(t,field_name) 
    end 
end 

步驟3運行後

def method3 (title,field2) 
    t=title.to_s 
    field2.each do |f| 
     field_name =f.to_s 
      sub_method3(t,field_name) 
    end 
end 

步驟運行4是最後

def method4 (title,field2) 
    t=title.to_s 
    field2.each do |f| 
     field_name =f.to_s 
      sub_method4(t,field_name) 
    end 
end 

這將不起作用

def method1 (title,field2) 
    t=title.to_s 
    field2.each do |f| 
     field_name =f.to_s 
      sub_method1(t,field_name) 
      sub_method2(t,field_name) 
      sub_method3(t,field_name) 
      sub_method4(t,field_name) 
    end 
end 

回答

2

這就是塊的用途。

def method(title, field) 
    field2.each { |field| yield(title.to_s, field.to_s) } 
end 

然後,您可以打電話給你的方法是這樣的:

method(title, field) { |t, f| submethodX(t, f) } 

這樣你就可以有一個呼籲,你需要每一步,並通過在調用點塊注入更改代碼,同時留下共享代碼定義爲method

相關問題