# Factories the Modern Way: A Dictionary of Functions

A factory's if chain still grows by one line a month and gets edited by everyone; a dictionary from each product's name to a function that makes it lets a new product be added in one line, from anywhere, without touching the factory.

Apprentice · OOP · Updated November 17, 2026

By Gregor Dzierzon

## After this lesson you can

- Write a factory as a dictionary from a name to a function that makes the object
- Choose between a factory's if chain and a dictionary of functions, and say why

## Key takeaways

- A dictionary can hold functions as its values, so it can map a product's name to a function that makes that product.
- Adding a product is then one new entry, made from outside the factory; the code that looks products up never changes.
- An unknown name is one clear check in one place.
- A short, fixed if chain is still fine; reach for the dictionary when the list grows, changes often, or is filled from outside.

**Before this:** *Simple Factory: One Place That Says new*, and passing a function as a value (a lambda, or an arrow function).

The simple factory fixed the forgotten pie. Every product is now made in one place, `makeProduct`. But look at what happens next: every month someone opens `makeProduct` and adds a line. In December the owner wants a holiday cookie tin for three weeks, then gone. The function everyone depends on is the one being edited most. This lesson keeps the same factory and changes how it's written: as a *dictionary of functions*.

## The symptom: the factory keeps changing

`makeProduct` from the last lesson is a list of `if` lines that grows forever. That's a milder smell than before, since it's in one place now. But it's still the code that changes most, and every change means opening it, editing it and hoping nothing else broke. A seasonal product means adding a line in December and remembering to take it out in January.

## What would you try?

**Keep adding `if` lines.** Fine for four products. With twenty, `makeProduct` is a page long, and two people adding products in the same week get in each other's way.

**Turn the `if` lines into a `switch`.** It reads a little better, but it's the same list in the same function, edited the same way.

What would really help is if adding a product didn't mean editing `makeProduct` at all.

## The fix: a dictionary of functions

A bakery's recipe box works this way. Each product has an index card, filed under its name. The baker looks up "pie", pulls the card and follows it. A new product is one new card filed in the box. Nobody rewrites the box.

![A wooden recipe box with index cards filed under tabs labeled Cake, Cupcakes and Cookies, and a hand filing a new card labeled Pie](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/48ca08f3056042a2a119c1c223e4cef2.webp)

In code, the box is a **dictionary** (a map) whose keys are the products' names and whose values are **functions that make the product**. A function that takes or holds other functions like this is a *higher-order function*; here it's the dictionary that holds them:

![The makers dictionary as a two-column table: the names cake, cupcakes, cookies and pie, each pointing to what it makes (a Cake, a Cupcakes box, a Cookie box, a Pie). The pie row is highlighted: "added with one line"](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/5be95539adec4efa9039c85e964e2b8b.webp)

```csharp
Dictionary<string, Func<IProduct>> makers = new Dictionary<string, Func<IProduct>>
{
    ["cake"] = () => new Cake(),
    ["cupcakes"] = () => new Cupcakes(),
    ["cookies"] = () => new CookieBox()
};

// Next month's product: one line, and MakeProduct doesn't change.
makers["pie"] = () => new Pie();

Console.WriteLine("On the menu: " + string.Join(", ", makers.Keys));
List<IProduct> order = new List<IProduct> { MakeProduct("pie"), MakeProduct("cake") };
Console.WriteLine("Order: " + string.Join(", ", order.Select(product => product.Name)));
try
{
    MakeProduct("bagel");
}
catch (ArgumentException error)
{
    Console.WriteLine(error.Message);
}

IProduct MakeProduct(string kind)
{
    if (makers.TryGetValue(kind, out Func<IProduct>? maker))
    {
        return maker();
    }
    throw new ArgumentException("No such product: " + kind);
}

interface IProduct
{
    string Name { get; }
    int Price { get; }
}

class Cake : IProduct { public string Name => "Cake"; public int Price => 30; }
class Cupcakes : IProduct { public string Name => "Cupcakes"; public int Price => 12; }
class CookieBox : IProduct { public string Name => "Cookie box"; public int Price => 8; }
class Pie : IProduct { public string Name => "Pie"; public int Price => 15; }
```

```text
On the menu: cake, cupcakes, cookies, pie
Order: Pie, Cake
No such product: bagel
```

```java
interface Product {
    String name();
    int price();
}

class Cake implements Product { public String name() { return "Cake"; } public int price() { return 30; } }
class Cupcakes implements Product { public String name() { return "Cupcakes"; } public int price() { return 12; } }
class CookieBox implements Product { public String name() { return "Cookie box"; } public int price() { return 8; } }
class Pie implements Product { public String name() { return "Pie"; } public int price() { return 15; } }

Map<String, Supplier<Product>> makers = new LinkedHashMap<>();

Product makeProduct(String kind) {
    Supplier<Product> maker = makers.get(kind);
    if (maker == null) {
        throw new IllegalArgumentException("No such product: " + kind);
    }
    return maker.get();
}

void main() {
    makers.put("cake", () -> new Cake());
    makers.put("cupcakes", () -> new Cupcakes());
    makers.put("cookies", () -> new CookieBox());

    // Next month's product: one line, and makeProduct doesn't change.
    makers.put("pie", () -> new Pie());

    IO.println("On the menu: " + String.join(", ", makers.keySet()));
    List<Product> order = List.of(makeProduct("pie"), makeProduct("cake"));
    IO.println("Order: " + String.join(", ", order.stream().map(Product::name).toList()));
    try {
        makeProduct("bagel");
    } catch (IllegalArgumentException error) {
        IO.println(error.getMessage());
    }
}
```

```text
On the menu: cake, cupcakes, cookies, pie
Order: Pie, Cake
No such product: bagel
```

```python
class Cake:
    name = "Cake"
    price = 30


class Cupcakes:
    name = "Cupcakes"
    price = 12


class CookieBox:
    name = "Cookie box"
    price = 8


class Pie:
    name = "Pie"
    price = 15


makers = {"cake": Cake, "cupcakes": Cupcakes, "cookies": CookieBox}

# Next month's product: one line, and make_product doesn't change.
makers["pie"] = Pie


def make_product(kind):
    maker = makers.get(kind)
    if maker is None:
        raise ValueError(f"No such product: {kind}")
    return maker()


print("On the menu: " + ", ".join(makers))
order = [make_product("pie"), make_product("cake")]
print("Order: " + ", ".join(product.name for product in order))
try:
    make_product("bagel")
except ValueError as error:
    print(error)
```

```text
On the menu: cake, cupcakes, cookies, pie
Order: Pie, Cake
No such product: bagel
```

```javascript
class Cake { name = "Cake"; price = 30; }
class Cupcakes { name = "Cupcakes"; price = 12; }
class CookieBox { name = "Cookie box"; price = 8; }
class Pie { name = "Pie"; price = 15; }

const makers = new Map([
  ["cake", () => new Cake()],
  ["cupcakes", () => new Cupcakes()],
  ["cookies", () => new CookieBox()],
]);

// Next month's product: one line, and makeProduct doesn't change.
makers.set("pie", () => new Pie());

function makeProduct(kind) {
  const maker = makers.get(kind);
  if (maker === undefined) {
    throw new Error(`No such product: ${kind}`);
  }
  return maker();
}

console.log("On the menu: " + [...makers.keys()].join(", "));
const order = [makeProduct("pie"), makeProduct("cake")];
console.log("Order: " + order.map((product) => product.name).join(", "));
try {
  makeProduct("bagel");
} catch (error) {
  console.log(error.message);
}
```

```text
On the menu: cake, cupcakes, cookies, pie
Order: Pie, Cake
No such product: bagel
```

```typescript
interface Product {
  name: string;
  price: number;
}

class Cake implements Product { name = "Cake"; price = 30; }
class Cupcakes implements Product { name = "Cupcakes"; price = 12; }
class CookieBox implements Product { name = "Cookie box"; price = 8; }
class Pie implements Product { name = "Pie"; price = 15; }

const makers = new Map<string, () => Product>([
  ["cake", () => new Cake()],
  ["cupcakes", () => new Cupcakes()],
  ["cookies", () => new CookieBox()],
]);

// Next month's product: one line, and makeProduct doesn't change.
makers.set("pie", () => new Pie());

function makeProduct(kind: string): Product {
  const maker = makers.get(kind);
  if (maker === undefined) {
    throw new Error(`No such product: ${kind}`);
  }
  return maker();
}

console.log("On the menu: " + [...makers.keys()].join(", "));
const order = [makeProduct("pie"), makeProduct("cake")];
console.log("Order: " + order.map((product) => product.name).join(", "));
try {
  makeProduct("bagel");
} catch (error) {
  console.log((error as Error).message);
}
```

```text
On the menu: cake, cupcakes, cookies, pie
Order: Pie, Cake
No such product: bagel
```

`makeProduct` is now four lines, and it will still be four lines when the bakery sells forty things. Adding pies didn't touch it. The holiday cookie tin is one `makers` line in December and one removal in January. The price board and the counter tablet can even show `makers`' names as the menu, so the list of products lives in exactly one place.

**Where the languages differ.** In Python a class is already a function that makes an object (`Cake()` calls it), so the dictionary can hold the classes themselves. Java keeps the order you added things only in a `LinkedHashMap`; a plain `HashMap` may list them in any order. The others keep the order they were added in.

## How it got its name

This is still the **simple factory**, written the way modern code often writes it: the decision "which class for this name?" lives in data instead of in `if` lines. Teams call the dictionary a *registry*, and adding an entry *registering* a product. It follows an old piece of advice, the **open/closed principle**: code should be *open* to new behavior (a new product) and *closed* to edits (nobody opens `makeProduct`).

## Choosing between the two

| | The `if` chain | The dictionary of functions |
|---|---|---|
| **Reads best when** | there are a few kinds, fixed for good | there are many kinds, or they change often |
| **Adding a kind** | edit the factory | add one entry, from anywhere |
| **An unknown name** | the last line of the chain | one check after the lookup |
| **Watch out for** | a chain that grows every month | an entry added in a place nobody can find; keep them together |

## Where you've already used it

- ASP.NET Core's `builder.Services.AddScoped<IUserDao>(_ => new UserDao(connectionString))` registers a function the framework calls whenever something needs an `IUserDao`.
- A command-line tool that maps each command word (`"add"`, `"list"`, `"remove"`) to the function that handles it uses the same dictionary.
- JavaScript code that keeps an object of handlers, `{ save: saveDraft, publish: publishPost }`, and calls `handlers[action]()` is this idea too.

## When not to use it

- **When the list is short and fixed.** Three kinds that never change read more clearly as three `if` lines than as a dictionary the reader has to go and find.
- **When each kind needs different arguments to be made.** A dictionary of functions works best when every product is made the same way. If a cake needs a flavor and a pie needs a filling, a plain function per product may be clearer.

**How often you'll meet it:** now and then in app code, and every day inside frameworks (our estimate).

## Check yourself

2 questions to try on the lesson page.

## So what

A dictionary can hold functions, and that turns a growing `if` chain into data that's added to, not edited. When the list of kinds keeps changing, the code that uses it can stop changing.

## Key terms

- [Simple Factory](https://www.ask-codey.com/glossary/simple-factory)
- [Higher-Order Function](https://www.ask-codey.com/glossary/higher-order-function-software-development)
- [Open/Closed Principle](https://www.ask-codey.com/glossary/open-closed-principle)

## Cheat sheets

- [Factories the Modern Way: A Dictionary of Functions](https://www.ask-codey.com/cheat-sheets/dp-factories-modern-cheat-sheet)

Source: https://www.ask-codey.com/lessons/dp-factories-modern
