Legacy Code & Wrapping Methods

Reading about working in legacy code bases. Say have a method that calculates points per monster slayed:

def get_points_for_killing(monster)
points = monster.points_for_kill + self.kill_bonus
add_to_murder_points(points)
end

and you need to add code to report the new score to a score-reporting UI. That logic needs to execute when get_points_for_killing executes, but aside from that it’s not super related to the logic in the original method. Putting the logic here will highly couple the two functions.

def get_points_for_killing(monster)
points = monster.points_for_kill + self.kill_bonus
add_to_murder_points(points)
log_point_change(@name, @points)
end

A better solution would be to create a new method that wraps the old and new logic. If you need to keep the interface the same because of calling functions, this is possible:

def get_points_for_killing(monster)
update_score_for_murder_of(monster)
log_point_change(@name, @points)
end
def update_score_for_murder_of(monster)
points = monster.points_for_kill + self.kill_bonus
add_to_murder_points(points)
end

The naming isn’t ideal, but this allows you to preserve the interface if many other methods depend on it.

Show your support

Clapping shows how much you appreciated Nicole McCabe’s story.