The Single Responsibility Principle: Overview
Jul 6 2016
The Single Responsibility Principle states that a class must have only one reason to change.
To demonstrate this principle, let’s take a look at the BoardGame example:
interface BoardGame {
public void move(Player, Space);
public Player determinWinner();
public boolean isOver();
public void clear();
}
Here is what each of these is intended to do.
movewill move a player to a space on the board.calculateWinnerwill calculate the winner of the game.isOveris false until there is a winner.clearwill reset the game state.
What are some reasons that would necessitate a change in a class that implemented this interface?
- The rules for what a valid move is change.
- The rules for how a player can win change.
- A new rule is introduced that enables the game to have multiple winners.
- The player configuration should remain intact when the game is cleared.
Listing some of the possible reasons that we may need to change our implementation of the BoardGame reveals something. The responsibility of the class is to enforce the rules of the game and manage the game state.
Often, the difficulty doesn’t lie in resolving the SRP violations, but rather in identifying them. The fix is usually rather simple. For our BoardGame example, we would simply introduce another abstraction which was only responsibile for the game state.
interface BoardGame {
public void move(Player, Space);
public Player determinWinnkr();
public boolean isOver();
}
interface State {
public void clear();
}
Why we should bother with SRP and techniques for identifying violations will be covered in upcoming posts.
Recent Articles
- Apprenticeship Retro Oct 14 2016
- What the hell is CORS Oct 13 2016
- Cross-site Tracing Oct 11 2016
- Learning Testing Tools First Oct 7 2016