Composition over inheritance
Mar 6, 2022
Basically, while writing ruby codes, I avoid using inheritance because inheritance sometimes produce unnecessary tight couplings.
Example
class Vehicle
def start_engine
end def stop_engine
end
end
class Car < Vehicle
def drive
start_engine
stop_engine
end
end
In this case, Car class knows about the codes of Vehicle class. If we create objects that don’t use an engine, it will necessary to take much time to change the codes.
Solution
We should use compositions. In other words, we should define Engine object.
class Car
def initialize
@engine = Engine.new
end def drive
@engine.start
@engine.stop
end
end class Engine
def start
end def stop
end
end
In this case, Engine class was separated from Car class. Moreover, it has become easy to make new objects that don’t use an engine.