루비로 배우는 객체지향 디자인 - 2장 단일 책임 원칙을 따르는 클래스 디자인하기

By: Jun Heo
Posted: September 19, 2021

• 하나의 책임만 수행하는 메서드와 클래스로 분리한다.

Example1: Gear class code

Gear class 에서 Wheel class를 분리한다. 먼저 gear_inches method의 연산에서 diameter method를 분리한 후 Wheel class를 만든다.

# chainring(앞 톱니수), cog(뒷 톱니수), rim(바퀴테 지름), tire(타이어 높이)
# ratio(기어비)
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 + (tire * 2))
  end
end

puts Gear.new(52, 11).ratio
puts Gear.new(30, 27).ratio

Example 2: Gear and Wheel class

# chainring(앞 톱니수), cog(뒷 톱니수), rim(바퀴테 지름), tire(타이어 높이)
# ratio(기어비)
class Gear
  attr_reader :chainring, :cog, :wheel
  def initialize(chainring, cog, wheel=nil)
    @chainring = chainring
    @cog = cog
    @wheel = wheel
  end

  def ratio
    chainring / cog.to_f
  end

  def gear_inches
    ratio * wheel.diameter
  end
end

class Wheel
  attr_reader :rim, :tire

  def initialize(rim, tire)
    @rim = rim
    @tire = tire
  end

  def diameter  
    rim + (tire * 2)
  end

  def circumference
    diameter * Math::PI
  end
end

@wheel = Wheel.new(26, 1.5)
puts @wheel.circumference
puts Gear.new(52, 11, @wheel).ratio
puts Gear.new(52, 11, @wheel).gear_inches
puts Gear.new(30, 27).ratio