Template Method Pattern

The Template Method Pattern consists of a method that is used as a default value. It is then overwritten in classes that inherit or include it:

class Bicycle
  attr_reader :size, :chain, :tire_size

  def initialize(args={})
    @size = args[:size]
    @chain = args[:chain] || default_chain
    @tire_size = args[:tire_size] || default_tire_size
  end

  def default_chain # <- common default
    '10-speed'
  end
end

This way classes that inherit from Cycle can overwrite default_chain, removing the need of super calls and achieve less coupling:

</pre>
class MountainBike < Bicycle
  def default_chain
    '5-speed'
  end
end

Seen in POODR.


Avoid the need for comments

As comments are not executable, they are easily out of date. They are a form of decaying documentation.

If the code inside a method needs a comment, you probably can extract the code into a new method whose name explains what you need to clarify.

Moreover, the Single Responsibility Principle says that classes and methods should have a single responsibility so when you need comments they probably have more than one responsibility.

Therefore instead of:

def gear_inches
  # tire goes around rim twice for diameter
  ratio * rim + (tire * 2)
end

The following is clearer and needs no comment:


def gear_inches
  ratio * diameter
end

def diameter
  rim + (tire * 2)
end

Examples from POODR and here.