Skip to content

Hide Delegate: Stop Callers Reaching Through an Object's Internals

Learn Hide Delegate: add delegating methods so callers stop navigating object internals, with TypeScript, Python and PHP examples.

6 min readRefactoring

Hide Delegate is a small refactoring with a big effect on coupling. When client code asks one object for another object and then calls methods on that second object, you add methods to the first object that make the call for the client. The client then talks to one object only, and the delegate becomes an implementation detail you are free to change. In interviews it often comes up alongside the Law of Demeter, message chains, and its mirror image, Remove Middle Man. You should be able to explain when to apply it, when to stop, and how to do it in steps that keep the tests green.

The problem

A situation where the obvious design starts to hurt.

Picture BoxDrop, a parcel-locker service. A Parcel holds a Locker, and the locker knows its station name, compartment code and closing hour. The notification code that texts customers and the job that decides whether a parcel can still be collected today both reach through parcel.locker to read those fields.

That means every caller knows that a parcel is stored in a locker and knows the locker's shape. If BoxDrop later adds home-delivery parcels with no locker, or moves the closing hour onto a separate station schedule, you have to find and edit every caller. The coupling spreads with each new feature that needs pickup details.

Before and after

The same code, before and after the change.

Before

class Locker {
  constructor(
    readonly stationName: string,
    readonly compartment: string,
    readonly closingHour: number,
  ) {}
}

class Parcel {
  constructor(
    readonly trackingId: string,
    readonly locker: Locker,
  ) {}
}

function pickupMessage(parcel: Parcel): string {
  const locker = parcel.locker;
  return `Parcel ${parcel.trackingId} is waiting at ${locker.stationName}, compartment ${locker.compartment}. Collect it before ${locker.closingHour}:00.`;
}

function canCollectToday(parcel: Parcel, currentHour: number): boolean {
  return currentHour < parcel.locker.closingHour;
}

const parcel = new Parcel("BX-48213", new Locker("Harbour Street", "C17", 22));
console.log(pickupMessage(parcel));
console.log(canCollectToday(parcel, 21));

After

class Locker {
  constructor(
    readonly stationName: string,
    readonly compartment: string,
    readonly closingHour: number,
  ) {}
}

class Parcel {
  constructor(
    readonly trackingId: string,
    private readonly locker: Locker,
  ) {}

  stationName(): string {
    return this.locker.stationName;
  }

  compartment(): string {
    return this.locker.compartment;
  }

  closingHour(): number {
    return this.locker.closingHour;
  }
}

function pickupMessage(parcel: Parcel): string {
  return `Parcel ${parcel.trackingId} is waiting at ${parcel.stationName()}, compartment ${parcel.compartment()}. Collect it before ${parcel.closingHour()}:00.`;
}

function canCollectToday(parcel: Parcel, currentHour: number): boolean {
  return currentHour < parcel.closingHour();
}

const parcel = new Parcel("BX-48213", new Locker("Harbour Street", "C17", 22));
console.log(pickupMessage(parcel));
console.log(canCollectToday(parcel, 21));

Why it's worth it

What the change buys you.

Before the refactoring, pickupMessage and canCollectToday depended on two classes: Parcel and Locker. After it, they depend on Parcel alone. The fact that pickup details live in a locker is now private to Parcel, so changing that structure touches one class instead of every caller.

That matters the day BoxDrop adds a parcel type collected from a staffed counter, or moves closing hours into a station schedule shared by many lockers. You change the body of closingHour() and the notification code, the collection check and any future callers keep working untouched.

The delegating methods also give the concept a name in the parcel's vocabulary. A caller asking a parcel for its closing hour reads more naturally than one that knows which nested object happens to store it. Behaviour is unchanged: the same message and the same boolean come out, and each new method is a single field read, so there is no meaningful runtime cost.

  • Clients depend on one object instead of a chain of objects, so structural changes stay local.
  • The delegate can be replaced, split or moved without editing callers.
  • Pickup details get names in the domain language of the class callers already use.
  • Making the delegate field private lets the compiler or linter prevent new chains from appearing.

Careful with

  • Each new delegating method grows the server's interface. If most of a class becomes pass-through methods, you have created a Middle Man and should consider Remove Middle Man instead.
  • Do not hide a delegate that callers legitimately need as a whole, such as passing the locker to a maintenance scheduler. Hide only the pieces clients keep reaching for.
  • Making the field private is a breaking change for any external code or serializers that read it. Check usages across services and templates before you restrict access.
  • Avoid adding delegating methods speculatively for every field of the delegate. Add them when a real caller needs them.

Step by step

Small, safe steps, with the tests passing after each.

  1. Make sure tests cover the callers that navigate through the delegate, here the pickup message text and the collection check at hours before and after closing.

  2. Add one delegating method to the server class, for example closingHour() on Parcel, returning this.locker.closingHour. Run the tests.

  3. Switch one caller from parcel.locker.closingHour to parcel.closingHour(). Run the tests.

  4. Repeat for the remaining callers of that field until no client reads it through the locker. Run the tests after each change.

  5. Add the next delegating method, such as stationName() or compartment(), and migrate its callers the same way, one at a time.

  6. Search the codebase for any remaining access to parcel.locker. When none remain outside Parcel, make the field private.

  7. Run the full test suite and, if your language supports it, let the compiler or a static analyser confirm nothing outside the class still touches the delegate.

Smells it removes

Smells this refactoring helps remove.

Common questions

Short answers to the usual doubts.

How is Hide Delegate different from Remove Middle Man?

They are inverses. Hide Delegate adds forwarding methods so clients stop reaching through an object. Remove Middle Man deletes forwarding methods and lets clients talk to the delegate directly. You pick based on how much forwarding the class is doing: a few well-named methods that hide structure are good, a class that does nothing but forward is not.

Is this the same as following the Law of Demeter?

It is the most common way to fix Law of Demeter violations. The guideline says a method should talk to its immediate collaborators rather than to objects returned by them. Hide Delegate gives the immediate collaborator a method that answers the question, so the chain disappears from the caller.

What if the chain is several levels deep?

Work one level at a time. If callers write a.b().c().value(), first add a method on b that returns c().value(), migrate callers, then add a method on a that calls it. Each step is small and keeps tests passing, and you can stop at whichever level gives callers what they need.

Does adding these methods hurt performance?

In practice no. Each delegating method is a single extra call that reads a field, so the cost is constant and usually inlined by the runtime or JIT. The coupling you remove matters far more than the call overhead.

How would I explain this refactoring in an interview?

Describe a concrete chain, name the coupling it causes, show the delegating method, and mention the trade-off with Middle Man. Then say how you would do it safely: tests first, one method and one caller at a time, and only make the field private once no external code uses it.

Next guide5 of 5 · Techniques: moving featuresRemove Middle Man: Let Callers Talk to the Real ObjectRead the next one