HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyrailsMinor

Temperature converter that seems to violate SRP

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
srptemperatureviolateseemsthatconverter

Problem

I've written this class for two purposes (I think only this fact shows that this code violates SRP): convert weight from one unit to another and to represent them accurate or not accurate. So class methods can be used for calculation and the present method rounds the value for presentation. I don't like this code - can you propose better solution?

class Temperature

  UNITS = %w(C F)
  DEFAULT_UNITS = "C"

  attr_reader :value, :units

  def initialize(value, units = DEFAULT_UNITS)
    @value = value
    @units = units.to_s
  end

  def as(units, accurate)
    return unless UNITS.include?(units.to_s)
    value = units.to_s == @units ? @value : self.class.try("#{@units.downcase}_to_#{units.downcase}", @value)
    accurate ? value : self.class.new(value, units).present
  end

  def default(accurate = false)
    as(DEFAULT_UNITS, accurate)
  end

  def present
    value.round(1)
  end

  def self.c_to_f(val)
    val * 9 / 5 + 32
  end

  def self.f_to_c(val)
    (val - 32) * 5 / 9
  end

end

Solution

class Numeric

  def fahrenheit_to_celsius
    (self - 32) * 5 / 9
  end

  def celsius_to_fahrenheit
    self * 9 / 5 + 32
  end

end

p -7.5.celsius_to_fahrenheit #=> 18.5


Classes are open for a reason in ruby. A temperature is just a number, converting it is just a method. The accuracy thing disappears by itself - an integer results in an integer, a float will give a float.

Code Snippets

class Numeric

  def fahrenheit_to_celsius
    (self - 32) * 5 / 9
  end

  def celsius_to_fahrenheit
    self * 9 / 5 + 32
  end

end

p -7.5.celsius_to_fahrenheit #=> 18.5

Context

StackExchange Code Review Q#8499, answer score: 2

Revisions (0)

No revisions yet.