In my journey to become a better developer I’m currently concentrating my efforts on design patterns and principles.  I came across this video by Sandi Metz on how the 5 SOLID design principles apply to Ruby.  SOLID is about managing the dependencies in your application.  

  • Single Responsibility (Coding Strategies): There should never be more than one reason for a class to change.
  • Open/Closed (is a Goal): A module should be open for extension but closed for modification.
  • Liskov Substitution: Subclasses should be substitutable for their base classes.  If you make a class Foo and a subclass Fooish you should be able to replace Fooish in any place you use a Foo.  If you don’t do that, then the callers have to figure out what to do with that object and you’ve created a dependency.
  • Interface Segregation: Many client specific interfaces are better than one general purpose interface.  You care about this if you program in statically typed languages like Java or C++, does not apply to dynamic languages like Ruby.
  • Dependency Inversion (Coding Strategies): Depend upon abstractions. Do not depend upon concretions.

REFACTOR, NOT BECAUSE YOU KNOW THE ABSTRACTION, BUT BECAUSE YOU WANT TO FIND IT.  TDD is great but it’s not enough.  DRY is an excellent thing, but it’s not enough.  Design because you expect your application to succeed and the future to come.

The goal is to have strategies to achieve independence.

Red, Green, Refactor.  Ask yourself (the correct answer is yes to all of them):

  1. Is it DRY?
  2. Does it have one responsibility?
  3. Does everything in it change at the same rate?
  4. Does it depend on things that change less often than it does?  Make a picture diagram that of the objects and their likelihood to change from less on the right to more on the left.  You want objects that change all the time dependent on objects that do not change much.

If one of these questions is no you should change something in your code.

Triangle of Responsibility: Refactor, Extract, Inject.

  1. Identify the responsibility you want to remove.
  2. You make a new spec and a new class that has that code and no other code in it.
  3. You take that code and you inject it back into your original class.

You follow this pattern until you don’t have anymore responsibilities to take out.  Do the simplest thing possible; don’t guess where you’re going to end up.