我收到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 :(得分: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
(另外我无法抗拒“修复”你的WEST运动,对不起,如果那确实是错误的)
答案 1 :(得分: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
答案 2 :(得分: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_coordindate
和self.y_coordinate
的“重复通话”的投诉有点误报,但每条路径只会调用一次。