The Principle of Least Knowledge (Law of Demeter)
What you'll learn: How limiting what objects know about each other reduces coupling and makes your code easier to change.
The Core Idea
The Principle of Least Knowledge, also called the Law of Demeter, says: only talk to your immediate friends, not to strangers. In code, this means an object should only interact with:
- Itself
- Objects passed to it as parameters
- Objects it creates
- Its direct components (properties or fields)
It should not reach through one object to access another object's internals.
Why It Matters
When objects know too much about each other's internal structure, they become tightly coupled. Imagine asking a friend for their wallet, then opening it yourself to take out money. If your friend changes wallets or reorganizes it, your process breaks. Instead, you should simply ask your friend for money—you don't need to know about their wallet at all.
This principle keeps your objects independent. When one object changes internally, fewer other objects need to update.
A Simple Example
Bad (reaching through):
customer.getWallet().getMoney() // Knows too much about wallet internals
Better (asking directly):
customer.payAmount() // Customer handles their own wallet
The second approach hides how the customer stores or retrieves money. If they switch from a wallet to a digital payment system, your code doesn't break.
The Benefit
By limiting knowledge, you create natural boundaries between parts of your system. Changes stay localized, and you build more resilient, maintainable code.
Key Takeaway: Only talk to your immediate neighbors—don't reach through objects to access their internals. This keeps coupling low and makes your system flexible.