POODR


Single responsability
&
Managing dependencies

Design


  • Not perfect code
  • Allow to design later
  • Reduce cost of change

Easy to change


  • No unexpected side effects
  • Cost of change proportional to its benefits
  • Reusability (in new & unexpected context)

Without Single Reponsability


  • Can't select only the behavior U want
  • Difficult to reuse
  • Leads to code duplication
  • Leads to dependencies

Single Responsability


Example with bicycles


class Gear



More logic



Single responsability


  • "Mr Gear, what is your ratio ?" - OK
  • "Mr Gear, what is your tire ?" - NOK

Easy to change


  • Hide instance variables
  • Hide data structure
  • Extract responsabilities from methods
  • Isolate responsabilities

Hide instance variables


Don't


Do

Hide instance variables


if @cog needs to change


Hide Data Structure





  • Need to know the internal structure of @data
  • If @data structure change, everything breaks

Hide Data Structure



  • 'diameter' method doesn't know the structure of 'wheels'
  • This knowledge is encapsulated in a single place
  • More tolerant to change

Extract responsabilities from Methods



  • Iterates over the wheels
  • And caculater the diameter for each wheel
  • Why not have a 'diameter' method ?


Remember the Gear class ?



  • This method has more than one responsability


Remember the Gear class ?


  • 'gear_inches' belongs in the Gear class
  • 'diameter' does not


This refactoring allows to :
  • Clarify the class and its responsibilities
  • Avoid needs of comment
  • Reusability

Isolate Responsabilities




  • 'Wheel' struct clean the 'Gear' class
  • Delay the creation of a real 'Wheel' class

The Real Wheel



The Real Wheel


  • This code is not perfect
  • It achieves a higher standard
  • It isĀ good enough

Managing dependencies




Next time ;)

Poodr - single responsability

By Thomas Petrachi

Poodr - single responsability

  • 1,216