Sunday, November 17, 2013

SOLID Principles

The SOLID principles can lead to less technical debt, easier maintenance, and an ever increasing delivery of software on time.  Bob Martin can be thanked for the SOLID principles.

S - Single Responsibility Principle
O - Open/Close Principle
L - Liskov Substitution Principle
I - Interface Segregation Principle
D - Dependency Inversion Principle

What IS a principle?  Think of these as rules or concepts that, when followed, produce desirable results in your software.  It's a means to an end, so don't spend all of your time working on SOLID principles while you throw the book of common sense out the window.  There is a balance of each of these principles that, when that balance is met, you achieve software maintenance nirvana.  Be wary...  These principles are more like guidelines, not laws.  You won't be thrown in jail nor will your hair catch fire if it's not followed perfectly, because there are tradeoffs down the road and each of those tradeoffs have their own value.

So let's get started on 'S'.

Single Responsibility Principle  (SRP)

The "Responsibility" is applied to a class.  A class should have only one responsibility.  There are two types of responsibilities: knowing and doing.  As Robert Martin (Uncle Bob) puts it, a class having only one responsibility is like saying that a class should have only one reason for change.

So...  What's a reason for change?  This is where things get a little less obvious in my opinion.  I can argue with myself all day on why even a single method could have more than one reason for change.  I can even argue that if a method has more than one line of code, there's more than one possible "reason" for change.  This isn't the essence of this "guideline", er, I mean "principle".  The essence is in the idea of grouping your methods with other methods that serve a single "role".  Typical roles could be business model related or persistence related or interface related.  A role's interest could change, changing the requirements of the application, but since that role's interest is decoupled from other roles' interests, there's a minimal amount of coding and testing required to implement the requirements for this role's changing interests.

Let's be clear that a role may not be entirely obvious when you "File->New" your project or your new code file, but do remember that we should be refactoring like little boy scouts: Always leave things better than how you found them.

For a brief example, we could take a quick look at ORM's.  The ORM patterns help you separate the responsibility of persisting your data from representing your data (a doing from a knowing).     

1 comment:

  1. FWIW, I find that a good rule of thumb for a function is that it should fit on your monitor vertically. If it gets longer than that then chances are good it's doing too much. Lovely post Bryan!

    ReplyDelete