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.

  1. Concepts
  2. Questions
  3. Sort and link
  4. Scenarios
  5. 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 Triangle shape. 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 aire to be reopened and modified. The fix: a Forme interface with an aire() 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 Invoice class 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 Machine interface declares imprimer(), scanner() and faxer(). The simple printer has to implement everything and throws UnsupportedOperationException in scanner() and faxer(). Which fix?

    • Split into Imprimante, Scanner and Fax: 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 to Machine to test before each call
    Show the answer

    Split into Imprimante, Scanner and Fax: each class implements only its own

    Empty 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.