POODR Ch 3 summary Part 1


POODR ch 3 Managing Dependencies

Video

YouTubeVideo of CodeNewbie meeting

Slides

Exercises

Intro

Understanding Dependencies


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

  def gear_inches
    ratio * Wheel.new( rim, tire). diameter
  end
  
  def ratio 
    chainring / cog.to_f 
  end 

  # ... 
end

class Wheel 
  attr_reader :rim, :tire 
  def initialize( rim, tire) 
    @rim = rim 
    @tire = tire 
  end 
  
  def diameter 
    rim + (tire * 2) 
  end 
  
  # ...
end

Write Loosely Coupled Code

Inject Dependencies


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

  def gear_inches
    ratio * Wheel.new(rim, tire).diameter
  end
end

class Gear
  attr_reader :chainring, :cog, :wheel
  def initialize(chainring, cog, :wheel)
    @chainring = chainring
    @cog       = cog
    @wheel     = wheel
  end

  def gear_inches
    ratio * wheel.diameter
  end
end

def initialize(chainring, cog, rim, tire)
  @chainring = chainring
  @cog       = cog
  @wheel     = Wheel.new(rim, tire)
end

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

def wheel
  @wheel || Wheel.new(rim, tire)
end

Remove Argument-Order Dependencies


def initialize(args)
  @chainring = args[:chainring]
  @cog       = args[:cog]
  @wheel     = args[:wheel]
end

...

Gear.new(
  chainring: 52,
  cog:       11,
  wheel:     Wheel.new(26, 1.5)
).gear_inches

def initialize(args)
  @chainring = args[:chainring] || 40
  @cog       = args[:cog]       || 18
  @wheel     = args[:wheel]
end

# may be an issue if there are boolean args
# will never set args[:bool] with false of nil values if, @bool = args[:bool] || true

# use fetch if args have false or nil values

def initialize(args)
  @chainring = args.fetch(:chainring, 40)
  @cog       = args.fetch(:cog, 18)
  @wheel     = args[:wheel]
end

# specifying defaults by merging a defaults hash 

def initialize( args)
  args = defaults.merge( args) 

  # merge will add default key and value pairs of `args` is missing key
  @chainring = args[:chainring] 
  @cog       = args[:cog]
  @wheel     = args[:wheel]
end 

def defaults  
  { chainring: 40, cog: 18 }
end