All posts

· 7 min read

Path · Ch. 14

Factory: stop scattering `new` across your code

The Factory pattern puts the decision of which object to create in one place. We use the corner store's notifications: first the code with a repeated `switch`, then the version with a factory.

On this page
  1. The problem: new and switch everywhere
  2. First step: a shared interface
  3. The factory: one place where the decision lives
  4. Simple factory and Factory Method
  5. When NOT to use a factory
  6. Mini-exercise: add WhatsApp
  7. Suggested solution
  8. What you learned
  9. Stuck?

The corner store already tells customers when their order is ready. At first it was email only. Then someone asked for SMS, and after that WhatsApp. Every time you add a channel, you have to remember every place in the program where one gets picked, and one of them always slips through.

That problem has a name and a well-known solution: the Factory pattern. Today we start from the code that hurts, because a pattern only makes sense once you have felt the problem it solves.

The problem: new and switch everywhere

This program sends two kinds of messages. The notifier classes share nothing yet:

SendReady("email", "Ana");
SendOnTheWay("sms", "Luis");

static void SendReady(string channel, string customer)
{
    switch (channel)
    {
        case "email":
            new EmailNotifier().Send(customer, "Your order is ready.");
            break;
        case "sms":
            new SmsNotifier().Send(customer, "Your order is ready.");
            break;
        default:
            throw new ArgumentException($"Unknown channel: {channel}");
    }
}

static void SendOnTheWay(string channel, string customer)
{
    switch (channel)
    {
        case "email":
            new EmailNotifier().Send(customer, "Your order is on the way.");
            break;
        case "sms":
            new SmsNotifier().Send(customer, "Your order is on the way.");
            break;
        default:
            throw new ArgumentException($"Unknown channel: {channel}");
    }
}

class EmailNotifier
{
    public void Send(string customer, string message)
    {
        Console.WriteLine($"[Email] To {customer}: {message}");
    }
}

class SmsNotifier
{
    public void Send(string customer, string message)
    {
        Console.WriteLine($"[Sms] To {customer}: {message}");
    }
}
[Email] To Ana: Your order is ready.
[Sms] To Luis: Your order is on the way.

It works. The trouble shows up when the business grows. To add WhatsApp you have to:

  1. Write the new class.
  2. Add a case in SendReady.
  3. Add another case in SendOnTheWay.
  4. Remember that a third place exists, which you haven’t written yet, and that it needs its own case too.

The knowledge of “which channels exist and how they are created” is spread across the program. Worse, every function that sends a message knows too much: it knows the names of all the concrete classes. If SmsNotifier needs an API key in its constructor tomorrow, you will have to fix every new.

First step: a shared interface

You already know interfaces from chapter 10. If all notifiers promise the same thing, the code that uses them does not need to know which is which:

interface INotifier
{
    void Send(string customer, string message);
}

Each class declares that it keeps the promise with : INotifier. That alone does not fix the switch, but it prepares the ground: now there is one type that means “something that knows how to send a message”.

The factory: one place where the decision lives

A factory is a method whose only job is to create the right object. The caller says what it wants and gets back something that satisfies the interface, without knowing which concrete class came out:

INotifier notifier = NotifierFactory.Create("sms");
notifier.Send("Luis", "Your order is on the way.");

interface INotifier
{
    void Send(string customer, string message);
}

class EmailNotifier : INotifier
{
    public void Send(string customer, string message)
    {
        Console.WriteLine($"[Email] To {customer}: {message}");
    }
}

class SmsNotifier : INotifier
{
    public void Send(string customer, string message)
    {
        Console.WriteLine($"[Sms] To {customer}: {message}");
    }
}

static class NotifierFactory
{
    public static INotifier Create(string channel)
    {
        switch (channel)
        {
            case "email":
                return new EmailNotifier();
            case "sms":
                return new SmsNotifier();
            default:
                throw new ArgumentException($"Unknown channel: {channel}");
        }
    }
}
[Sms] To Luis: Your order is on the way.

A static class is a class you never instantiate: it only groups methods that you call through the class name, like NotifierFactory.Create(...). For a small factory it is the simplest option.

Look at what happened. The switch did not disappear, it moved. The difference is that it now exists once. The functions that send messages shrink to this:

INotifier notifier = NotifierFactory.Create(channel);
notifier.Send(customer, "Your order is ready.");

They have no case, and they mention neither EmailNotifier nor SmsNotifier. To add WhatsApp you write the class and one line in the factory. Nothing else changes. And if a class constructor needs new data, you fix a single new.

Simple factory and Factory Method

In the classic patterns book (the “Gang of Four” one we mentioned in the previous chapter), Factory Method is something slightly different: a method in a base class that subclasses override to decide what to create. What we just wrote is usually called a simple factory. It is not a pattern from the book, but it is the form that will serve you when you start, and most of the time someone says “factory” in a work conversation, this is what they mean. What both share is the same idea: separate who uses the object from who decides which one to create.

When NOT to use a factory

There is plenty of code where a factory is too much:

  • There is only one class. If you always create a Product, new Product("Coffee", 3.50m) is perfect. A ProductFactory that does the same adds one more file to read.
  • The new appears in a single place. A factory helps when the decision repeats. If the switch lives once, it is already centralized.
  • There is no interface or anything in common. A factory that returns object forces casts everywhere. If the objects cannot be used the same way, you probably do not need a factory.
  • Factories of factories. If you catch yourself writing NotifierFactoryFactory, stop. That is the kind of over-engineering we talked about in chapter 11.

My rule: I wait until I see the same switch or the same chain of new a second time. The first time I keep it simple. By the second I know the decision repeats and the factory pays for itself.

Mini-exercise: add WhatsApp

Start from the factory program above and do three things:

  1. Create WhatsAppNotifier, which prints [WhatsApp] To {customer}: {message}.
  2. Make the factory accept the channel in any casing. For that, channel.ToLower() returns the text in lowercase.
  3. In the main program, send “Your order is ready.” to Ana through "WhatsApp" and to Luis through "SMS". Then try to create the channel "pigeon" inside a try/catch (chapter 7) and print the exception message.

Suggested solution

INotifier byWhatsApp = NotifierFactory.Create("WhatsApp");
byWhatsApp.Send("Ana", "Your order is ready.");

INotifier bySms = NotifierFactory.Create("SMS");
bySms.Send("Luis", "Your order is ready.");

try
{
    NotifierFactory.Create("pigeon");
}
catch (ArgumentException ex)
{
    Console.WriteLine(ex.Message);
}

interface INotifier
{
    void Send(string customer, string message);
}

class EmailNotifier : INotifier
{
    public void Send(string customer, string message)
    {
        Console.WriteLine($"[Email] To {customer}: {message}");
    }
}

class SmsNotifier : INotifier
{
    public void Send(string customer, string message)
    {
        Console.WriteLine($"[Sms] To {customer}: {message}");
    }
}

class WhatsAppNotifier : INotifier
{
    public void Send(string customer, string message)
    {
        Console.WriteLine($"[WhatsApp] To {customer}: {message}");
    }
}

static class NotifierFactory
{
    public static INotifier Create(string channel)
    {
        switch (channel.ToLower())
        {
            case "email":
                return new EmailNotifier();
            case "sms":
                return new SmsNotifier();
            case "whatsapp":
                return new WhatsAppNotifier();
            default:
                throw new ArgumentException($"Unknown channel: {channel}");
        }
    }
}
[WhatsApp] To Ana: Your order is ready.
[Sms] To Luis: Your order is ready.
Unknown channel: pigeon

Look at how little you had to touch: the new class and one case. The code that sends messages never found out WhatsApp exists, and that is the benefit of the pattern.

What you learned

  • When the decision of which new to run repeats in several places, every change forces you to hunt for all of them.
  • A shared interface (INotifier) lets the rest of the code avoid depending on concrete classes.
  • A simple factory is a method that takes what you want and returns an object that satisfies the interface. The switch is still there, but in one place.
  • Do not use a factory with a single class, a single new, or objects that have nothing in common.

In the next chapter we cover Strategy: what to do when a giant if or switch decides how something is calculated, like the corner store’s discounts.

Stuck?

If your factory does not compile or you do not see why the switch is still there, DM me on Instagram or ask in the Discord community. Paste your code and the error you get, and we will look at it together.