Controller

“What first object beyond the UI layer receives and coordinates a system operation?” – Craig Larman

A Controller is the first object beyond the UI layer that is responsible for receiving or handling a system operation message.

When to use

When connecting a UI (View) to the business logic (Model). You need a mediator to decouple them.

Why it matters

  • Decoupling: UI code doesn’t contain business logic.
  • Reusability: Business logic can be reused by different UIs (Web, CLI, Mobile) if it’s behind a controller.

Signs of Violation

  • “Fat Controllers”: The controller does all the work itself rather than delegating to domain objects.
  • UI logic (like handling DOM events) mixed with business calculations in the same file.

Explanation

Problem

If the UI talks directly to domain objects (managing transactions, coordinating work), the UI becomes tightly coupled to the system mechanisms. If business logic is in the UI, you can’t reuse it (e.g., exposing an API).

Solution

Introduce a Controller class (e.g., RegisterUserController, OrderHandler) that accepts the input, orchestrates the work by calling domain objects, and returns the result.

Real world analogy

A receptionist at a company. You don’t walk straight to the CEO’s office. You talk to the receptionist (Controller), who directs your request to the appropriate department.

Pros and Cons

Pros Cons
  • Separation of concerns (UI vs Logic)
  • Orchestration point
  • Can become bloated (Bloated Controller smell)
  • Comparison

    • Facade Pattern: A controller is often a facade for the underlying domain layer.
    • Command Pattern: Controllers often fire Commands.

    Code example

    Typescript

    Bad (Violation)

    Good (Adherence)

    PHP

    Bad (Violation)

    Good (Adherence)