Return to site

🚦 Law of Demeter (LoD): “Don’t talk to strangers.”

· craftsmanship

Keep objects talking only to their immediate friends. Fewer train-wreck chains, more intention-revealing methods. Your code gets safer, easier to change, and simpler to test. 💡

Why care?

  • 🔒 Lower coupling
  • 🛠 Easier refactors
  • 🧪 Cleaner tests
  • 📦 Better encapsulation

❌ Smell: Train-wreck chaining

✅ LoD-friendly: Tell, don’t ask

❌ Smell: Deep dives in streams

✅ LoD-friendly: Push logic to the owner

Quick checklist 🧾

  • ▶️ Prefer order.shippingCity() over order.getCustomer().getAddress().getCity()
  • 🗣️ Tell objects to do things, don’t pull their guts
  • 🧩 Hide structure behind intention-revealing methods
  • ✂️ If you must chain, keep it within the same object (fluent APIs are usually fine)

Go further with Java certification:

Java👇

Spring👇