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
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:
- Code a method on the parameter.
- Derive its name from the original message.
- Take the original receiver as a parameter to the new method.
- 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
Even though we introduced an additional object, the print
method is now easy to read and understand.
What do you think?
Top comments (0)