Strategy: When the Rule Needs a Class of Its Own
Pass 1 handed the weekly deal in as one function; a carrier's rate needs its own numbers and answers more than one question, so the function grows into a class per carrier, each holding its numbers and keeping one promise, and the quote screen asks whichever carrier it's handed: the Strategy pattern in its classic form.
Journeyman · OOP · Updated
After this lesson you can
- Grow a rule that needs its own data and several methods from a function into a strategy class
- Spot the smells that point to Strategy: a switch on a name in more than one method, with each case's numbers mixed in
Key takeaways
- The smell: a switch on the carrier's name in more than one method, with each carrier's numbers mixed into the cases.
- A function is enough when a rule is one question with no data of its own. A carrier needs its own numbers and answers several questions.
- The fix: one class per carrier, each holding its own numbers and keeping one promise; the quote screen asks whichever carrier it's handed.
- A new carrier is a new class, and a carrier's new numbers are a change to one object, not to the quote screen.
- Records, dataclasses and object literals write the same strategy in a few lines.
Before this: Weekly Deals: Pass the Rule In (Pass 1), where a deal was handed into checkout as a function, and interfaces (a promise any class can keep).
In Pass 1, one function was enough. The bakery's weekly deal answered one question, "how much comes off this order?", and handing it into checkout as a function kept checkout from changing every week. Now Lakeside Parcel works with three carriers, and the quote screen shows what each one charges. A carrier looks like a rule too. But try handing one in as a function, and it doesn't fit: a carrier has numbers of its own and answers more than one question. By the end of this lesson the function has grown into something with a name you've already met, a strategy, now as a class.
The symptom: the carriers are tangled into the quote screen
Each carrier prices a package by its zone, 1 to 4: QuickShip charges $5 plus $2 a zone; EcoFreight charges $7 flat, plus a 10% fuel charge; SameDay charges $15 flat, and only goes to zones 1 and 2. Prices are kept in cents, so the fuel charge never rounds wrong. Here is the quote screen for zones 2 and 3:
foreach (int zone in new List<int> { 2, 3 })
{
foreach (string carrier in new List<string> { "QuickShip", "EcoFreight", "SameDay" })
{
Console.WriteLine(Quote(carrier, zone));
}
}
string Quote(string carrier, int zone)
{
if (!CanDeliver(carrier, zone)) { return quot;{carrier}: doesn't deliver to zone {zone}"; }
int cents = 0;
if (carrier == "QuickShip") { cents = 500 + 200 * zone; }
else if (carrier == "EcoFreight") { cents = 700 + 700 * 10 / 100; }
else if (carrier == "SameDay") { cents = 1500; }
return quot;{carrier} to zone {zone}: {Dollars(cents)}";
}
bool CanDeliver(string carrier, int zone)
{
if (carrier == "SameDay") { return zone <= 2; }
return true;
}
string Dollars(int cents) => quot;${cents / 100}.{cents % 100:D2}";
QuickShip to zone 2: $9.00
EcoFreight to zone 2: $7.70
SameDay to zone 2: $15.00
QuickShip to zone 3: $11.00
EcoFreight to zone 3: $7.70
SameDay: doesn't deliver to zone 3
String dollars(int cents) { return " quot; + cents / 100 + "." + String.format("%02d", cents % 100); }
boolean canDeliver(String carrier, int zone) {
if (carrier.equals("SameDay")) { return zone <= 2; }
return true;
}
String quote(String carrier, int zone) {
if (!canDeliver(carrier, zone)) { return carrier + ": doesn't deliver to zone " + zone; }
int cents = 0;
if (carrier.equals("QuickShip")) { cents = 500 + 200 * zone; }
else if (carrier.equals("EcoFreight")) { cents = 700 + 700 * 10 / 100; }
else if (carrier.equals("SameDay")) { cents = 1500; }
return carrier + " to zone " + zone + ": " + dollars(cents);
}
void main() {
for (int zone : List.of(2, 3)) {
for (String carrier : List.of("QuickShip", "EcoFreight", "SameDay")) {
IO.println(quote(carrier, zone));
}
}
}
QuickShip to zone 2: $9.00
EcoFreight to zone 2: $7.70
SameDay to zone 2: $15.00
QuickShip to zone 3: $11.00
EcoFreight to zone 3: $7.70
SameDay: doesn't deliver to zone 3
def dollars(cents):
return f"${cents // 100}.{cents % 100:02d}"
def can_deliver(carrier, zone):
if carrier == "SameDay":
return zone <= 2
return True
def quote(carrier, zone):
if not can_deliver(carrier, zone):
return f"{carrier}: doesn't deliver to zone {zone}"
cents = 0
if carrier == "QuickShip":
cents = 500 + 200 * zone
elif carrier == "EcoFreight":
cents = 700 + 700 * 10 // 100
elif carrier == "SameDay":
cents = 1500
return f"{carrier} to zone {zone}: {dollars(cents)}"
for zone in [2, 3]:
for carrier in ["QuickShip", "EcoFreight", "SameDay"]:
print(quote(carrier, zone))
QuickShip to zone 2: $9.00
EcoFreight to zone 2: $7.70
SameDay to zone 2: $15.00
QuickShip to zone 3: $11.00
EcoFreight to zone 3: $7.70
SameDay: doesn't deliver to zone 3
function dollars(cents) {
return `${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, "0")}`;
}
function canDeliver(carrier, zone) {
if (carrier === "SameDay") { return zone <= 2; }
return true;
}
function quote(carrier, zone) {
if (!canDeliver(carrier, zone)) { return `${carrier}: doesn't deliver to zone ${zone}`; }
let cents = 0;
if (carrier === "QuickShip") { cents = 500 + 200 * zone; }
else if (carrier === "EcoFreight") { cents = 700 + Math.floor(700 * 10 / 100); }
else if (carrier === "SameDay") { cents = 1500; }
return `${carrier} to zone ${zone}: ${dollars(cents)}`;
}
for (const zone of [2, 3]) {
for (const carrier of ["QuickShip", "EcoFreight", "SameDay"]) {
console.log(quote(carrier, zone));
}
}
QuickShip to zone 2: $9.00
EcoFreight to zone 2: $7.70
SameDay to zone 2: $15.00
QuickShip to zone 3: $11.00
EcoFreight to zone 3: $7.70
SameDay: doesn't deliver to zone 3
function dollars(cents: number): string {
return `${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, "0")}`;
}
function canDeliver(carrier: string, zone: number): boolean {
if (carrier === "SameDay") { return zone <= 2; }
return true;
}
function quote(carrier: string, zone: number): string {
if (!canDeliver(carrier, zone)) { return `${carrier}: doesn't deliver to zone ${zone}`; }
let cents = 0;
if (carrier === "QuickShip") { cents = 500 + 200 * zone; }
else if (carrier === "EcoFreight") { cents = 700 + Math.floor(700 * 10 / 100); }
else if (carrier === "SameDay") { cents = 1500; }
return `${carrier} to zone ${zone}: ${dollars(cents)}`;
}
for (const zone of [2, 3]) {
for (const carrier of ["QuickShip", "EcoFreight", "SameDay"]) {
console.log(quote(carrier, zone));
}
}
QuickShip to zone 2: $9.00
EcoFreight to zone 2: $7.70
SameDay to zone 2: $15.00
QuickShip to zone 3: $11.00
EcoFreight to zone 3: $7.70
SameDay: doesn't deliver to zone 3
It works. Now look at what's coming: EcoFreight's fuel charge goes to 12% next month, a fourth carrier is in talks, and the dispatch screen wants to ask "who can deliver to zone 3?" too.
- The symptom: a switch on the carrier's name in more than one method (
QuoteandCanDeliver), with each carrier's numbers (500, 200, 10%, zone 2) buried in the cases. - The cause: everything about one carrier, its numbers and its rules, is spread across the code that uses carriers. To change EcoFreight's fuel charge you edit the quote screen; to add a carrier you edit both methods and hope you found them all.
What would you try?
Pass 1's fix: hand the rate in as a function. Quote(zone, rate) with rate a function from zone to cents. That covers one question. But SameDay also has to answer "do you deliver to zone 3?", so each carrier becomes two functions, plus its name for the screen, three things that have to travel together and stay matched. And EcoFreight's 10% is buried inside a lambda, where next month's change is an edit to the lambda, not a new number.
A dictionary from each carrier's name to its rate function. That's Pass 1's dictionary of functions. It removes one switch, but CanDeliver keeps its own, and the numbers are still inside the functions.
Another else if in each method for the fourth carrier. It works for one more carrier, and every carrier after it is the same hunt through the same two methods.
The weekly deal was one question with no data of its own. A carrier is a bundle: its numbers, and the answers to several questions that use them. What we want is to keep that bundle together, in one place, and have the quote screen ask it.

The everyday version: a camera's lenses
In Pass 1, a camera's mode dial picked one rule for the shutter button. A camera with interchangeable lenses goes a step further. Each lens carries its own numbers, how far it zooms and how much light it lets in, and the camera asks the lens it's wearing several questions: how far can you zoom, how close can you focus? The camera body never changes. A new lens is a new lens, not a new camera.

The fix: one class per carrier
Make each carrier an object that holds its own numbers and keeps one promise: I can tell you my name, whether I deliver to a zone, and my rate for it. The quote screen is handed a list of carriers and asks each one; it never mentions a name or a number:

How it got its name
It's the same pattern as Pass 1's weekly deal: one way of doing a job, kept separate so it can be swapped for another, is a strategy, and code that's handed one follows the Strategy pattern. The 1994 book wrote every strategy as a class, and this is why: once a rule has data of its own and more than one method, a class is what keeps them together. The function in Pass 1 was a strategy with nothing to hold; this one has numbers.
The classic version
List<ICarrier> carriers = new List<ICarrier> { new QuickShip(500, 200), new EcoFreight(700, 10), new SameDay(1500, 2) };
foreach (int zone in new List<int> { 2, 3 })
{
foreach (ICarrier carrier in carriers)
{
Console.WriteLine(Quote(carrier, zone));
}
}
// The quote screen never changes again: it asks whichever carrier it's handed.
string Quote(ICarrier carrier, int zone)
{
if (!carrier.CanDeliver(zone)) { return quot;{carrier.Name}: doesn't deliver to zone {zone}"; }
return quot;{carrier.Name} to zone {zone}: {Dollars(carrier.Rate(zone))}";
}
string Dollars(int cents) => quot;${cents / 100}.{cents % 100:D2}";
// One carrier's rules: its name, where it delivers, and what it charges, in cents.
interface ICarrier
{
string Name { get; }
bool CanDeliver(int zone);
int Rate(int zone);
}
class QuickShip : ICarrier
{
private readonly int baseCents;
private readonly int perZoneCents;
public QuickShip(int baseCents, int perZoneCents) { this.baseCents = baseCents; this.perZoneCents = perZoneCents; }
public string Name => "QuickShip";
public bool CanDeliver(int zone) => true;
public int Rate(int zone) => baseCents + perZoneCents * zone;
}
class EcoFreight : ICarrier
{
private readonly int flatCents;
private readonly int fuelPercent;
public EcoFreight(int flatCents, int fuelPercent) { this.flatCents = flatCents; this.fuelPercent = fuelPercent; }
public string Name => "EcoFreight";
public bool CanDeliver(int zone) => true;
public int Rate(int zone) => flatCents + flatCents * fuelPercent / 100;
}
class SameDay : ICarrier
{
private readonly int flatCents;
private readonly int farthestZone;
public SameDay(int flatCents, int farthestZone) { this.flatCents = flatCents; this.farthestZone = farthestZone; }
public string Name => "SameDay";
public bool CanDeliver(int zone) => zone <= farthestZone;
public int Rate(int zone) => flatCents;
}
QuickShip to zone 2: $9.00
EcoFreight to zone 2: $7.70
SameDay to zone 2: $15.00
QuickShip to zone 3: $11.00
EcoFreight to zone 3: $7.70
SameDay: doesn't deliver to zone 3
// One carrier's rules: its name, where it delivers, and what it charges, in cents.
interface Carrier {
String name();
boolean canDeliver(int zone);
int rate(int zone);
}
class QuickShip implements Carrier {
int baseCents;
int perZoneCents;
QuickShip(int baseCents, int perZoneCents) { this.baseCents = baseCents; this.perZoneCents = perZoneCents; }
public String name() { return "QuickShip"; }
public boolean canDeliver(int zone) { return true; }
public int rate(int zone) { return baseCents + perZoneCents * zone; }
}
class EcoFreight implements Carrier {
int flatCents;
int fuelPercent;
EcoFreight(int flatCents, int fuelPercent) { this.flatCents = flatCents; this.fuelPercent = fuelPercent; }
public String name() { return "EcoFreight"; }
public boolean canDeliver(int zone) { return true; }
public int rate(int zone) { return flatCents + flatCents * fuelPercent / 100; }
}
class SameDay implements Carrier {
int flatCents;
int farthestZone;
SameDay(int flatCents, int farthestZone) { this.flatCents = flatCents; this.farthestZone = farthestZone; }
public String name() { return "SameDay"; }
public boolean canDeliver(int zone) { return zone <= farthestZone; }
public int rate(int zone) { return flatCents; }
}
String dollars(int cents) { return " quot; + cents / 100 + "." + String.format("%02d", cents % 100); }
// The quote screen never changes again: it asks whichever carrier it's handed.
String quote(Carrier carrier, int zone) {
if (!carrier.canDeliver(zone)) { return carrier.name() + ": doesn't deliver to zone " + zone; }
return carrier.name() + " to zone " + zone + ": " + dollars(carrier.rate(zone));
}
void main() {
List<Carrier> carriers = List.of(new QuickShip(500, 200), new EcoFreight(700, 10), new SameDay(1500, 2));
for (int zone : List.of(2, 3)) {
for (Carrier carrier : carriers) {
IO.println(quote(carrier, zone));
}
}
}
QuickShip to zone 2: $9.00
EcoFreight to zone 2: $7.70
SameDay to zone 2: $15.00
QuickShip to zone 3: $11.00
EcoFreight to zone 3: $7.70
SameDay: doesn't deliver to zone 3
class QuickShip:
"""One carrier's rules: its name, where it delivers, and what it charges, in cents."""
name = "QuickShip"
def __init__(self, base_cents, per_zone_cents):
self.base_cents = base_cents
self.per_zone_cents = per_zone_cents
def can_deliver(self, zone):
return True
def rate(self, zone):
return self.base_cents + self.per_zone_cents * zone
class EcoFreight:
name = "EcoFreight"
def __init__(self, flat_cents, fuel_percent):
self.flat_cents = flat_cents
self.fuel_percent = fuel_percent
def can_deliver(self, zone):
return True
def rate(self, zone):
return self.flat_cents + self.flat_cents * self.fuel_percent // 100
class SameDay:
name = "SameDay"
def __init__(self, flat_cents, farthest_zone):
self.flat_cents = flat_cents
self.farthest_zone = farthest_zone
def can_deliver(self, zone):
return zone <= self.farthest_zone
def rate(self, zone):
return self.flat_cents
def dollars(cents):
return f"${cents // 100}.{cents % 100:02d}"
def quote(carrier, zone):
"""The quote screen never changes again: it asks whichever carrier it's handed."""
if not carrier.can_deliver(zone):
return f"{carrier.name}: doesn't deliver to zone {zone}"
return f"{carrier.name} to zone {zone}: {dollars(carrier.rate(zone))}"
carriers = [QuickShip(500, 200), EcoFreight(700, 10), SameDay(1500, 2)]
for zone in [2, 3]:
for carrier in carriers:
print(quote(carrier, zone))
QuickShip to zone 2: $9.00
EcoFreight to zone 2: $7.70
SameDay to zone 2: $15.00
QuickShip to zone 3: $11.00
EcoFreight to zone 3: $7.70
SameDay: doesn't deliver to zone 3
// One carrier's rules: its name, where it delivers, and what it charges, in cents.
class QuickShip {
name = "QuickShip";
constructor(baseCents, perZoneCents) {
this.baseCents = baseCents;
this.perZoneCents = perZoneCents;
}
canDeliver(zone) { return true; }
rate(zone) { return this.baseCents + this.perZoneCents * zone; }
}
class EcoFreight {
name = "EcoFreight";
constructor(flatCents, fuelPercent) {
this.flatCents = flatCents;
this.fuelPercent = fuelPercent;
}
canDeliver(zone) { return true; }
rate(zone) { return this.flatCents + Math.floor(this.flatCents * this.fuelPercent / 100); }
}
class SameDay {
name = "SameDay";
constructor(flatCents, farthestZone) {
this.flatCents = flatCents;
this.farthestZone = farthestZone;
}
canDeliver(zone) { return zone <= this.farthestZone; }
rate(zone) { return this.flatCents; }
}
function dollars(cents) {
return `${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, "0")}`;
}
// The quote screen never changes again: it asks whichever carrier it's handed.
function quote(carrier, zone) {
if (!carrier.canDeliver(zone)) { return `${carrier.name}: doesn't deliver to zone ${zone}`; }
return `${carrier.name} to zone ${zone}: ${dollars(carrier.rate(zone))}`;
}
const carriers = [new QuickShip(500, 200), new EcoFreight(700, 10), new SameDay(1500, 2)];
for (const zone of [2, 3]) {
for (const carrier of carriers) {
console.log(quote(carrier, zone));
}
}
QuickShip to zone 2: $9.00
EcoFreight to zone 2: $7.70
SameDay to zone 2: $15.00
QuickShip to zone 3: $11.00
EcoFreight to zone 3: $7.70
SameDay: doesn't deliver to zone 3
// One carrier's rules: its name, where it delivers, and what it charges, in cents.
interface Carrier {
name: string;
canDeliver(zone: number): boolean;
rate(zone: number): number;
}
class QuickShip implements Carrier {
name = "QuickShip";
baseCents: number;
perZoneCents: number;
constructor(baseCents: number, perZoneCents: number) {
this.baseCents = baseCents;
this.perZoneCents = perZoneCents;
}
canDeliver(zone: number): boolean { return true; }
rate(zone: number): number { return this.baseCents + this.perZoneCents * zone; }
}
class EcoFreight implements Carrier {
name = "EcoFreight";
flatCents: number;
fuelPercent: number;
constructor(flatCents: number, fuelPercent: number) {
this.flatCents = flatCents;
this.fuelPercent = fuelPercent;
}
canDeliver(zone: number): boolean { return true; }
rate(zone: number): number { return this.flatCents + Math.floor(this.flatCents * this.fuelPercent / 100); }
}
class SameDay implements Carrier {
name = "SameDay";
flatCents: number;
farthestZone: number;
constructor(flatCents: number, farthestZone: number) {
this.flatCents = flatCents;
this.farthestZone = farthestZone;
}
canDeliver(zone: number): boolean { return zone <= this.farthestZone; }
rate(zone: number): number { return this.flatCents; }
}
function dollars(cents: number): string {
return `${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, "0")}`;
}
// The quote screen never changes again: it asks whichever carrier it's handed.
function quote(carrier: Carrier, zone: number): string {
if (!carrier.canDeliver(zone)) { return `${carrier.name}: doesn't deliver to zone ${zone}`; }
return `${carrier.name} to zone ${zone}: ${dollars(carrier.rate(zone))}`;
}
const carriers: Carrier[] = [new QuickShip(500, 200), new EcoFreight(700, 10), new SameDay(1500, 2)];
for (const zone of [2, 3]) {
for (const carrier of carriers) {
console.log(quote(carrier, zone));
}
}
QuickShip to zone 2: $9.00
EcoFreight to zone 2: $7.70
SameDay to zone 2: $15.00
QuickShip to zone 3: $11.00
EcoFreight to zone 3: $7.70
SameDay: doesn't deliver to zone 3
Same six lines, and the quote screen is two lines that mention no carrier. Each carrier's numbers are passed in when it's made, so next month's fuel charge is new EcoFreight(700, 12), a change to one object, and the quote screen never hears about it. A fourth carrier is a fourth class. The dispatch screen can ask the same objects "who can deliver to zone 3?" without a switch of its own.
Where the languages differ. C#, Java and TypeScript write the promise as an interface (ICarrier, Carrier). Python and JavaScript don't need one: any object with a name, can_deliver and rate will do, which is called duck typing. The fuel charge is whole cents in every language: / on two ints in C# and Java, // in Python, Math.floor in JavaScript and TypeScript.
Here is one quote for zone 3, as a sequence diagram. The screen asks each carrier the same two questions; only the answers differ:

The modern version: the strategy as a record
A strategy that's mostly numbers plus a few short methods is what records, dataclasses and object literals are for. The promise stays; each carrier shrinks to a few lines:
List<ICarrier> carriers = new List<ICarrier> { new QuickShip(500, 200), new EcoFreight(700, 10), new SameDay(1500, 2) };
foreach (int zone in new List<int> { 2, 3 })
{
foreach (ICarrier carrier in carriers)
{
Console.WriteLine(Quote(carrier, zone));
}
}
string Quote(ICarrier carrier, int zone)
{
if (!carrier.CanDeliver(zone)) { return quot;{carrier.Name}: doesn't deliver to zone {zone}"; }
return quot;{carrier.Name} to zone {zone}: {Dollars(carrier.Rate(zone))}";
}
string Dollars(int cents) => quot;${cents / 100}.{cents % 100:D2}";
interface ICarrier
{
string Name { get; }
bool CanDeliver(int zone);
int Rate(int zone);
}
// A record holds the carrier's numbers; its methods use them.
record QuickShip(int BaseCents, int PerZoneCents) : ICarrier
{
public string Name => "QuickShip";
public bool CanDeliver(int zone) => true;
public int Rate(int zone) => BaseCents + PerZoneCents * zone;
}
record EcoFreight(int FlatCents, int FuelPercent) : ICarrier
{
public string Name => "EcoFreight";
public bool CanDeliver(int zone) => true;
public int Rate(int zone) => FlatCents + FlatCents * FuelPercent / 100;
}
record SameDay(int FlatCents, int FarthestZone) : ICarrier
{
public string Name => "SameDay";
public bool CanDeliver(int zone) => zone <= FarthestZone;
public int Rate(int zone) => FlatCents;
}
QuickShip to zone 2: $9.00
EcoFreight to zone 2: $7.70
SameDay to zone 2: $15.00
QuickShip to zone 3: $11.00
EcoFreight to zone 3: $7.70
SameDay: doesn't deliver to zone 3
interface Carrier {
String name();
boolean canDeliver(int zone);
int rate(int zone);
}
// A record holds the carrier's numbers; its methods use them.
record QuickShip(int baseCents, int perZoneCents) implements Carrier {
public String name() { return "QuickShip"; }
public boolean canDeliver(int zone) { return true; }
public int rate(int zone) { return baseCents + perZoneCents * zone; }
}
record EcoFreight(int flatCents, int fuelPercent) implements Carrier {
public String name() { return "EcoFreight"; }
public boolean canDeliver(int zone) { return true; }
public int rate(int zone) { return flatCents + flatCents * fuelPercent / 100; }
}
record SameDay(int flatCents, int farthestZone) implements Carrier {
public String name() { return "SameDay"; }
public boolean canDeliver(int zone) { return zone <= farthestZone; }
public int rate(int zone) { return flatCents; }
}
String dollars(int cents) { return " quot; + cents / 100 + "." + String.format("%02d", cents % 100); }
String quote(Carrier carrier, int zone) {
if (!carrier.canDeliver(zone)) { return carrier.name() + ": doesn't deliver to zone " + zone; }
return carrier.name() + " to zone " + zone + ": " + dollars(carrier.rate(zone));
}
void main() {
List<Carrier> carriers = List.of(new QuickShip(500, 200), new EcoFreight(700, 10), new SameDay(1500, 2));
for (int zone : List.of(2, 3)) {
for (Carrier carrier : carriers) {
IO.println(quote(carrier, zone));
}
}
}
QuickShip to zone 2: $9.00
EcoFreight to zone 2: $7.70
SameDay to zone 2: $15.00
QuickShip to zone 3: $11.00
EcoFreight to zone 3: $7.70
SameDay: doesn't deliver to zone 3
from dataclasses import dataclass
# A dataclass holds the carrier's numbers; its methods use them.
@dataclass(frozen=True)
class QuickShip:
base_cents: int
per_zone_cents: int
name = "QuickShip"
def can_deliver(self, zone):
return True
def rate(self, zone):
return self.base_cents + self.per_zone_cents * zone
@dataclass(frozen=True)
class EcoFreight:
flat_cents: int
fuel_percent: int
name = "EcoFreight"
def can_deliver(self, zone):
return True
def rate(self, zone):
return self.flat_cents + self.flat_cents * self.fuel_percent // 100
@dataclass(frozen=True)
class SameDay:
flat_cents: int
farthest_zone: int
name = "SameDay"
def can_deliver(self, zone):
return zone <= self.farthest_zone
def rate(self, zone):
return self.flat_cents
def dollars(cents):
return f"${cents // 100}.{cents % 100:02d}"
def quote(carrier, zone):
if not carrier.can_deliver(zone):
return f"{carrier.name}: doesn't deliver to zone {zone}"
return f"{carrier.name} to zone {zone}: {dollars(carrier.rate(zone))}"
carriers = [QuickShip(500, 200), EcoFreight(700, 10), SameDay(1500, 2)]
for zone in [2, 3]:
for carrier in carriers:
print(quote(carrier, zone))
QuickShip to zone 2: $9.00
EcoFreight to zone 2: $7.70
SameDay to zone 2: $15.00
QuickShip to zone 3: $11.00
EcoFreight to zone 3: $7.70
SameDay: doesn't deliver to zone 3
// A function that makes a carrier: an object literal whose methods remember its numbers.
function quickShip(baseCents, perZoneCents) {
return { name: "QuickShip", canDeliver: (zone) => true, rate: (zone) => baseCents + perZoneCents * zone };
}
function ecoFreight(flatCents, fuelPercent) {
return { name: "EcoFreight", canDeliver: (zone) => true, rate: (zone) => flatCents + Math.floor(flatCents * fuelPercent / 100) };
}
function sameDay(flatCents, farthestZone) {
return { name: "SameDay", canDeliver: (zone) => zone <= farthestZone, rate: (zone) => flatCents };
}
function dollars(cents) {
return `${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, "0")}`;
}
function quote(carrier, zone) {
if (!carrier.canDeliver(zone)) { return `${carrier.name}: doesn't deliver to zone ${zone}`; }
return `${carrier.name} to zone ${zone}: ${dollars(carrier.rate(zone))}`;
}
const carriers = [quickShip(500, 200), ecoFreight(700, 10), sameDay(1500, 2)];
for (const zone of [2, 3]) {
for (const carrier of carriers) {
console.log(quote(carrier, zone));
}
}
QuickShip to zone 2: $9.00
EcoFreight to zone 2: $7.70
SameDay to zone 2: $15.00
QuickShip to zone 3: $11.00
EcoFreight to zone 3: $7.70
SameDay: doesn't deliver to zone 3
interface Carrier {
name: string;
canDeliver(zone: number): boolean;
rate(zone: number): number;
}
// A function that makes a carrier: an object literal whose methods remember its numbers.
function quickShip(baseCents: number, perZoneCents: number): Carrier {
return { name: "QuickShip", canDeliver: (zone) => true, rate: (zone) => baseCents + perZoneCents * zone };
}
function ecoFreight(flatCents: number, fuelPercent: number): Carrier {
return { name: "EcoFreight", canDeliver: (zone) => true, rate: (zone) => flatCents + Math.floor(flatCents * fuelPercent / 100) };
}
function sameDay(flatCents: number, farthestZone: number): Carrier {
return { name: "SameDay", canDeliver: (zone) => zone <= farthestZone, rate: (zone) => flatCents };
}
function dollars(cents: number): string {
return `${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, "0")}`;
}
function quote(carrier: Carrier, zone: number): string {
if (!carrier.canDeliver(zone)) { return `${carrier.name}: doesn't deliver to zone ${zone}`; }
return `${carrier.name} to zone ${zone}: ${dollars(carrier.rate(zone))}`;
}
const carriers = [quickShip(500, 200), ecoFreight(700, 10), sameDay(1500, 2)];
for (const zone of [2, 3]) {
for (const carrier of carriers) {
console.log(quote(carrier, zone));
}
}
QuickShip to zone 2: $9.00
EcoFreight to zone 2: $7.70
SameDay to zone 2: $15.00
QuickShip to zone 3: $11.00
EcoFreight to zone 3: $7.70
SameDay: doesn't deliver to zone 3
Same lines again. C# and Java's record and Python's @dataclass write the constructor and fields from one line, so each carrier is its numbers and its two answers. JavaScript and TypeScript go further: a carrier is an object literal made by a small function, and its methods remember the numbers they were made with (that memory is called a closure). The strategy is still there; the boilerplate isn't.
Where you've already used it
- Sorting with a comparer object that holds settings, such as C#'s
StringComparer.OrdinalIgnoreCaseor Java'sComparator.comparing(...).reversed(): the sort asks it the same question every time, and the object carries how to answer. - A shopping site's payment options: card, gift card and pay-later each answer "can you pay this amount?" and "charge it", and checkout asks whichever one the customer picked.
- Logging libraries' formatters and "appenders": the logger asks whichever one it's handed to write the line, and each holds its own settings.
When not to use it
- One rule that never changes. A single carrier forever needs no promise and no classes.
- A rule that's one question with no data of its own. Then Pass 1's function is the better fit: a class adds lines and buys nothing.
- Carriers that differ only in numbers. If every carrier were "$X plus $Y a zone", one class with two numbers, made three times, would be enough; separate classes earn their place when the rules differ, as SameDay's zones do.
The cost: one more jump for the reader, since the quote screen's answer depends on which carrier it was handed, and one class per carrier.
Look-alikes: Template Method lets a step vary too, through a subclass instead of an object handed in; Strategy or Template Method? compares them. State has the same shape on paper; Look-Alikes: Strategy, State and Command puts the three side by side.
How often you'll meet it: every day (our estimate: as a function in most code, and as a class wherever the rule carries data).
Check yourself
2 questions to try on the lesson page.
So what
When a rule needs numbers of its own and answers more than one question, the function from Pass 1 grows into a class. Each carrier keeps its own rules in one place, the quote screen stops changing, and the next carrier is a class nobody else has to touch.