Thursday, February 17, 2011

What is SOLID?

I saw this pop up earlier in a list of interview questions and decided that it might be a great way to start seeding my blog -- by answering interview questions.  So, what is SOLID?

SOLID, as it pertains to object-oriented design, is a mnemonic acronym that breaks down into even more acronyms.  It's a tree of acronyms, which might be a fun thing to mention during interviews.

While you could go to Wikipedia entry on SOLID, I'll capture the salient points here as well.

S is for Single Responsibility Principle (SRP).  SRP is a design principle that effectively states that any class should have 1 reason to exist, or 1 reason to change.  When a class does more than one thing, the chances that it will change increase.

O is the Open/Close Principle (OCP).  OCP, in long form, says that classes should be open for extension and closed for modification.  Put another way, only make changes to fix errors.

L is for Liskov Substitution Principle (LSP).  LSP, sometimes known as design by contract or substitutability, simply encourages one to design to an interface, not an implementation.  When discussing substitutability, it's important to understand contravariance and covariance.  The common heuristics here include:

  • Contravariance of method arguments in the subtype
  • Covariance of return types in the subtype

I, the Interface Segregation Principle (ISP), compels one to use multiple simple interfaces rather than fewer complex interfaces.  The net effect is measured by cohesion where high cohesion implies that objects are loosely coupled, low cohesion the opposite.

D for Dependency Inversion Principle (DIP).  Create dependencies on ideal types, not on concrete types.  When talking about dependency inversion, two major points pop up:

  • High level modules should not depend on low level modules.  Both should depend on abstractions.
  • Abstractions should not depend on details, details should depend on abstractions.

For more on DIP, check out these patterns: Adapter, Plugin, Service Locator and Dependency Injection.

No comments: