SOLID Software Principles in Practice
Introduction
The acronym SOLID refers to five software design principles which have been developed to make code more readable, flexible and maintainable. Since being introduced by Robert C. Martin (aka Uncle Bob) back in 2000, they have been embraced by software developers world-wide.
The concepts of SOLID are as follows:
- Single responsibility principle
- “a class should have only a single responsibility (i.e. only changes to one part of the software’s specification should be able to affect the specification of the class).”
- Open/closed principle
- “software entities … should be open for extension, but closed for modification.”
- Liskov substitution principle
- “objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.” See also design by contract.”
- Interface segregation principle
- “many client-specific interfaces are better than one general-purpose interface.”
- Dependency inversion principle
- one should “depend upon abstractions, [not] concretions.”
There are many articles out there which describe the SOLID principles, but I think that many of them can be fairly brief or way too formal. In this set of posts I describe them in a far less formal manner, using example code and class diagrams from a fictional and simple Space Invaders type game design. Note that the design I have used throughout this post has been contrived to help explain each SOLID principle and is not necessarily how I would structure classes for a game in real life.
- Single Responsibility Principle (SRP)
- Open/Closed Principle (OCP)
- Liskov Substitution Principle
- Interface Segregation Principle (ISP)
- Dependency Inversion Principle (DIP)
On a final note, I just want to stress one thing, and that is to only make use of the SOLID principles when it makes sense! When used incorrectly, they can add unnecessary complexity to your code and make it less readable. For example, don’t use SOLID if you are writing a throw away prototype, or a piece of code that is trivial to change should the need arise.