Smells of Making: new Everywhere

When the code that uses an object also builds it (new scattered through business code, a constructor with nine arguments, a class that opens its own database connection), every change to how things are made touches the code that uses them, and nothing can be tested on its own; the cures give making its own home.

Journeyman · Software Development · OOP · Updated

By

After this lesson you can

  • Spot a smell of making in code and name its cause
  • Choose the cure for a smell of making: a factory, Builder, Prototype, dependency injection or an object pool

Key takeaways

  • The smells of making: new scattered through business code, a constructor with a long list of arguments, and a class that builds what it needs, such as its own database connection.
  • Their cause: the code that uses an object is also the code that decides how to make it, so making and using can't change, or be tested, apart.
  • The cures give making a home: a factory for picking a class, Builder for many parts, dependency injection for what a class needs but shouldn't build.
  • A class that builds its own database connection can't be tested without the database; handing the connection in fixes that with one constructor parameter.

Before this: Smells of Choosing, the first family, and Why Singleton Is Usually a Trap, which first handed a class the object it needs.

Pilates is in, and the owner has a question that sounds small: "Before we change anything else, can we have tests? I don't want to find out about the next $0 price from a customer." Summit Gym's booking rule is simple: each class has 12 places, then a waitlist. Testing it should take a few lines. In this code it takes a database.

A doctor's clipboard chart titled "Summit Gym's booking system", with five rows, one for each family of smells: Choosing, Making, Tangling, Size and Combining, and three columns headed Symptom, Cause and Cure

The symptom: a class that builds its own database

The class that books places is called Bookings. Its constructor makes the gym's database connection itself, so every new Bookings() connects to the real database, summit-db, wherever it runs. Here is a short test of the booking rule, run against it:

// A test of the booking rule.
Bookings bookings = new Bookings();
Console.WriteLine(bookings.Book("Maya", "Yoga"));
Console.WriteLine(bookings.Book("Sam", "Yoga"));

class GymDatabase
{
    private readonly List<string> rows = new List<string>();
    public GymDatabase() => Console.WriteLine("Connecting to summit-db...");
    public int Save(string row) { rows.Add(row); return rows.Count; }
}

class Bookings
{
    private readonly GymDatabase database = new GymDatabase(); // it builds its own
    public string Book(string member, string kind) => quot;{member}: place {database.Save(member + " in " + kind)} of 12";
}
Connecting to summit-db...
Maya: place 1 of 12
Sam: place 2 of 12
class GymDatabase {
    private final List<String> rows = new ArrayList<>();
    GymDatabase() { IO.println("Connecting to summit-db..."); }
    int save(String row) { rows.add(row); return rows.size(); }
}

class Bookings {
    private final GymDatabase database = new GymDatabase(); // it builds its own
    String book(String member, String kind) { return member + ": place " + database.save(member + " in " + kind) + " of 12"; }
}

void main() {
    // A test of the booking rule.
    Bookings bookings = new Bookings();
    IO.println(bookings.book("Maya", "Yoga"));
    IO.println(bookings.book("Sam", "Yoga"));
}
Connecting to summit-db...
Maya: place 1 of 12
Sam: place 2 of 12
class GymDatabase:
    def __init__(self):
        print("Connecting to summit-db...")
        self.rows = []

    def save(self, row):
        self.rows.append(row)
        return len(self.rows)


class Bookings:
    def __init__(self):
        self.database = GymDatabase()  # it builds its own

    def book(self, member, kind):
        return f"{member}: place {self.database.save(member + ' in ' + kind)} of 12"


# A test of the booking rule.
bookings = Bookings()
print(bookings.book("Maya", "Yoga"))
print(bookings.book("Sam", "Yoga"))
Connecting to summit-db...
Maya: place 1 of 12
Sam: place 2 of 12
class GymDatabase {
  #rows = [];
  constructor() { console.log("Connecting to summit-db..."); }
  save(row) { this.#rows.push(row); return this.#rows.length; }
}

class Bookings {
  #database = new GymDatabase(); // it builds its own
  book(member, kind) { return `${member}: place ${this.#database.save(member + " in " + kind)} of 12`; }
}

// A test of the booking rule.
const bookings = new Bookings();
console.log(bookings.book("Maya", "Yoga"));
console.log(bookings.book("Sam", "Yoga"));
Connecting to summit-db...
Maya: place 1 of 12
Sam: place 2 of 12
class GymDatabase {
  private rows: string[] = [];
  constructor() { console.log("Connecting to summit-db..."); }
  save(row: string): number { this.rows.push(row); return this.rows.length; }
}

class Bookings {
  private database = new GymDatabase(); // it builds its own
  book(member: string, kind: string): string { return `${member}: place ${this.database.save(member + " in " + kind)} of 12`; }
}

// A test of the booking rule.
const bookings = new Bookings();
console.log(bookings.book("Maya", "Yoga"));
console.log(bookings.book("Sam", "Yoga"));
Connecting to summit-db...
Maya: place 1 of 12
Sam: place 2 of 12

In this lesson the "database" only prints a line, so the code runs anywhere. The real one connects to the gym's server. So the test needs that server running, it writes Maya and Sam into the real bookings, and a test of "the 13th member goes on the waitlist" has to fill a real class first. Nobody writes that test. That's why the owner has none.

  • The symptom: a class that builds what it needs (new GymDatabase() inside Bookings). Nothing in new Bookings() says it needs a database: it's a hidden dependency, the same smell as Why Singleton Is Usually a Trap's shared settings.
  • The cause: the code that uses the database is also the code that decides how to make it. Making and using are tangled, so they can't change apart, and they can't be tested apart.

The rest of the family

The gym's code has two more smells of making, with the same cause:

  • new scattered through business code. The booking screen, the weekly schedule and the member import each say new YogaClass(...) or new SpinClass(...) themselves, picking the class with an if. A new kind of class means finding each one. (Pass 1's new Cake() in six places was this smell.)
  • A constructor with a long list of arguments. new GymClass("Yoga", "Priya", "7:00", 60, "Studio A", 12, 15, null, null). Which number is the price, and what are the two nulls? Books on refactoring call this a long parameter list. Every caller has to know the order, and a new optional part adds another argument to every call.

Each one makes the reader stop and work out how a thing is built, in the middle of code that's about using it.

The cure: hand it in

What would you try? A switch inside GymDatabase that says "if we're testing, don't connect" puts test code into the product, and every class that builds its own database needs the same switch. A test database on every developer's computer is slow to set up and still shared between tests.

The cure takes the making out of Bookings. It asks for its storage in its constructor, so the app hands it the real database and a test hands it a list in memory. That's dependency injection, the fix Why Singleton Is Usually a Trap started and Pass 4 built a whole app on:

// A test hands in a list in memory. The app hands in the real database.
Bookings bookings = new Bookings(new MemoryStore());
Console.WriteLine(bookings.Book("Maya", "Yoga"));
Console.WriteLine(bookings.Book("Sam", "Yoga"));

interface IStore
{
    int Save(string row);
}

class MemoryStore : IStore
{
    private readonly List<string> rows = new List<string>();
    public int Save(string row) { rows.Add(row); return rows.Count; }
}

class Bookings
{
    private readonly IStore store;
    public Bookings(IStore store) => this.store = store; // it's handed what it needs
    public string Book(string member, string kind) => quot;{member}: place {store.Save(member + " in " + kind)} of 12";
}
Maya: place 1 of 12
Sam: place 2 of 12
interface Store {
    int save(String row);
}

class MemoryStore implements Store {
    private final List<String> rows = new ArrayList<>();
    public int save(String row) { rows.add(row); return rows.size(); }
}

class Bookings {
    private final Store store;
    Bookings(Store store) { this.store = store; } // it's handed what it needs
    String book(String member, String kind) { return member + ": place " + store.save(member + " in " + kind) + " of 12"; }
}

void main() {
    // A test hands in a list in memory. The app hands in the real database.
    Bookings bookings = new Bookings(new MemoryStore());
    IO.println(bookings.book("Maya", "Yoga"));
    IO.println(bookings.book("Sam", "Yoga"));
}
Maya: place 1 of 12
Sam: place 2 of 12
class MemoryStore:
    def __init__(self):
        self.rows = []

    def save(self, row):
        self.rows.append(row)
        return len(self.rows)


class Bookings:
    def __init__(self, store):
        self.store = store  # it's handed what it needs

    def book(self, member, kind):
        return f"{member}: place {self.store.save(member + ' in ' + kind)} of 12"


# A test hands in a list in memory. The app hands in the real database.
bookings = Bookings(MemoryStore())
print(bookings.book("Maya", "Yoga"))
print(bookings.book("Sam", "Yoga"))
Maya: place 1 of 12
Sam: place 2 of 12
class MemoryStore {
  #rows = [];
  save(row) { this.#rows.push(row); return this.#rows.length; }
}

class Bookings {
  #store;
  constructor(store) { this.#store = store; } // it's handed what it needs
  book(member, kind) { return `${member}: place ${this.#store.save(member + " in " + kind)} of 12`; }
}

// A test hands in a list in memory. The app hands in the real database.
const bookings = new Bookings(new MemoryStore());
console.log(bookings.book("Maya", "Yoga"));
console.log(bookings.book("Sam", "Yoga"));
Maya: place 1 of 12
Sam: place 2 of 12
interface Store {
  save(row: string): number;
}

class MemoryStore implements Store {
  private rows: string[] = [];
  save(row: string): number { this.rows.push(row); return this.rows.length; }
}

class Bookings {
  private readonly store: Store;
  constructor(store: Store) { this.store = store; } // it's handed what it needs
  book(member: string, kind: string): string { return `${member}: place ${this.store.save(member + " in " + kind)} of 12`; }
}

// A test hands in a list in memory. The app hands in the real database.
const bookings = new Bookings(new MemoryStore());
console.log(bookings.book("Maya", "Yoga"));
console.log(bookings.book("Sam", "Yoga"));
Maya: place 1 of 12
Sam: place 2 of 12

The booking lines are the same, and the "Connecting" line is gone: this test never touches the gym's server. It runs in a few milliseconds, so filling a class with 12 members to test the waitlist is a three-line loop. new Bookings(store) now says out loud what it needs.

Which cure fits?

The cure for every smell of making is "give making its own home". Which home depends on what's being made:

What's being made The cure Where you met it
Something the class needs but shouldn't build (storage, a clock, settings) Dependency injection: hand it in Why Singleton Is Usually a Trap; Dependency Injection: Hand Me What I Need
One of several classes, picked by a word A factory, or a dictionary of functions Simple Factory: One Place That Says new; Factories the Modern Way
A product each subclass decides Factory Method Factory Method: Let Each Carrier Decide
A set of parts that must match each other Abstract Factory Abstract Factory: Parts That Must Match
An object with many parts, several of them optional Builder, or named arguments and records Builder: Step by Step, Then Build; Builders the Modern Way
A copy of one that's nearly right Prototype Prototype: Duplicate, Then Change
Something expensive, made again and again An object pool, or making it late Object Pool and Lazy Loading

Sometimes the cure is smaller than any of these. A GymClass built in one place, with three arguments that always come together, may need nothing at all; and a long argument list in a language with named arguments (new GymClass(kind: "Yoga", price: 15)) may only need the names written out.

The smells of making as a symptom, cause and cure table: new for a family of products in business code (every caller decides; a factory); a long list of constructor arguments (no named steps; Builder or named arguments); a class building its own connection (dependency injection)

Check yourself

2 questions to try on the lesson page.

So what

When the code that uses something is also the code that builds it, you can't change one or test one without the other. Give making its own home: a factory, a builder, or a constructor parameter, and the tests the owner asked for become a few lines each.

Key terms

Cheat sheets