Single Responsibility Principle
A class or method should only have a single reason to change.
Rationale
Having only a single reason to change helps reduce coupling. Having to make a change to a responsibility may break or inhibit the functionality of another responsibility.
Examples
Example that breaks the rule
In this example the class both calculates the total score, but also the amount of points given for a event in a game.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
class ScoreBoard {
private int score = 0;
public int getScore() { return score; }
public int increaseScore(String event) {
score += calculateScore(event);
}
public int calculateScore(String event) {
switch(event) {
case "HitCentreRing" : return 10;
case "HitOuterRing" : return 1;
default: new Random().nextInt(9) + 1 ;
}
}
ScoreBoard scoreBoard = new ScoreBoard();
scoreBoard.increaseScore("HitCentreRing");
scoreBoard.increaseScore("HitOuterRing");
scoreBoard.getScore();
|
Example that doesn’t break the rule
In this example ScoringEvent has been introduced to calculate the points for the event. this could be taken further to allow the scoreboard to accept an interface allowing varying implementations of a ScoringEvent.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
class ScoringEvent {
public ScoringEvent(String type) {
this.type = type;
}
public int score() {
switch(this.type) {
case "HitCentreRing" : return 10;
case "HitOuterRing" : return 1;
default: new Random().nextInt(9) + 1 ;
}
}
class ScoreBoard {
private int score = 0;
public int getScore() { return score; }
public int increaseScore(ScoringEvent event) {
score += event.score();
}
}
ScoreBoard scoreBoard = new ScoreBoard();
scoreBoard.increaseScore(new ScoringEvent("HitCentreRing"));
scoreBoard.increaseScore(new ScoringEvent("HitOuterRing"));
scoreBoard.getScore();
|
References