The SOLID principles
The five object-oriented design principles (single responsibility, open-closed, Liskov substitution, interface segregation, dependency inversion): stating them, recognising a violation and fixing it.
- 28 cards
- 5 topics
- Free
The outline, topic by topic
Each topic is weighted the way the exam weighs it.
- Concepts
- Questions
- Sort and link
- Scenarios
- Understand
A few cards from the deck
SOLID: what is it?
Show the answer
Acronym for five object-oriented design principles aimed at code that is easy to change: single responsibility, open-closed, Liskov substitution, interface segregation, dependency inversion.
They are design principles, not language rules: the compiler does not check them; review and the cost of changes reveal them.
We want to add a
Triangleshape. Which principle does this method violate?
```java
double aire(Forme f) {
switch (f.type) {
case CERCLE: return Math.PI * f.rayon * f.rayon;
case CARRE: return f.cote * f.cote;
default: throw new IllegalArgumentException();
}
}`- Open-closed
- Single responsibility
- Interface segregation
- Liskov substitution
Show the answer
Open-closed
Each new shape forces
aireto be reopened and modified. The fix: aFormeinterface with anaire()method that each class implements.The open-closed principle asks a module to be … to extension and … to modification.
Show the answer
The open-closed principle asks a module to be open to extension and closed to modification.
Open: behaviours can be added to it. Closed: there is no need to rewrite its code to do so.
Single responsibility: what is it?
Show the answer
The principle that a class should have only one reason to change: it answers to a single actor or a single concern.
An
Invoiceclass that computes, prints and writes to a database changes when the calculation rule, the print format or the database evolves: three reasons, so three classes.A
Machineinterface declaresimprimer(),scanner()andfaxer(). The simple printer has to implement everything and throwsUnsupportedOperationExceptioninscanner()andfaxer(). Which fix?- Split into
Imprimante,ScannerandFax: each class implements only its own - Leave the bodies empty instead of throwing an exception
- Make the simple printer extend a full-featured one
- Add an
estSupporte()method toMachineto test before each call
Show the answer
Split into
Imprimante,ScannerandFax: each class implements only its ownEmpty bodies hide the violation without solving it, and inheritance adds another. An
estSupporte()method forces every client to know about methods that do not concern it: only splitting removes the needless dependency.- Split into