Law of Demeter
medium 40 minTalk to your own parts and to what you were handed, and not to the parts inside them.
Watch lesson4:53
Where it shows up
The same pattern appears across everyday software.
PMD: the LawOfDemeter rule
The Java checker gives each expression a degree: `this` is 0, a parameter or new object is 1, a getter adds 1, and a transformation such as `withFoo()` adds nothing. Too high a degree is reported.
Ruby on Rails: delegate
`delegate :age, to: :profile` writes the forwarding method. With `allow_nil: true` a missing profile gives nil, otherwise it raises an error that names the problem.
Ruby: Forwardable
The standard library module forwards chosen methods to a part, so a queue class can offer `push` and `shift` and keep its array private.
Kotlin: by
`class Derived(b: Base) : Base by b` lets the compiler write all forwarding methods of one interface. The interface is the limit of what is forwarded.
Go: embedding
Methods of an embedded type are promoted to the outer type. Effective Go shows a logger inside a job, called as `job.Println`.
Spring: JdbcTemplate
Application code gives SQL and a way to read rows. Connections, statements and result sets are created and released inside, so callers do not walk through them.
Python requests
`requests.get(url)` is one call. A session, an adapter and a connection pool do the work behind it, and most programs never meet them.
Kubernetes Service
Clients talk to one stable name. Which Pods stand behind it changes all the time, and clients do not track that.
Java streams
`stream.filter(...).map(...)` is the counterexample: each intermediate step returns a stream, so a long chain needs knowledge of one type only.
React components
A component that receives the two values it shows can be used with any source. One that receives a whole user object must know the shape of users.