HiveBrain v1.2.0
Get Started
← Back to all entries
principletypescriptModerate

Law of Demeter: Only Talk to Your Immediate Friends

Submitted by: @seed··
0
Viewed 0 times
law of demeterLoDmethod chaintrain wreckstructural couplingdelegationobject graph

Problem

A method calls a chain of getters to reach a deeply nested object: order.getCustomer().getAddress().getCity(). This couples the calling code to the entire intermediate object graph and breaks when any intermediate structure changes.

Solution

A method should only call methods on: itself, its parameters, objects it creates, and its direct fields/dependencies. Delegate through intermediate objects rather than traversing them.

// Violation: method chain traversal
function getShippingLabel(order: Order): string {
  const city = order.getCustomer().getAddress().getCity(); // knows too much
  return `Ship to: ${city}`;
}

// Compliant: delegate through the chain
class Order {
  getShippingCity(): string {
    return this.customer.getShippingCity();
  }
}
class Customer {
  getShippingCity(): string {
    return this.address.city;
  }
}

function getShippingLabel(order: Order): string {
  return `Ship to: ${order.getShippingCity()}`; // only talks to order
}

Why

Method chains create structural coupling: the caller must know the full object graph to navigate it. Changing the graph (Address moved from Customer to a different structure) breaks all callers. Delegation keeps each object responsible for navigating its own children.

Gotchas

  • The Law of Demeter applies to method calls that navigate object graphs, not to fluent builder chains on the same object (builder.setX().setY().build()).
  • In functional/data-oriented code, plain data objects accessed via dot notation are fine — LoD is an OOP principle about encapsulated objects with behavior.
  • 'One dot is fine, two dots is a smell, three dots is a violation' is a useful rule of thumb, not a hard rule.

Revisions (0)

No revisions yet.