Code smells

The smells Fowler describes, which say a piece of code deserves rework, grouped into families (bloaters, object-orientation abusers, change preventers, dispensables, couplers), plus magic numbers; recognising them in a snippet and behind a symptom met in practice.

  • 36 cards
  • 4 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

A few cards from the deck

  • Code smell: what is it?

    Show the answer

    A hint, in a program's structure, of a deeper design problem; the program works, but it will be costly to change.

    It is not a bug: no test fails. It is a signal that invites a closer look, then a refactoring if the problem is real.

  • Which code smell does this code show?

    ```java
    class Commande {
    String etiquette(Client c) {
    return c.getPrenom() + " " + c.getNom() + "\n"
    + c.getRue() + "\n" + c.getVille();
    }
    }
    `

    • Feature envy
    • Shotgun surgery
    • Magic number
    • Divergent change
    Show the answer

    Feature envy

    The method uses no data from Commande: everything comes from Client. It would sit better in Client, which holds those fields.

  • A number written in the code whose meaning appears nowhere is a …; replace it with a named ….

    Show the answer

    A number written in the code whose meaning appears nowhere is a magic number; replace it with a named constant.

    The constant's name replaces the comment and gives a single place to change the value.

  • Long method: what is it?

    Show the answer

    A function that chains so many steps that it can no longer be read at a glance or tested piece by piece.

    A comment that announces a block ("compute the discount") is often the name of a method waiting to be extracted.

  • To add a payment method, you have to edit nine classes. What is the smell, and what should you do?

    • Divergent change: extract one class per payment method inside each affected class
    • Feature envy: move the nine classes into the same package
    • Long method: split each method into pieces of under ten lines
    • Shotgun surgery: gather into one class everything that varies with the payment method
    Show the answer

    Shotgun surgery: gather into one class everything that varies with the payment method

    A single rule change scattered over several classes is the definition of shotgun surgery. The cure moves the pieces (move method, move field) into a single class.