The delegation design pattern describes an approach in OOP. Thus an object (delegator) passes a task to its associated helper object (delegate). Essentially an object requests another object to execute a task or it; a task is delegated.
That makes sense especially for decoupling responsibilities. Apart from that, delegation combined with composition is a powerful alternative to class inheritance.
For illustration reasons, imagine cars. Each car contains an engine:
class Engine def start puts "puff puff" end end class Car def initialize engine @engine = engine end end
When initializing a car it gets an engine and can move:
engine = Engine.new car = Car.new engine car.engine.start # => "puff puff"
However that way it is quite awkward.
Whoever wants to use the Car object, also has to know the Engine API as well. Similarly, I am absolutely not interested in how the engine works, when I just want to drive the car. I naturally assume the engine somehow starts automatically, when I start driving.
That is why the call rather should look like:
car.start # => "puff puff"
For this the car has to delegate the task to the Engine and the Car class has to look like:
class Car def initialize engine @engine = engine end def start @engine.start end end
Delegation not only mean to pass the responsibility for the business logic implemention. It also contributes to object decoupling by dealing with the relation between the objects internally (inside an object), instead of spreading the relation all over the application.
Besides changing the Engine API causes no application code maintenance trouble any more.
Along with delegating the logic, it sometimes makes sense to adjust the message (method) name for clarity reasons:
class Car def initialize engine @engine = engine end def move @engine.start end end