Factory: who creates the objects

  • Lesson 5 of 32
  • 10 min
  • Beginner
  • 11 steps

The same `if` that picks a payment class, copied into three places. You will gather it into a factory and see what you gain and what you pay.

Classes to edit per new method
1
CheckoutCheckoutRefundsRefundsyour codeRefundsSubscriptionsSubscriptionscreatePaymentcreateElementcreatePaymentCardPaymentHTMLDivElementCardPaymentTransferPaymentHTMLUnknownElementTransferPaymentWalletPaymentWalletPaymentPaymentinterfacePaymentpPaymentFlowabstractPaymentFlowCardFlowCardFlowTransferFlowTransferFlowthe same if · 3 copiesIn Checkout, Refunds and Subscriptions// every class repeats thisif (method === "card") {new CardPayment().pay(total);} else {new TransferPayment().pay(total);}new method3 classes to editonly the contractOne contract, two classesinterface Payment {pay(amount: number): string;}class CardPayment implements Payment {pay(a: number) { return `card ${a}`; }}the class is chosen herecreatePaymentfunction createPayment(m: Method) {switch (m) {case "card":return new CardPayment();case "transfer":return new TransferPayment();}}createPayment("card")type: PaymentWhat Checkout writesconst p = createPayment("card");p.pay(100); // "card 100"new methodcallers do not changeThe only changetype Method = "card" | "transfer"+| "wallet";function createPayment(m: Method) {switch (m) {// card and transfer, as before+case "wallet":+return new WalletPayment();} }the switch lives hereThree wrong ideas“it needs an XFactory class”a function is enough“it removes the switch”it gathers it in one place“every new needs one”only when you pick between classescreateElement(tag)unknown tagThe browser's factorydocument.createElement("div");// → HTMLDivElementdocument.createElement("foo");// → HTMLUnknownElementthe subclass decides create()Factory Method with inheritanceabstract class PaymentFlow {abstract create(): Payment;run = (t: number) => this.create().pay(t);}class CardFlow extends PaymentFlow {create() { return new CardPayment(); }}one class only · an extra layerWith only one class−createPayment("card").pay(total);+new CardPayment().pay(total);one place decidesFactory at a glanceproblemrepeated new + iffixone function picks the classcalleronly sees Paymentnew class1 place changesskip itwith only one class
  • request
  • response

Step 1 of 11

Problem

Every class picks its payment method

A shop takes card or bank transfer. Checkout, Refunds and Subscriptions all need to charge, and each one decides on its own which class to create with an if and a new.

It works. The problem is that the same decision lives in three places, and all three classes know CardPayment and TransferPayment by name.

Step 2 of 11

Problem

A third payment method arrives

The business wants to accept a digital wallet: WalletPayment is born. Now you have to open all three classes and add another branch to the if in each one.

Forget one and that screen does not accept the wallet, and nobody notices until it fails in production. Each business class changes for a reason that is not its own.

What changed

  • WalletPayment
  • Checkout, Refunds and Subscriptions

Step 3 of 11

Concept

First, a common contract

Before moving anything, the payment classes share an interface: Payment, with one method pay(amount). CardPayment and TransferPayment implement it.

The dashed line with a hollow triangle means "implements". Thanks to that contract, the code that charges can work with "a Payment" without knowing which one.

What changed

  • interface Payment

Step 4 of 11

Solution

One function decides which class to create

We gather the decision in one place: createPayment(method). It takes "card" or "transfer" and returns the right object. That is a factory.

Now Checkout, Refunds and Subscriptions only talk to createPayment. None of them writes new CardPayment().

What changed

  • createPayment
  • 6 scattered new calls

Step 5 of 11

Technique

The caller only sees a `Payment`

Checkout asks for createPayment("card") and gets an object back. To Checkout its type is Payment: it knows it has pay() and nothing else.

Then it calls p.pay(100). If tomorrow the factory returns another class that keeps the contract, Checkout does not notice and does not have to change.

What changed

  • p: Payment

Step 6 of 11

Solution

The third method, now in one place

Back to WalletPayment. With the factory, the change is one file: you add "wallet" to the type and one branch to the switch.

The three calling classes stay the same: none of them knows WalletPayment exists. Only the factory knows it.

What changed

  • WalletPayment
  • createPayment

Step 7 of 11

Concept

The switch does not disappear

Three common wrong ideas. A factory does not need a class called XFactory: a function is enough. It does not remove the switch: it moves it to one place.

And not every new needs a factory: it only pays off when the code has to choose between several classes.

Step 8 of 11

Technique

A factory you already use

document.createElement(tag) is a browser factory. You pass "div" and get an HTMLDivElement back; you never write the class name.

If it does not know the tag, for example "foo", in an HTML document it returns an HTMLUnknownElement. The decision of which class to create lives inside the factory, not in your code.

Step 9 of 11

Concept

The book version: Factory Method

In the design patterns book (Gamma, Helm, Johnson and Vlissides, 1994), Factory Method solves the same problem with inheritance: an abstract class uses a create() method and each subclass decides which object it returns.

PaymentFlow knows how to charge with run(); CardFlow and TransferFlow only pick the product. In everyday TypeScript the factory function is more common, but you will see this shape in class-based frameworks.

Step 10 of 11

Trade-off

When a factory is too much

If only CardPayment exists and no second method is in sight, createPayment("card") is one more layer to read and to step through when debugging. new CardPayment() says the same thing, more clearly.

You also do not need one when building the object is trivial and nobody picks between classes. The factory gives you one place to change and an easy spot to return a fake object in a test; in exchange, you add an indirection.

Step 11 of 11

Summary

One place decides what to create

When several parts of the code use new and if to choose which class to create, gather that decision into a factory. Callers depend on the Payment interface, and a new class changes one place.

The switch still exists, but in one place. If there is only one class, skip it.

You will learn

  • Spot the problem: `new` and `switch` repeated in the code that uses the objects.
  • Move the decision of which class to create into a factory function.
  • Make callers depend on an interface instead of the concrete class.
  • Recognise factories you already use, such as `document.createElement`, and the book's Factory Method.
  • Know when a factory is not worth it.