Card 06/ 08

GotchaDifficulty: Advanced2 min

A Mediator That Knows Too Much

Every rule in the application moves into the mediator, and it becomes the class everyone edits.

A mediator removes the links between colleagues by taking on the rules those links carried. It moves complexity rather than removing it, and if one mediator collects the rules for every part of an application, it grows into the largest and most edited class in the codebase. This card shows the shape that problem takes, and how to keep each mediator to one conversation.

The booking dialog works well, so the team routes more through it: payment validation, a loyalty discount, an email after booking, and the analytics events for every click.

One mediator for everything, and one mediator per conversation

Without limitsevery rule goes in one method

py
def changed(self, field):
    if field is self.trip: ...
    if field is self.departure: ...
    if field is self.card_number: ...
    if field is self.loyalty_code: ...
    if field is self.book: ...
    self.track_click(field)

Every new feature edits this method.

With limitseach mediator coordinates one group

py
class JourneyDialog: ...
class PaymentDialog: ...


class BookingFlow:
    def journey_chosen(self, journey): ...
    def payment_accepted(self, payment): ...

The flow coordinates the dialogs, not their fields.

The cost is the one the pattern set out to avoid, in a new place. The colleagues are simple, but the mediator now has a reason to change for every feature, two developers working on payment and analytics edit the same method, and a test of the seat rule must build a dialog that also knows about card numbers.

The fix is to give each mediator one conversation: the objects that really do affect each other. The journey fields belong together; the payment fields belong together; the two meet only when a journey is chosen and paid for, which a higher-level mediator can coordinate. Rules that do not involve the colleagues at all, such as analytics, belong outside, often as observers of the mediator's events.

A useful check is to read the mediator's colleague list aloud. If two of its colleagues never affect each other, they may belong to different mediators.