The Single Responsibility Principle

(as understood by self)

A class should only have one reason to change

SRP is about distributing responsibilities.

 

If a class have many responsibilities, it means
it also have many reasons to change.

Conceptual code example:

"Hey Earth! How you doin'?"


class Earth

  def innovation
    #handles information about innovation
  end

  def armed_conflicts
  end

  def climate_change
  end

  def you_doin_ok_earth?
    calculate_status(self)
    return yay_or_nay
  end

  def maximize(god_stuff)
    god_stuff += SUPER_HUGE_MUCH
    yay.add(god_stuff)
  end

  def minimize (bad_stuff)
    until eliminated
      bad_stuff.be_gone!
      nay.subtract(bad_stuff)
    end
  end

end

If a class have many responsibilities, it means it also have many reasons to change.

 A class should only have one reason to change!


It should only have one responsibility

module StatusEvaluator
  # calculates and returns a status of an area
end

class Innovation
  #handles information about innovation
end

class ArmedConflicts
  #handles information about armed conflicts
end

class ClimateChange
  #handles information about climate change
end

Refactoring! 

class Earth

  def you_doin_ok_earth?
    return yay_or_nay
  end

  def maximize(god_stuff)
    god_stuff += SUPER_HUGE_MUCH
    yay.add(god_stuff)
  end

  def minimize (bad_stuff)
    until eliminated
      bad_stuff.be_gone!
      nay.subtract(bad_stuff)
    end
  end

end

No longer handles all information

No longer evaluates/calculates status

But class Earth is still responsible for minimizing the bad stuff and maximizing the good stuff!

There is only one logical conclusion.

 

As usual, we have to go ahead and make it all about you

class You

  def maximize(god_stuff)
    god_stuff += SUPER_HUGE_MUCH
    yay.add(god_stuff)
  end

  def minimize (bad_stuff)
    until eliminated
      bad_stuff.be_gone!
      nay.subtract(bad_stuff)
    end
  end

end

Our last class

I will give you the choice of doing only the maximizing of good stuff or minimizing the bad stuff...


... If you feel like it's too much responsibility.



But if you do choose only one responsibility, and fail, I reserve the right to tell you this:

Thank you!

Made with Slides.com