Sonntag, 9. Februar 2014

Return early! ... a Ruby guard pattern example.

The guard pattern means to improve readability, maintainability and stability. And it is a cheap refeactoring technique.
A simple original Ruby code:
class Person
  # weight in gram and height in centimeter
  attr_accessor :weight, :height

  def bmi
    if weight.nil? or height.nil?
      0
    else
      height_in_meter = height * 100
      (weight * 1000) / (height_in_meter * height_in_meter)
    end
  end
end
can be refactored to:
class Person
  # weight in gram and height in centimeter
  attr_accessor :weight, :height

  def bmi
    return 0 if weight.nil? or height.nil?
    height_in_meter = height * 100
    (weight * 1000) / (height_in_meter * height_in_meter)
  end
end
The improvement by just simply returning the result when it is known is obvious.

Supported by Ruby 2.1.0