Hook Methods
Hook methods are messages used during inheritance allowing sub-classes the ability to add value without creating a common anti-pattern. For instance, calling super
from a subclass is a strong indicator of a tightly coupled relationship. Changing one may require a change to the other.
Before refactor
class Stroller
...
def initialize
@wheels = DEFAULT_WHEELS
@seats = DEFAULT_SEATS
end
...
end
class DoubleStroller < Stroller
def initialize
super
@seats = 2
end
end
class JoggingStroller < Stroller
def initialize
super
@wheels = 3
end
end
The double and jogging stroller’s both call super
during initialize
to inherit the defaults. Then each subclass adds their Stroller specific information by overriding the attributes set via super. The problem here is that every future Stroller type will need to be aware of the super-classes initialize method. A developer may forget to call super and not know to explicitly set the wheels
and seats
.
The goal is to make these classes more independent from each other. We do so with introducing a hook method.
class Stroller
attr_accessor :wheels, :seats
def initialize
@wheels = DEFAULT_WHEELS
@seats = DEFAULT_SEATS
post_initialize
end
def post_initialize
end
...
end
class DoubleStroller < Stroller
def post_initialize
@seats = 2
end
end
class JoggingStroller < Stroller
def post_initialize
@wheels = 3
end
end
post_initialize
is defined and called by the parent. Stroller’s implementation of it is intentionally empty as it is not required. Any future type of stroller may or may not use post_initialize.
Did you like this article? Check out these too.
Found this useful? Have a suggestion? Get in touch at blog@hocnest.com
.