Programming Search⌘K

Patterncore

Middle Man

A code smell: a class does little but pass calls on to another object, so clients pay for an extra layer that adds no rule of its own.

Family
code-smell
Intent
Find the classes whose methods mostly forward to one delegate, and let the clients talk to the delegate, or fold the class into it.

Intent

Find the classes that mostly pass calls on to one other object. If the class adds no rule to the calls, let the clients call the delegate directly. If it adds a little, fold that little into the delegate or into the clients. Keep the layer only where it hides something that the clients should not know.

Problem

Delegation is a normal part of design. A class hides an object behind its own methods, so that the clients do not depend on the object. That is the point of Hide Delegate, the fix for Message Chains. Refactoring notes that the same tool can go too far: when half of a class's methods do nothing but delegate to another class, the class is a middle man.1

The forces are these:

  • Each forwarding method is small and seems harmless. A class gets one each time a client needs a feature of the delegate.
  • The forwarding methods must grow with the delegate. Each feature of the delegate that a client wants needs one more method in the middle.
  • A reader who follows a call must step through the middle man to find the code that does the work.
  • Wikipedia notes the same cost for the Law of Demeter, which "may result in having to write many wrapper methods to propagate calls to components".2

Solution

Refactoring gives three moves, by how much the middle man does.1 The catalogue at refactoring.com has a card for each refactoring.3

  1. The class mostly forwards: Remove Middle Man. Give the clients access to the delegate, and change them to call it directly. Then delete the forwarding methods.
  2. Only a few methods forward: Inline Function on each one, into its callers.
  3. The middle man also has some behaviour: Replace Superclass with Delegate or Replace Subclass with Delegate, to fold the middle man into the real object.

The first edition of Refactoring names the same smell, and Remove Middle Man as its main fix.4

Refactoring treats Hide Delegate and Remove Middle Man as a pair that a programmer applies back and forth as the code changes.1 Neither one is right for good. The question is how much of the delegate the clients need.

Example

The class Playlist holds an array of songs. Four of its five methods only forward to the array, and each feature of arrays that a client wants needs one more of them. After Remove Middle Man, the clients use the array, and the one method with a rule of its own stays.

import assert from "node:assert/strict";

const songs = [
  { title: "Intro", seconds: 90 },
  { title: "Theme", seconds: 200 },
  { title: "Outro", seconds: 60 },
];

// Before: four methods forward, and one has a rule.
class PlaylistBefore {
  #songs = [];
  add(song) { this.#songs.push(song); }
  size() { return this.#songs.length; }
  at(i) { return this.#songs.at(i); }
  some(f) { return this.#songs.some(f); }
  totalSeconds() { return this.#songs.reduce((t, s) => t + s.seconds, 0); }
}

// After: the clients use the array; the rule is a function.
const totalSeconds = (list) => list.reduce((t, s) => t + s.seconds, 0);

const before = new PlaylistBefore();
for (const s of songs) before.add(s);
const after = [...songs];

assert.equal(before.size(), after.length);
assert.equal(before.at(-1).title, after.at(-1).title);
assert.equal(before.some((s) => s.seconds > 180), after.some((s) => s.seconds > 180));
assert.equal(before.totalSeconds(), totalSeconds(after));
assert.equal(totalSeconds(after), 350);
console.log("playlist: tests pass");
Output
playlist: tests pass

The array already has length, at, some and many more methods, and the clients can use all of them without a change to any class. The total is the only rule, so it is the only code that remains.

Language What the example shows
JavaScript forwarding methods removed, as above
Python the same class, removed, with the rule kept as a function
Java a class that forwards to a List, removed; the rule moves to a record
Go forwarding methods replaced by an embedded field, whose methods the struct gets for free
PythonGitHub
songs = [
    {"title": "Intro", "seconds": 90},
    {"title": "Theme", "seconds": 200},
    {"title": "Outro", "seconds": 60},
]


# Before: four methods forward, and one has a rule.
class PlaylistBefore:
    def __init__(self):
        self._songs = []

    def add(self, song):
        self._songs.append(song)

    def size(self):
        return len(self._songs)

    def at(self, i):
        return self._songs[i]

    def any_longer_than(self, seconds):
        return any(s["seconds"] > seconds for s in self._songs)

    def total_seconds(self):
        return sum(s["seconds"] for s in self._songs)


# After: the clients use the list; the rule is a function.
def total_seconds(playlist):
    return sum(s["seconds"] for s in playlist)


before = PlaylistBefore()
for s in songs:
    before.add(s)
after = list(songs)

assert before.size() == len(after)
assert before.at(-1)["title"] == after[-1]["title"]
assert before.any_longer_than(180) == any(s["seconds"] > 180 for s in after)
assert before.total_seconds() == total_seconds(after) == 350
print("playlist: tests pass")
Output
playlist: tests pass
  • A Python list already supports len, indexing, slicing and iteration, so the forwarding methods are a second, smaller interface to the same thing.
  • any_longer_than is a forwarding method with a name. If many clients ask the same question, it can stay as a function next to total_seconds.
JavaGitHub
import java.util.ArrayList;
import java.util.List;

public class Main {
    record Song(String title, int seconds) {}

    // Before: four methods forward to the list, and one has a rule.
    static final class PlaylistBefore {
        private final List<Song> songs = new ArrayList<>();
        void add(Song s) { songs.add(s); }
        int size() { return songs.size(); }
        Song get(int i) { return songs.get(i); }
        boolean contains(Song s) { return songs.contains(s); }
        int totalSeconds() { return songs.stream().mapToInt(Song::seconds).sum(); }
    }

    // After: the clients use the list; the rule is a record around an unmodifiable copy.
    record Playlist(List<Song> songs) {
        Playlist {
            songs = List.copyOf(songs);
        }

        int totalSeconds() { return songs.stream().mapToInt(Song::seconds).sum(); }
    }

    public static void main(String[] args) {
        List<Song> songs = List.of(new Song("Intro", 90), new Song("Theme", 200), new Song("Outro", 60));
        PlaylistBefore before = new PlaylistBefore();
        songs.forEach(before::add);
        Playlist after = new Playlist(songs);

        if (before.size() != after.songs().size()) throw new AssertionError("size");
        if (!before.get(2).equals(after.songs().get(2))) throw new AssertionError("get");
        if (before.contains(songs.get(1)) != after.songs().contains(songs.get(1))) throw new AssertionError("contains");
        if (before.totalSeconds() != after.totalSeconds() || after.totalSeconds() != 350) throw new AssertionError("total");
        System.out.println("playlist: tests pass");
    }
}
Output
playlist: tests pass
  • after.songs() gives the clients the whole List interface. List.copyOf makes the list unmodifiable, so the clients can read it but cannot change it behind the record's back.
  • The record keeps totalSeconds, the one method that is a rule and not a forward.
package main

import (
	"fmt"
	"slices"
)

type Song struct {
	Title   string
	Seconds int
}

// Before: four methods forward to the slice, and one has a rule.
type PlaylistBefore struct{ songs []Song }

func (p *PlaylistBefore) Add(s Song)           { p.songs = append(p.songs, s) }
func (p *PlaylistBefore) Len() int             { return len(p.songs) }
func (p *PlaylistBefore) At(i int) Song        { return p.songs[i] }
func (p *PlaylistBefore) Contains(s Song) bool { return slices.Contains(p.songs, s) }
func (p *PlaylistBefore) TotalSeconds() int {
	t := 0
	for _, s := range p.songs {
		t += s.Seconds
	}
	return t
}

// After: a named slice type. Clients use len, indexing and the slices package
// directly, and the type keeps only the rule.
type Playlist []Song

func (p Playlist) TotalSeconds() int {
	t := 0
	for _, s := range p {
		t += s.Seconds
	}
	return t
}

// Embedding: a struct that gets all the methods of a field for free.
type Library struct {
	Playlist // embedded; Library has TotalSeconds with no forwarding code
	Owner    string
}

func main() {
	songs := []Song{{"Intro", 90}, {"Theme", 200}, {"Outro", 60}}
	before := &PlaylistBefore{}
	for _, s := range songs {
		before.Add(s)
	}
	after := Playlist(slices.Clone(songs))

	if before.Len() != len(after) || before.At(2) != after[2] {
		panic("len or index")
	}
	if before.Contains(songs[1]) != slices.Contains(after, songs[1]) {
		panic("contains")
	}
	if before.TotalSeconds() != after.TotalSeconds() || after.TotalSeconds() != 350 {
		panic("total")
	}
	lib := Library{Playlist: after, Owner: "ana"}
	if lib.TotalSeconds() != 350 {
		panic("promoted method")
	}
	fmt.Println("playlist: tests pass")
}
Output
playlist: tests pass
  • Playlist is a defined type whose underlying type is []Song, so len, indexing and the functions of the slices package work on it with no forwarding methods.
  • Library embeds Playlist. The method TotalSeconds is promoted, so lib.TotalSeconds() works without a method on Library.

Consequences

The clients reach the delegate in one step, and they can use all its features. There is no layer to keep in step with the delegate.

The layer may have been doing a job. A private array behind a class cannot be changed by the clients, and a class can keep a rule, such as no duplicates, on each change. When the clients get the array, they can break the rule. If the class guards a rule on writes, the class is not a middle man, even if most of its methods forward. Keep the methods that guard the rule, and remove the others.

Some languages remove the cost of the forwarding methods. In Go, a field that is declared with a type and no name is an embedded field. The Go specification calls its fields and methods promoted, says that "Promoted fields act like ordinary fields of a struct", and includes the promoted methods in the method set of the outer struct.5 The outer struct gets the methods of the delegate with no code, and can still add rules of its own.

How to fix it

Message Chains. The opposite smell. Hide Delegate fixes it, and too much Hide Delegate makes a middle man. See Message Chains.

Lazy Element. A middle man is a lazy element whose one job is to forward. See Lazy Element.

Proxy and decorator. Patterns that forward calls on purpose, to add a rule such as access control or caching on each call. A class that forwards and adds a rule is one of these, not a middle man.

References

  1. Martin Fowler, with Kent Beck, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 3, Bad Smells in Code, Middle Man
  2. Wikipedia, Law of Demeter, revision 1306566666, Disadvantages
  3. Martin Fowler, Catalog of Refactorings, the cards Remove Middle Man, Inline Function, Replace Superclass with Delegate and Replace Subclass with Delegate
  4. Martin Fowler, Refactoring, Improving the Design of Existing Code, Addison-Wesley, 1999, Chapter 3, Bad Smells in Code, Middle Man
  5. The Go Programming Language Specification, Struct types, promoted fields and methods

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/DCBNAH/text.yaml