POODR Ch 2 Summary


Ch 2 Summary “Designing Classes with a Single Responsibility

Intro

Deciding what belongs in a class

Creating classes that have single responsibility


class Gear 
  attr_reader :chainring, :cog 
  def initialize( chainring, cog) 
    @chainring = chainring 
    @cog = cog 
  end 
  
  def ratio 
    chainring / cog.to_f 
  end 
end 

puts Gear.new( 52, 11).ratio # -> 4.72727272727273 
puts Gear.new( 30, 27).ratio # -> 1.11111111111111

class Gear 
  attr_reader :chainring, :cog, :rim, :tire
  def initialize( chainring, cog, rim, tire) 
    @chainring = chainring 
    @cog       = cog 
    @rim       = rim
    @tire      = tire
  end 
  
  def ratio 
    chainring / cog.to_f 
  end 

  def gear_inches
    ratio * (rim + 2 * tire)
  end
end

puts Gear.new( 52, 11, 26, 1.5). gear_inches 
# -> 137.090909090909 22 23 
puts Gear.new( 52, 11, 24, 1.25). gear_inches 
# -> 125.272727272727

Writing Code that Embraces Change


# @data = [[ 622, 20], [622, 23], [559, 30], [559, 40]]

def diameters
  # 0 is rim, 1 is tire
  data.collect do |cell|
    cell[0] + (cell[1] * 2)
  end
end

# @data = [[ 622, 20], [622, 23], [559, 30], [559, 40]]
# converted to
# @data = [#<struct Wheel rim = 622, tire = 20>, ... , #<struct Wheel rim = 559, tire = 40>]

def diameters
  wheels.collect do |wheel|
    wheel.rim + (wheel * 2)
  end

  Wheel = Struct.new(:rim, :tire)
  def wheelify(data)
    data.collect do |cell|
      Wheel.new(cell[0], cell[1])
    end
  end
end

def diameters
  wheels.collect { |wheel| wheel.rim + (wheel.tire * 2) }
end

instead:


def diameters
  wheels.collect { |wheel| diameter(wheel) }
end

def diameter(wheel)
  wheel.rim + (wheel.tire * 2)
end

class Gear
  Wheel = Struct.new(:rim, :tire) do 
    ...
  end
end

class Gear
  ...
end

class Wheel
end