Refactoring: Refactorings/Hide Delegate
Jump to navigation
Jump to search
A client calls a method on a delegate rather than using the public interface on the "server" class: The client knows too much about the inner workings of a delegate class.
Mechanics
- For each method on the delegate, create a simple delegating method on the server
- Adjust the client to call the server method
- Test after adjusting each method
- If no client needs to access the delegate anymore, remove the server's accessor for the delegate.
- Test
Example
Before
class Person
attr_accessor :manager
# ...
end
class Department
attr_reader :manager
def initialize(manager)
@manager = manager
end
end
# client code
manager = john.department.manager
After
class Person
extend Forwardable
def_delegator :@department, :manager
attr_accessor :manager
def manager
@department.manager
end
end
class Department
attr_reader :manager
def initialize(manager)
@manager = manager
end
end
# client code
manager = john.manager