Smells of Combining: A Class for Every Combination

When every mix of features gets its own class (YogaClassWithReminderAndWaitlist), or every missing piece gets its own null check, each new feature doubles the classes or adds a check to every screen; the smells of combining come from building mixes by copying instead of from small parts, and their cures put the parts together.

Journeyman · Software Development · OOP · Updated

By

After this lesson you can

  • Spot a smell of combining in code and name its cause
  • Choose the cure for a smell of combining: Decorator, Bridge, Composite or Null Object

Key takeaways

  • The smells of combining: a class for every combination of features, if (member != null) in every screen, and code that treats one thing and a group of things differently everywhere.
  • Their cause: mixes are built by copying (a new subclass, a new check) instead of by putting small parts together.
  • A class explosion multiplies: 3 kinds of class times 4 mixes of extras is 12 classes, and one more extra makes it 24; with small parts it's 3 kinds plus the extras.
  • The cures: Decorator or a list of extras for mixes, Bridge for two things that vary apart, Null Object for something missing, Composite for one thing and many.

Before this: the first four families, from Smells of Choosing to Smells of Size, and Prefer Composition to Inheritance in Module 1.

Summit Gym wants to offer towel service: tick a box when you book, and a towel is waiting for you. It sounds like one new option. Then you open the folder of class types and count the files.

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 for every mix

Every class can have a reminder text the evening before, a waitlist once it's full, both, or neither. The person who added reminders made a subclass for each kind; the person who added waitlists made a subclass of each of those:

Kind No extras With a reminder With a waitlist With both
Yoga YogaClass YogaClassWithReminder YogaClassWithWaitlist YogaClassWithReminderAndWaitlist
Spin SpinClass SpinClassWithReminder SpinClassWithWaitlist SpinClassWithReminderAndWaitlist
HIIT HiitClass HiitClassWithReminder HiitClassWithWaitlist HiitClassWithReminderAndWaitlist

Twelve classes, and towel service doubles every row: 24. A fourth extra makes 48. Each new option multiplies the classes, and the reminder code is copied into six of them.

  • The symptom: a class for every combination of features. Books call it a class explosion: the classes grow as a multiplication, not an addition.
  • The cause: each mix was built by copying, a new subclass for each one, instead of by putting small parts together. It's the GrilledVeggieWrapWithExtraCheeseNoOnion from Prefer Composition to Inheritance, at a gym.

The second smell: `if (member != null)` everywhere

The same family has a quieter smell. Walk-ins (people with no account, such as Zoe) can drop in on a class, so findMember gives back null (nothing) for them, and every screen has to check before it uses the member:

Dictionary<string, Member> members = new Dictionary<string, Member> { ["Maya"] = new Member("Maya", 120) };

foreach (string name in new[] { "Maya", "Zoe" })
{
    Member? member = members.GetValueOrDefault(name);
    Console.WriteLine(Greeting(member) + " | " + Points(member));
}

string Greeting(Member? member)
{
    if (member != null) { return quot;Welcome back, {member.Name}"; }
    return "Welcome, guest";
}

string Points(Member? member)
{
    if (member != null) { return quot;Points: {member.Points}"; }
    return "Points: none yet";
}

record Member(string Name, int Points);
Welcome back, Maya | Points: 120
Welcome, guest | Points: none yet
record Member(String name, int points) {}

String greeting(Member member) {
    if (member != null) { return "Welcome back, " + member.name(); }
    return "Welcome, guest";
}

String points(Member member) {
    if (member != null) { return "Points: " + member.points(); }
    return "Points: none yet";
}

void main() {
    Map<String, Member> members = Map.of("Maya", new Member("Maya", 120));
    for (String name : List.of("Maya", "Zoe")) {
        Member member = members.get(name);
        IO.println(greeting(member) + " | " + points(member));
    }
}
Welcome back, Maya | Points: 120
Welcome, guest | Points: none yet
class Member:
    def __init__(self, name, points):
        self.name = name
        self.points = points


def greeting(member):
    if member is not None:
        return f"Welcome back, {member.name}"
    return "Welcome, guest"


def points(member):
    if member is not None:
        return f"Points: {member.points}"
    return "Points: none yet"


members = {"Maya": Member("Maya", 120)}
for name in ["Maya", "Zoe"]:
    member = members.get(name)
    print(greeting(member) + " | " + points(member))
Welcome back, Maya | Points: 120
Welcome, guest | Points: none yet
function greeting(member) {
  if (member !== undefined) { return `Welcome back, ${member.name}`; }
  return "Welcome, guest";
}

function points(member) {
  if (member !== undefined) { return `Points: ${member.points}`; }
  return "Points: none yet";
}

const members = new Map([["Maya", { name: "Maya", points: 120 }]]);
for (const name of ["Maya", "Zoe"]) {
  const member = members.get(name);
  console.log(greeting(member) + " | " + points(member));
}
Welcome back, Maya | Points: 120
Welcome, guest | Points: none yet
interface Member { name: string; points: number; }

function greeting(member: Member | undefined): string {
  if (member !== undefined) { return `Welcome back, ${member.name}`; }
  return "Welcome, guest";
}

function points(member: Member | undefined): string {
  if (member !== undefined) { return `Points: ${member.points}`; }
  return "Points: none yet";
}

const members = new Map<string, Member>([["Maya", { name: "Maya", points: 120 }]]);
for (const name of ["Maya", "Zoe"]) {
  const member = members.get(name);
  console.log(greeting(member) + " | " + points(member));
}
Welcome back, Maya | Points: 120
Welcome, guest | Points: none yet

JavaScript and TypeScript use undefined here, because that's what a Map gives back for a missing key; Python has None, and C# and Java have null. It's the same smell in each.

It works today. The real system has the check in eleven places, and the new locker screen will make twelve. The day someone forgets one, the front desk stops with an error the moment a walk-in arrives.

  • The symptom: the same "is it missing?" check in front of every use.
  • The cause: "nobody" is handled by a check in every caller, instead of by a part that knows how to be nobody.

The cure: put small parts together

What would you try? For the class explosion, one big class with a true/false for every extra (hasReminder, hasWaitlist, hasTowel) stops the multiplying, but now every method checks the flags, which is a smell of choosing. For the null checks, a helper nameOrGuest(member) removes one check and leaves ten.

The cure for both is the same idea: build mixes from small parts. For the walk-in, the part is a stand-in that knows how to be nobody: a Guest that answers every question the screens ask. That's the Null Object pattern (Null Object: A Safe Stand-In for Nothing), and with it the screens have nothing to check:

Dictionary<string, IPerson> members = new Dictionary<string, IPerson> { ["Maya"] = new Member("Maya", 120) };

foreach (string name in new[] { "Maya", "Zoe" })
{
    IPerson person = members.GetValueOrDefault(name) ?? new Guest(); // nobody is a Guest, never null
    Console.WriteLine(person.Greeting() + " | " + person.PointsLine());
}

interface IPerson
{
    string Greeting();
    string PointsLine();
}

class Member(string name, int points) : IPerson
{
    public string Greeting() => quot;Welcome back, {name}";
    public string PointsLine() => quot;Points: {points}";
}

class Guest : IPerson
{
    public string Greeting() => "Welcome, guest";
    public string PointsLine() => "Points: none yet";
}
Welcome back, Maya | Points: 120
Welcome, guest | Points: none yet
interface Person {
    String greeting();
    String pointsLine();
}

record Member(String name, int points) implements Person {
    public String greeting() { return "Welcome back, " + name; }
    public String pointsLine() { return "Points: " + points; }
}

class Guest implements Person {
    public String greeting() { return "Welcome, guest"; }
    public String pointsLine() { return "Points: none yet"; }
}

void main() {
    Map<String, Person> members = Map.of("Maya", new Member("Maya", 120));
    for (String name : List.of("Maya", "Zoe")) {
        Person person = members.getOrDefault(name, new Guest()); // nobody is a Guest, never null
        IO.println(person.greeting() + " | " + person.pointsLine());
    }
}
Welcome back, Maya | Points: 120
Welcome, guest | Points: none yet
class Member:
    def __init__(self, name, points):
        self.name = name
        self.points = points

    def greeting(self):
        return f"Welcome back, {self.name}"

    def points_line(self):
        return f"Points: {self.points}"


class Guest:
    def greeting(self):
        return "Welcome, guest"

    def points_line(self):
        return "Points: none yet"


members = {"Maya": Member("Maya", 120)}
for name in ["Maya", "Zoe"]:
    person = members.get(name, Guest())  # nobody is a Guest, never None
    print(person.greeting() + " | " + person.points_line())
Welcome back, Maya | Points: 120
Welcome, guest | Points: none yet
class Member {
  constructor(name, points) { this.name = name; this.points = points; }
  greeting() { return `Welcome back, ${this.name}`; }
  pointsLine() { return `Points: ${this.points}`; }
}

class Guest {
  greeting() { return "Welcome, guest"; }
  pointsLine() { return "Points: none yet"; }
}

const members = new Map([["Maya", new Member("Maya", 120)]]);
for (const name of ["Maya", "Zoe"]) {
  const person = members.get(name) ?? new Guest(); // nobody is a Guest, never undefined
  console.log(person.greeting() + " | " + person.pointsLine());
}
Welcome back, Maya | Points: 120
Welcome, guest | Points: none yet
interface Person {
  greeting(): string;
  pointsLine(): string;
}

class Member implements Person {
  name: string;
  points: number;
  constructor(name: string, points: number) { this.name = name; this.points = points; }
  greeting(): string { return `Welcome back, ${this.name}`; }
  pointsLine(): string { return `Points: ${this.points}`; }
}

class Guest implements Person {
  greeting(): string { return "Welcome, guest"; }
  pointsLine(): string { return "Points: none yet"; }
}

const members = new Map<string, Person>([["Maya", new Member("Maya", 120)]]);
for (const name of ["Maya", "Zoe"]) {
  const person = members.get(name) ?? new Guest(); // nobody is a Guest, never undefined
  console.log(person.greeting() + " | " + person.pointsLine());
}
Welcome back, Maya | Points: 120
Welcome, guest | Points: none yet

The same two lines, and not one check. "Nobody" is decided once, where the member is looked up, and the locker screen will call person.greeting() like everyone else.

For the class explosion, the parts are the extras. A gym class has a list of extras (a reminder, a waitlist, a towel), or each extra wraps the class and adds its job, which is Decorator (Decorator: Same Phone, More Features). Either way it's 3 kinds plus 3 extras, 6 small classes instead of 24, and a fourth extra is one more.

Which cure fits?

What's being combined The cure Where you met it
A thing and its optional extras, as a class per mix Decorator, or a list of extras the thing has Decorator: Same Phone, More Features; Prefer Composition to Inheritance
Two things that vary on their own, as a class per pair Bridge: one has the other Bridge: Any Control, Any Device
Something that may be missing, checked everywhere Null Object: a stand-in that does nothing safely Null Object: A Safe Stand-In for Nothing
One thing and a group of things, told apart everywhere Composite: the group answers the same questions Composite: Boxes Inside Boxes
Extra jobs (caching, logging, a permission check, retrying) pasted around every call A wrapper: Decorator, Proxy, middleware, Retry or Circuit Breaker Three Wrappers, Three Reasons; Middleware: The Airport Checkpoints; Circuit Breaker: Stop Calling a Broken Service

The smells of combining as a symptom, cause and cure table: a class for every combination (each mix a subclass; Decorator or a list of extras); the same "is it missing?" check everywhere (Null Object); one thing and a group told apart everywhere (two shapes for one question; Composite)

Check yourself

2 questions to try on the lesson page.

So what

When the classes multiply with every option, or the same null check sits in front of every use, the mix is being built by copying. Build it from small parts instead, and the next option is one more part.

Key terms

Cheat sheets