AI Briefing
KO

Improving Code Quality - Session 55: The Law of Demeter

·2025.11.28 11:00

Key point

Rather than simply applying the Law of Demeter, it is important to understand the boundaries of knowledge from the perspective of information hiding and encapsulation.

Details

One of the programming principles, the Law of Demeter, is the principle that an object should only interact with members (properties/methods) it directly knows about. It is often expressed as "only talk to your friends," and its purpose is to lower coupling between objects.

Specifically, when calling a method, the receiver should be limited to the following cases:

  • this (itself)
  • A field or property of this
  • An object passed as an argument to the function
  • An object created directly inside the function
  • A global variable or singleton object

On the other hand, calling the return value of a property again, or digging into the properties of an argument, are examples that violate the law. However, simply separating code just to follow the law is not always the right answer.

For example, when performing a refactoring that extracts a separate function to avoid chained method calls, you need to consider, from the perspective of boundaries, whether this truly realizes Information Hiding and Encapsulation in a meaningful sense, or whether it is merely following a superficial rule.

This summary was generated automatically by AI. Check the original for the author's claims and context. Copyright belongs to the original author.

Our guide explains how the AI works. Report summary errors, attribution issues, or removal requests via Contact.