Delegation: Handing the Job On

When every screen reaches through a rental to price its bike, a new rule such as a $2 helmet has to be added everywhere, and one place is missed; delegation gives the rental its own price() that hands the bike's part on to the bike, the move half the design patterns are built from.

Apprentice · OOP · C# · Java · Python · JavaScript · TypeScript · Updated

By

After this lesson you can

  • Write a method that hands its job to an object the class holds
  • Spot code that reaches through one object into another, and move the job to the object that owns the data

Key takeaways

  • Code that reaches through one object into another (rental.item.price(rental.hours)) has to change whenever those insides change.
  • Delegation means an object takes a job and hands it, or part of it, to an object it holds.
  • The caller talks to one object and never sees who does the work behind it.
  • Many patterns are delegation with a purpose: a front that hands calls to parts, a wrapper that adds something on the way.

Before this: Inheritance and Composition: Is-a and Has-a, where a class keeps another object in a field.

Pedal & Go starts renting helmets: $2 a rental, added to the price. It's a one-line rule. Then someone adds it to the receipt, the end-of-day total stays as it was, and the desk's report says the shop made $2 less than the receipts add up to. The rule took one line to write and a moment to forget, because the price of a rental was worked out in two places, by code that reached inside each rental to do it. This lesson is about delegation, the small move that stops that from happening, and that half of the design patterns are built from.

Reaching through

Each rental holds a vehicle, its hours, and whether the renter took a helmet. The receipt and the day's total each work out a rental's price themselves, by reaching through the rental to its vehicle:

List<Rental> rentals = new List<Rental>
{
    new Rental(new Bike(), 2, false),
    new Rental(new EBike(), 3, true),
};

// The receipt: updated when helmets arrived.
foreach (Rental rental in rentals)
{
    int price = rental.Item.Price(rental.Hours) + (rental.Helmet ? 2 : 0);
    Console.WriteLine(quot;{rental.Item.Name}, {rental.Hours} hours: ${price}");
}

// The day's total: nobody told it about helmets.
int total = 0;
foreach (Rental rental in rentals)
{
    total += rental.Item.Price(rental.Hours);
}
Console.WriteLine(quot;Day's total: ${total}");

interface IRentable { string Name { get; } int Price(int hours); }
class Bike : IRentable { public string Name => "Bike"; public int Price(int hours) => 10 * hours; }
class EBike : IRentable { public string Name => "E-bike"; public int Price(int hours) => 15 * hours; }
record Rental(IRentable Item, int Hours, bool Helmet);
Bike, 2 hours: $20
E-bike, 3 hours: $47
Day's total: $65
interface Rentable { String name(); int price(int hours); }
class Bike implements Rentable { public String name() { return "Bike"; } public int price(int hours) { return 10 * hours; } }
class EBike implements Rentable { public String name() { return "E-bike"; } public int price(int hours) { return 15 * hours; } }
record Rental(Rentable item, int hours, boolean helmet) {}

void main() {
    List<Rental> rentals = List.of(
        new Rental(new Bike(), 2, false),
        new Rental(new EBike(), 3, true));

    // The receipt: updated when helmets arrived.
    for (Rental rental : rentals) {
        int price = rental.item().price(rental.hours()) + (rental.helmet() ? 2 : 0);
        IO.println(rental.item().name() + ", " + rental.hours() + " hours: quot; + price);
    }

    // The day's total: nobody told it about helmets.
    int total = 0;
    for (Rental rental : rentals) {
        total += rental.item().price(rental.hours());
    }
    IO.println("Day's total: quot; + total);
}
Bike, 2 hours: $20
E-bike, 3 hours: $47
Day's total: $65
class Bike:
    name = "Bike"

    def price(self, hours):
        return 10 * hours


class EBike:
    name = "E-bike"

    def price(self, hours):
        return 15 * hours


class Rental:
    def __init__(self, item, hours, helmet):
        self.item = item
        self.hours = hours
        self.helmet = helmet


rentals = [Rental(Bike(), 2, False), Rental(EBike(), 3, True)]

# The receipt: updated when helmets arrived.
for rental in rentals:
    price = rental.item.price(rental.hours) + (2 if rental.helmet else 0)
    print(f"{rental.item.name}, {rental.hours} hours: ${price}")

# The day's total: nobody told it about helmets.
total = 0
for rental in rentals:
    total += rental.item.price(rental.hours)
print(f"Day's total: ${total}")
Bike, 2 hours: $20
E-bike, 3 hours: $47
Day's total: $65
class Bike { name = "Bike"; price(hours) { return 10 * hours; } }
class EBike { name = "E-bike"; price(hours) { return 15 * hours; } }

class Rental {
  constructor(item, hours, helmet) {
    this.item = item;
    this.hours = hours;
    this.helmet = helmet;
  }
}

const rentals = [new Rental(new Bike(), 2, false), new Rental(new EBike(), 3, true)];

// The receipt: updated when helmets arrived.
for (const rental of rentals) {
  const price = rental.item.price(rental.hours) + (rental.helmet ? 2 : 0);
  console.log(`${rental.item.name}, ${rental.hours} hours: ${price}`);
}

// The day's total: nobody told it about helmets.
let total = 0;
for (const rental of rentals) {
  total += rental.item.price(rental.hours);
}
console.log(`Day's total: ${total}`);
Bike, 2 hours: $20
E-bike, 3 hours: $47
Day's total: $65
interface Rentable { name: string; price(hours: number): number; }
class Bike implements Rentable { name = "Bike"; price(hours: number): number { return 10 * hours; } }
class EBike implements Rentable { name = "E-bike"; price(hours: number): number { return 15 * hours; } }

class Rental {
  item: Rentable;
  hours: number;
  helmet: boolean;

  constructor(item: Rentable, hours: number, helmet: boolean) {
    this.item = item;
    this.hours = hours;
    this.helmet = helmet;
  }
}

const rentals = [new Rental(new Bike(), 2, false), new Rental(new EBike(), 3, true)];

// The receipt: updated when helmets arrived.
for (const rental of rentals) {
  const price = rental.item.price(rental.hours) + (rental.helmet ? 2 : 0);
  console.log(`${rental.item.name}, ${rental.hours} hours: ${price}`);
}

// The day's total: nobody told it about helmets.
let total = 0;
for (const rental of rentals) {
  total += rental.item.price(rental.hours);
}
console.log(`Day's total: ${total}`);
Bike, 2 hours: $20
E-bike, 3 hours: $47
Day's total: $65

The receipts add up to $67; the day's total says $65. Look at how each loop gets a price: rental.item.price(rental.hours). The loop reaches through the rental to its vehicle, pulls out the hours, and does the rental's math itself. Every place that does that knows how a rental is priced, so every one of them has to change when the rule does. Code that depends on another object's insides like this is tightly coupled to it: coupling is how much one piece of code has to know about another, and the more it knows, the more it breaks when the other changes.

Hand the job to whoever owns it

At a bike shop's front desk, you say "my brakes squeak". The clerk writes it up and hands the repair to the mechanic in the back. You never talk to the mechanic, and you don't need to know whether there's one mechanic or three, or whether the wheels go out to a specialist. You deal with the desk, and the desk passes the job on.

A bike shop's front desk: a customer hands a bike across the counter to the clerk, and through a doorway behind the clerk a mechanic at a workbench is reaching for the bike's brake; the customer only faces the clerk

That's delegation: an object takes a job and hands it, or part of it, to an object it holds. Here, the rental is the one that knows its hours and its helmet, so it should be the one that knows its price. It keeps a vehicle (composition, from the last lesson), and for the vehicle's part of the price it hands the job on:

List<Rental> rentals = new List<Rental>
{
    new Rental(new Bike(), 2, false),
    new Rental(new EBike(), 3, true),
};

foreach (Rental rental in rentals)
{
    Console.WriteLine(quot;{rental.Item.Name}, {rental.Hours} hours: ${rental.Price()}");
}

int total = 0;
foreach (Rental rental in rentals)
{
    total += rental.Price();
}
Console.WriteLine(quot;Day's total: ${total}");

interface IRentable { string Name { get; } int Price(int hours); }
class Bike : IRentable { public string Name => "Bike"; public int Price(int hours) => 10 * hours; }
class EBike : IRentable { public string Name => "E-bike"; public int Price(int hours) => 15 * hours; }

record Rental(IRentable Item, int Hours, bool Helmet)
{
    // A rental knows its own price, and hands the vehicle's part to the vehicle.
    public int Price()
    {
        int helmetFee = Helmet ? 2 : 0;
        return Item.Price(Hours) + helmetFee;
    }
}
Bike, 2 hours: $20
E-bike, 3 hours: $47
Day's total: $67
interface Rentable { String name(); int price(int hours); }
class Bike implements Rentable { public String name() { return "Bike"; } public int price(int hours) { return 10 * hours; } }
class EBike implements Rentable { public String name() { return "E-bike"; } public int price(int hours) { return 15 * hours; } }

record Rental(Rentable item, int hours, boolean helmet) {
    // A rental knows its own price, and hands the vehicle's part to the vehicle.
    int price() {
        int helmetFee = helmet ? 2 : 0;
        return item.price(hours) + helmetFee;
    }
}

void main() {
    List<Rental> rentals = List.of(
        new Rental(new Bike(), 2, false),
        new Rental(new EBike(), 3, true));

    for (Rental rental : rentals) {
        IO.println(rental.item().name() + ", " + rental.hours() + " hours: quot; + rental.price());
    }

    int total = 0;
    for (Rental rental : rentals) {
        total += rental.price();
    }
    IO.println("Day's total: quot; + total);
}
Bike, 2 hours: $20
E-bike, 3 hours: $47
Day's total: $67
class Bike:
    name = "Bike"

    def price(self, hours):
        return 10 * hours


class EBike:
    name = "E-bike"

    def price(self, hours):
        return 15 * hours


class Rental:
    def __init__(self, item, hours, helmet):
        self.item = item
        self.hours = hours
        self.helmet = helmet

    def price(self):
        """A rental knows its own price, and hands the vehicle's part to the vehicle."""
        helmet_fee = 2 if self.helmet else 0
        return self.item.price(self.hours) + helmet_fee


rentals = [Rental(Bike(), 2, False), Rental(EBike(), 3, True)]

for rental in rentals:
    print(f"{rental.item.name}, {rental.hours} hours: ${rental.price()}")

total = 0
for rental in rentals:
    total += rental.price()
print(f"Day's total: ${total}")
Bike, 2 hours: $20
E-bike, 3 hours: $47
Day's total: $67
class Bike { name = "Bike"; price(hours) { return 10 * hours; } }
class EBike { name = "E-bike"; price(hours) { return 15 * hours; } }

class Rental {
  constructor(item, hours, helmet) {
    this.item = item;
    this.hours = hours;
    this.helmet = helmet;
  }

  // A rental knows its own price, and hands the vehicle's part to the vehicle.
  price() {
    const helmetFee = this.helmet ? 2 : 0;
    return this.item.price(this.hours) + helmetFee;
  }
}

const rentals = [new Rental(new Bike(), 2, false), new Rental(new EBike(), 3, true)];

for (const rental of rentals) {
  console.log(`${rental.item.name}, ${rental.hours} hours: ${rental.price()}`);
}

let total = 0;
for (const rental of rentals) {
  total += rental.price();
}
console.log(`Day's total: ${total}`);
Bike, 2 hours: $20
E-bike, 3 hours: $47
Day's total: $67
interface Rentable { name: string; price(hours: number): number; }
class Bike implements Rentable { name = "Bike"; price(hours: number): number { return 10 * hours; } }
class EBike implements Rentable { name = "E-bike"; price(hours: number): number { return 15 * hours; } }

class Rental {
  item: Rentable;
  hours: number;
  helmet: boolean;

  constructor(item: Rentable, hours: number, helmet: boolean) {
    this.item = item;
    this.hours = hours;
    this.helmet = helmet;
  }

  // A rental knows its own price, and hands the vehicle's part to the vehicle.
  price(): number {
    const helmetFee = this.helmet ? 2 : 0;
    return this.item.price(this.hours) + helmetFee;
  }
}

const rentals = [new Rental(new Bike(), 2, false), new Rental(new EBike(), 3, true)];

for (const rental of rentals) {
  console.log(`${rental.item.name}, ${rental.hours} hours: ${rental.price()}`);
}

let total = 0;
for (const rental of rentals) {
  total += rental.price();
}
console.log(`Day's total: ${total}`);
Bike, 2 hours: $20
E-bike, 3 hours: $47
Day's total: $67

The two loops now ask the rental, rental.price(), and know nothing about helmets or hours. The rental does its own part (the helmet) and delegates the rest to its vehicle, item.price(hours), which knows its own rate. Next month's rule, a late fee or a member discount, goes in one method, and every screen gets it. In C# and Java, a record can have methods too, like any class.

In your textbook

The rule of thumb behind this has a formal name: the Law of Demeter, or "talk to your friends, not to strangers". A method should call methods on the objects it was handed or holds, not on objects it digs out of them. A line with a chain of dots reaching into something's insides, like rental.item.price(rental.hours), is the warning sign. It's a rule of thumb, not a law: name.ToUpper().Trim() is a chain of dots that's perfectly fine, because nothing's insides are being dug into.

Half the patterns, in one move

You'll meet delegation again and again, each time with a purpose of its own. A front that hands each call on to the right part (a Facade). A wrapper that hands calls on and adds something along the way. A stand-in that hands calls on only when it's worth the trip. Each is "hold an object, and hand it the job", with a reason for doing it that gives the pattern its name.

Try it. Add a member discount to Rental's price: $3 off when a new member flag is true. Give the bike's rental the flag. The receipt and the total change together, and neither loop is touched.

Check yourself

2 questions to try on the lesson page.

So what

When code reaches through an object to do that object's job, move the job to the object and let it hand on what it holds: every rule then has one home, and every caller gets it for free.

Key terms

Cheat sheets