2013-08-26 31 views
1

我得到下面的錯誤從reek臭佬代碼異味複製方法調用修復

lib/actions.rb -- 5 warnings: 
    Actions#move_forward calls (self.x_coordinate + unit) twice (DuplicateMethodCall) 
    Actions#move_forward calls place((self.x_coordinate + unit), self.y_coordinate, self.direction) twice (DuplicateMethodCall) 
    Actions#move_forward calls self.direction 5 times (DuplicateMethodCall) 
    Actions#move_forward calls self.x_coordinate 4 times (DuplicateMethodCall) 
    Actions#move_forward calls self.y_coordinate 4 times (DuplicateMethodCall) 

下面就是該方法move_forward

def move_forward(unit = 1) 
     case self.direction 
     when Direction::SOUTH 
      place(self.x_coordinate, self.y_coordinate - unit, self.direction) 
     when Direction::EAST 
      place(self.x_coordinate + unit, self.y_coordinate, self.direction) 
     when Direction::NORTH 
      place(self.x_coordinate, self.y_coordinate + unit, self.direction) 
     when Direction::WEST 
      place(self.x_coordinate - unit, self.y_coordinate, self.direction) 
     else 

     end 
    end 

我想刪除所有錯誤特別是重複的方法調用。在這種情況下,修復所有警告的最佳方法是什麼?

+0

你的東西方向確實有相同的代碼,這可能是一個錯誤。 'reek'輸出看起來不符合您的代碼示例 - 您*有*使用單位,並且您粘貼的輸出引用包括'self.x_coordinate + 1'的調用。你能否檢查一下,確保兩件事情匹配(如果它們不這樣,它會讓你更難理解並提出改進建議)。 –

+0

對不起剛更新了Reek錯誤信息 –

回答

1

也許這樣?

def move_forward(unit = 1) 
    x, y, d = x_coordinate, y_coordinate, direction 
    case d 
    when Direction::SOUTH 
    place(x, y - unit, d) 
    when Direction::EAST, Direction::WEST 
    place(x + unit, y, d) 
    when Direction::NORTH 
    place(x, y + unit, d) 
    else 
    end 
end 

我找到了「重複呼叫」。self.x_coordindateself.y_coordinate投訴有點假positivey雖然,他們只是每個路徑調用一次。

+0

謝謝。是的,我認爲這有點荒謬,但只是繼續進行變革,並按預期現在沒有錯誤。 –

+2

'reek'似乎喜歡乾燥的代碼。部分原因是因爲重複檢測很容易。然而,它並不像看起來那麼荒謬 - 它不是基於被調用次數的「誤報」,而是提到你在你的方法中輸入同樣東西的頻率。反過來,這是衡量您需要花費多少精力來修復代碼,例如,您需要更改其中的任何方法的工作方式。 –

2

觸發reek報告的代碼「嗅覺」是,您正在調用一個方法來設置多個實例變量的狀態,當實踐中更少變化時(例如方向完全不變) 。 place方法設置所有內容,這使得它使用一個很小的改變過於冗長。

這可能因素的方法降低造成少報的問題:

def move_forward(unit = 1) 
    case direction 
    when Direction::SOUTH 
    move_relative(0, -unit) 
    when Direction::EAST 
    move_relative(unit, 0) 
    when Direction::WEST 
    move_relative(-unit, 0) 
    when Direction::NORTH 
    move_relative(0, unit) 
    end 
end 

def move_relative(delta_x, delta_y) 
    place(x_coordinate + delta_x, y_coordinate + delta_y, direction) 
end 

(我也無法抗拒「固定」的西進,對不起,如果這其實是錯誤的)

+0

你說得對。我其實知道情況是這樣,但只是想檢查這是否是最好的方式......非常感謝! –

2

你不似乎沒有使用面向對象的力量

那麼一種解決方案如何使用預先存在的對象的力量呢?

def move_forward(by_how_much = 1) 
    move_relative(*direction.change_in_coords(by_how_much)) 
end 

def move_relative(delta_x, delta_y) 
    place(x_coordinate + delta_x, y_coordinate + delta_y, direction) 
end 

class Direction::SOUTH 
    def self.change_in_coords(unit = 1) 
    [0, -unit] 
    end 
end