vendredi 26 décembre 2014

How to get rid of if statements

This is a fake implementation of the bmr calculation which I use in my Ruby on Rails app.


Since the formula is using only metric units I had to somehow convert imperial units to the metric if imperial units are set to be default for the user.


I have come up with this code.


Personally I think there is a lot of code for this kind of small problem. On the contraty, using polymorphism would be over engineering. Ways to improve this code?



require 'ostruct'
require 'delegate'

module BmrCalculator
class Calculator
def call(sex = :male, measurement_unit = :metric)
user = OpenStruct.new(sex: sex, weight: 2, height: 2, measurement_unit: measurement_unit)

if measurement_unit == :imperial #dont like it
user = ImperialToMetricDecorator.new(user)
end

BmrCalculator.new.bmr(user)
end

class BmrCalculator
def bmr(user)
if user.sex == :male
puts user.inspect
puts 1 * user.weight + 2 * user.height + 3 #this formula works only with metric units
else
puts user.inspect
puts 6 * user.weight + 3 * user.height + 5 #this formula works only with metric units
end
end
end
end

class ImperialToMetricDecorator < SimpleDelegator
def height
(super * 2.54)
end

def weight
(super / 2.2)
end
end

Calculator.new.call(:male, :metric)
end

Aucun commentaire:

Enregistrer un commentaire