ElectricalEngine class responds to the
horsepower message. Because efficiency is calculated in percent a programmer can mistakenly initialize it with an integer instead of a float.
class ElectricalEngine attr_reader :volts, :current, :efficiency def initialize(volts, current, efficiency) @volts, @current, @efficiency = volts, current, efficiency end HP_IN_WATTS = 746 def horsepower (volts * current * efficiency) / HP_IN_WATTS end end puts ElectricalEngine.new(240, 90, .6).horsepower # correct puts ElectricalEngine.new(240, 90, 60).horsepower # buggy
How would you handle this scenario?
- Do nothing. It's the programmers responsibility to know the right datatype.
efficiency_as_floatto make it clearer.
- Write a custom
efficiencymethod to check the datatype and convert it accordingly.
efficiencytype and raise an error if it's not a float.
Solution four might look like this. Of course this conversion can happen in the
initialize method too, but I think this is cleaner.
def horsepower (volts * current * efficiency_as_float) / HP_IN_WATTS end def efficiency_as_float if efficiency.is_a?(Integer) # what if 1 is passed in instead of 1.0? efficiency / 100.to_f else efficiency end end
Solution 5 would look something like this:
def initialize(volts, current, efficiency) raise "Efficiency must be a float" unless efficiency.is_a?(Float) @volts, @current, @efficiency = volts, current, efficiency end
ElectricalEngine own the responsibility of converting incorrect datatypes?