DEV Community 👩‍💻👨‍💻

Akshay Khot
Akshay Khot

Posted on

Reverse Method Refactoring

Here's a handy refactoring technique I learned today while reading Kent Beck's Smalltalk Best Practice Patterns.

But first, what's the problem? Sometimes, you have an unreadable method because you are calling different methods on different objects. You cannot extract a method because it's already small (but unreadable) and does one thing.

Here's a simplified example.

class Point
  def print(stream)
    x.print(stream)
    stream.print(', ')
    y.print(stream)
  end
end
Enter fullscreen mode Exit fullscreen mode

Though the example is not complicated, it takes a while to understand what's going on and who's calling whom.

We can solve the problem by making sure that all messages go through a single object. Kent provides the following approach for this refactoring:

  1. Code a method on the parameter.
  2. Derive its name from the original message.
  3. Take the original receiver as a parameter to the new method.
  4. Implement the method by sending the original message to the original receiver.
class Stream
  def print(obj)
    obj.print(self)
  end
end

class Point
  def print(stream)
    stream.print(x)
    stream.print(', ')
    stream.print(y)
  end
end
Enter fullscreen mode Exit fullscreen mode

Even though we introduced an additional object, the print method is now easy to read and understand.

What do you think?

Top comments (0)

🌚 Life is too short to browse without dark mode