SOLID PHP: The Single Responsibility Principle

The first of the SOLID principles is unfortunately violated quite often even though it is easy to understand why you want to maintain a separation of concerns. It is similar to the SQL injection vulnerabilities that show up on StackOverflow and other places even though the internet is flooded with warnings about how to avoid being pwnd by the easily escapable beast.

In the example repository, I give the example of a basketball player that is both a coach and a player. While there are several examples in NBA history of successful player coaches, none have won coach of the year and only two have won championships as player-coaches.

Since we are pursuing excellence, why would split our focus by being both a player and a coach? There are several examples of player-coaches going back to focusing on their playing career since it is very difficult to be great as both.

In warfare, it is a maxim to divide your enemies forces so that they cannot focus their strength. Thus it is so with player-coaches. They are at best a jack of all trades that has to deal with the politics of leading a team as well as the dynamics of winning basketball games on the court.

We should keep these principles in mind when we are designing objects and their interrelations. How does it make sense to have a player object that is also a coach object? As you can see from the example repository, the responsibilities that the PlayerCoach object takes on are contradictory in nature and would be confusing when utilized in code.

To sum up, don’t have your objects be a PlayerCoach. Have multiple objects: player and coach that can leverage their individual capabilities to their fullest.

To see if you are violating this principle, try extracting all of the interfaces that you can for a given class and see if they make sense to be utilized in the same class. Just make sure that your interfaces (or contracts) conform to the Interface Segregation Principle (ISP).

Written on April 4, 2015