We need to answer: "What is the 'Law of Demeter' (or Principle of Least Knowledge)? Please state the Law of Demeter, what is the goal of this principle? (To reduce coupling), provide a code example that violates the law (e.g., a.getB().getC().doSomething()), and show how to refactor the code to adhere to the principle."
We need to give a clear explanation, statement of the law, its goal (reduce coupling, increase encapsulation, etc.), provide a code example that violates, and then refactor to follow.
We should be thorough. The user might expect an answer in text, maybe with code snippets. We should state the law: "Only talk to your immediate friends." More formally: each unit should have limited knowledge about other units; only objects that are directly related should be accessed. There are variations: "The Law of Demeter for functions/methods" states that a method M of an object O should only call methods of: O itself, its parameters, any objects it creates/instantiates, its direct component objects (i.e., fields), or any objects returned by methods in the previous categories.
We should also mention "Principle of Least Knowledge" as another name.
Goal: reduce coupling, improve maintainability, make code more robust to changes, hide internal structure.
We'll provide a code example: say we have class A that has a B, B has a C, C has a doSomething() method. Violation: a.getB().getC().doSomething() — That's chaining. Show how to refactor: either add a method in B that delegates to C's doSomething, or in A that delegates through B, or maybe A should not need to know about C; maybe we can have a method in A that directly calls something like a.doSomethingInC() but that still might be violation if it's just forwarding. Actually proper refactor: we should move the behavior to where it's needed. Suppose we need to perform an operation that belongs to C. We could add a method in B: public void doSomethingInC() { c.doSomething(); } Then A can call a.getB().doSomethingInC(). That's one step less. Or better: we could have a method in A that internally uses B to do the work, without exposing C. But if A really needs to trigger something on C, maybe the design should be reconsidered: perhaps A should not be responsible for that; maybe the responsibility should be delegated to B or to a mediator. However, typical demonstration: Refactor by adding a method in B that encapsulates the call to C, so A only talks to B, not to C. Or even better: if C's behavior is something that A needs, maybe it's a sign that A should have a direct reference to C? But that might increase coupling. So we need to present a common refactor: add a method in B that forwards the call, thus reducing the chain length to 1.
We can also talk about the concept of "train wreck" code. Provide a before and after.
We need to be careful: The Law of Demeter is about limiting the number of "dots". So the solution is to reduce the chain depth to at most 1 (for that method). So we can refactor by adding a method in B that calls C.doSomething(). So the call becomes a.getB().doSomethingViaC() but that's still a chain of 1: getB then doSomethingViaC. That's okay: a.getB().doSomething() is a method on B, not on C. Or we could have a method in A that calls b.doSomething() without exposing getB? Actually a.getB() returns B, then we call a method on B. That's allowed if getB() is considered a direct component? But the rule says you can call methods on objects you create or have as fields (direct components). So if a has a field b, it can call b.doSomething() directly without getB? Actually it can access the field directly or via a getter? Typically, the Law of Demeter says you shouldn't chain more than one dot. So a.getB().doSomething() is okay because it's a.getB() then doSomething on that B. But a.getB().getC().doSomething() is two dots after a, which is violation. So we reduce to one dot after a.
So code example:
class C { void doSomething() { ... } }
class B { C getC() { ... } }
class A { B getB() { ... } }
Violation: a.getB().getC().doSomething();
Refactor: Add in B: void doSomethingInC() { getC().doSomething(); } Then call: a.getB().doSomethingInC(); That's now only one dot after a.
Alternatively, if we want to avoid B exposing C, we could have B handle the doSomething entirely: maybe B has a method performTask() that internally does c.doSomething(). That's similar.
We can also refactor by moving the behavior to A if it makes sense? But that might not reduce coupling; it could increase. Better to delegate.
We can also talk about the "Tell, Don't Ask" principle: tell the object what to do, don't ask for its data and then do it yourself. So instead of a.getB().getC().doSomething(), we could tell A: "hey, do the thing", and then A tells B, B tells C, etc. But in code, we need to implement methods.
We should also note that sometimes we might have to return a value from the chain; then we need to restructure.
I'll provide a simple example in Java (or any OOP language). Since the user expects code example, Java is typical.
Let's write:
// Violating code
class A {
private B b;
public B getB() { return b; }
}
class B {
private C c;
public C getC() { return c; }
}
class C {
public void doSomething() { System.out.println("Doing something"); }
}
// Somewhere:
a.getB().getC().doSomething();
Refactor:
Add in B:
public void doSomethingInC() {
c.doSomething();
}
// Maybe also rename to something meaningful like process().
Now usage:
a.getB().doSomethingInC();
But still uses getB. That's okay: a.getB().doSomethingInC() is one dot after a if you consider the call chain? Actually it's a.getB().doSomethingInC() - that's two method calls: getB() then doSomethingInC(). That's still a chain of one dot: the dot after a is getB(), and then we call method on returned B. That's allowed: you can call one method on the returned object. The violation is when you have two or more dots beyond the original object: a.b.c.d would be three dots. So a.getB().getC().doSomething() has two dots after a: getB() and getC() on the result of getB(). So that's two. So the refactor reduces to one dot after a: a.getB().doSomethingInC() is one method call on B after retrieving B. That's okay.
Alternatively, we could eliminate getB() by having A directly expose a method that delegates to B: e.g., in A:
public void doSomethingInC() {
b.doSomethingInC();
}
Then call a.doSomethingInC(). That's even better: a has direct behavior. But that may not be necessary.
We should also discuss that the Law of Demeter is about reducing coupling and making code more maintainable because changes in C won't affect A. In the violation, if getC() changes signature or returns something else, A must change. In the refactored version, A only depends on B's interface; changes inside B (like delegating to C differently) won't affect A.
We could also mention that the principle is not a strict rule but a guideline. There are cases where chaining is acceptable (e.g., building a query, immutable object patterns). But generally it's good.
We need to answer: "What is the Law of Demeter? Please state the Law of Demeter, what is the goal of this principle? (To reduce coupling), provide a code example that violates the law (e.g., a.getB().getC().doSomething()), and show how to refactor the code to adhere to the principle."
We'll produce a concise but thorough answer. Should we include formal statement? I'll state: "The Law of Demeter (LoD) or Principle of Least Knowledge states that a given object should only communicate with its immediate friends: its own methods, its own fields, its parameters, objects it creates, and objects returned by those. It should not call methods on objects that are obtained via another method call (i.e., no long chains of method calls)." More precise: "Each unit should have limited knowledge about other units; only units that are closely related should be accessed."
Goal: reduce coupling, increase modularity, improve maintainability, and adhere to encapsulation. It makes systems more robust to changes because changes in internal structures of distant objects don't ripple through.
Provide Java example. I'll write full classes, show violation, refactor.
We need to be careful: In Java, getB() returns a B. That's a method call that returns a "friend"? Actually getB() returns an object that is a direct component, but using getB().getC() is chaining. It's considered violation because we are navigating through B to get C. The principle says: you should only call methods of: self, parameters, fields, objects created, or objects returned by those. So if B is a field of A, then A can call B's methods directly (if it has direct reference). But here we are using getB() to retrieve it; that's okay, but then calling getC() on B is calling a method on an object that is not one of A's direct friends? Actually B is a direct friend (it's a field). But the result of getC() is a C, which is not a direct friend of A; it's a friend-of-a-friend. So that's violation. So we need to avoid that.
Refactor: Add a method in B that calls C's method, so A only calls B. That's the typical solution.
We could also think: If A has a direct reference to C, then it could call c.doSomething() directly. But that would increase coupling (A now depends on C). So not recommended.
We can present both: bad and good.
Maybe also show a more realistic scenario: like order processing where an order object has a customer, and you need to get customer's address to print label. If you do order.getCustomer().getAddress().printLabel(), that's violation. Better: order.printLabel() that internally gets customer and address.
Yes.
I'll provide an example: Class Order, class Customer, class Address. Violation: order.getCustomer().getAddress().printLabel(). Refactor: add method in Order: printShippingLabel() that uses customer.getAddress().printLabel(). Or even better: Order could have a method getShippingLabel() that returns the label string.
But I need to show two versions: violating and fixed.
We'll provide code snippets and explanation.
We also need to answer "Please state the Law of Demeter". So we should include a formal definition like: "For any object o, a method m of o should only invoke methods of the following kinds of objects: 1) itself (o); 2) its parameters; 3) any objects it creates/instantiates; 4) its direct component objects; 5) any objects returned by methods of the previous categories." That's a typical formulation.
Sometimes it's given as: "Only talk to your immediate friends." I'll provide that.
Goal: reduce coupling, increase maintainability, better encapsulation.
Now let's craft the answer. It should be clear, not too long but informative. We'll include code examples with Java-like syntax.
We'll check that we have all components: statement, goal, code example (violation), refactor.
I can also mention that the principle is also called "Principle of Least Knowledge".
We need to be careful to not overcomplicate. Provide simple code.
Let's produce:
// Violation
A a = new A();
a.getB().getC().doSomething();
Then refactored:
A a = new A();
a.getB().doSomethingInC();
Or:
a.doSomethingInC();
We can show both levels.
Also, we can discuss that sometimes the violation is hidden in multiple dots: a.b.c.d.method() etc.
We can also note that the principle does not prohibit returning a value; you can return a primitive or immutable value and then call methods on that? Actually you can call methods on the returned value but that would be a chain. So if you need to use a value from a deep chain, you need to pull it up: e.g., int size = a.getB().getC().size(); is violation. Instead, you'd add a method in B: int getCSize() { return c.size(); } and then call a.getB().getCSize(). That's still a chain of one dot? a.getB().getCSize() is one dot after a? Actually it's two method calls: getB then getCSize. That's allowed because we only have one dot after a? Actually the rule is about the number of dots in the expression. In a.getB().getC().doSomething(), there are three dots: after a, after getB(), after getC(). Actually the expression a.getB().getC().doSomething() has two dots separating method calls: a.getB() (dot), result.getC() (dot), result.doSomething(). So there are two method calls on intermediate results. In a.getB().getCSize(), we have a.getB() (dot), then getCSize() on the result. That's only one intermediate call (the getCSize is on B, not on C). So we still have a dot after a, and then a dot between getB and getCSize? Actually syntax: a.getB().getCSize() - there is a dot after a (calling getB), and then a dot after the result of getB (calling getCSize). That's two dots. Wait we need to count: In a.getB().doSomething(), there is a dot after a (calling getB) and then a dot after that result (calling doSomething). That's two dots. The Law of Demeter says that the number of dots should be at most 1? Actually typical phrasing: a method should only call methods on objects that are directly accessible: self, parameters, fields, newly created objects. That implies you should not chain calls beyond one level: object.method1().method2() violates if method1() returns an object that is not in the allowed set? Actually object.method1() is okay because you're calling a method on self. The returned value from method1() is not necessarily an immediate friend; you're allowed to call method2() on that returned value only if that returned value is itself a direct friend? Hmm, the typical rule: a method m of object o may only invoke methods on: o itself, its parameters, objects it creates, its direct component objects, or objects returned by those methods. So if o has a field b (direct component), it can call b.method(). That's fine. But if o calls b.getC().doSomething(), then the object on which doSomething() is invoked is returned by getC(), which is a method of b. b is a direct component, but getC() returns an object that is not a direct component of o; it's a component of a component (a friend-of-a-friend). So that's not allowed. So the chain a.getB().getC().doSomething() is violation because a calls getB() on itself (that's allowed: getB() is a method that returns a direct component? Actually a.getB() returns its direct component B. That's okay. But then on that returned B it calls getC(), which is a method on B. That's okay because B is a direct component of A? But wait: A is calling getB() on itself; the returned B is then used to call getC(). The call getC() is made on the B object, but who is making that call? It's the code in the context where we have a B variable. The rule about "a method m of object o may only invoke methods on objects in the following list" – when we are in the context of some method (maybe main), the object o is the one whose method we are writing. In our example, we are writing a statement that uses a. The method we are in is not part of A; it's external. So the rule applies to any method in the system. So if we have a client method that does a.getB().getC().doSomething(), that client method is invoking getB() on a (allowed because a is a parameter or local variable? Actually a is a local variable, so it's a direct reference? In the client method, a is a parameter or local variable, so it's allowed to call methods on a. Then it calls getB() on a, which is allowed because a is a direct friend. The result is a B object. Then the client method calls getC() on that B. Is B a direct friend? The client method just got B from a method call; B is not a direct friend of the client method (it was returned from a method). According to the rule, you can only call methods on objects that are either: the current object (self), its parameters, its fields, objects created within the method, or objects returned by methods of those. So B is returned by a.getB(). Since a is a parameter (or local variable), B is an object returned by a method of a parameter. That's allowed? Actually the rule says you can call methods on objects returned by methods of the parameters? Wait, typical formulation: "Each method should only call methods of: itself (this), its parameters, any objects it creates, any direct component objects (i.e., fields), and any objects returned by those." The phrase "any objects returned by those" means if you call a method on one of the allowed objects, the returned object is also allowed to be used for subsequent calls? That would permit chains? That's ambiguous. Actually there are two common formulations: one that says you can only use one dot, i.e., you should not have chains longer than one. But the original Law of Demeter says: "Each method should only interact with its immediate neighbors: itself, its parameters, any objects it creates, and its instance variables." That means you should not call methods on objects returned by other methods, except if that object is one of your immediate neighbors. Let's recall precisely. The classic LoD for OO is: For any object O, a method M of O should only invoke methods of the following kinds of objects: 1) O itself; 2) M's parameters; 3) any objects created or instantiated within M; 4) O's direct component objects (i.e., fields); 5) any objects returned by methods of (1)-(4). Some interpretations say (5) is included to allow methods that return objects that are then used? Actually I've seen both versions. The common "no train wreck" is the practical guideline: avoid a.b.c.d() chains. Some say the law permits calling methods on objects returned by methods of the allowed set, but only if you use the returned object immediately for one method call, not to continue chaining. Actually, if you call a.getB().doSomething() that's allowed because getB() returns a direct component (B), and then you call doSomething() on that B. But B is a direct component of A? It is a field of A. But we are not in A; we are in some client. The client's direct components are its own fields and parameters. The object a is a parameter or local variable, which is an immediate neighbor. The method getB() is a method of a, and it returns B. The client then calls doSomething() on B. Is B an immediate neighbor of the client? Not directly; it's returned from a call on a. According to some interpretations, you are allowed to call a method on the returned object because that returned object is considered an "object returned by a method of an allowed object". But then you could chain further: a.getB().getC().doSomething() would be a.getB() (returns B), then getC() on B (B is returned from a method call, but is it allowed to call getC() on B? B is not a direct neighbor, but it is returned by a method of a (which is a neighbor). Some sources say that's not allowed; only one level of returned objects is allowed. Actually there's nuance: The classic statement: "Only talk to your immediate friends." The idea is that you should not reach through an object to get to a third object. So a.getB() is okay because B is a friend of A. But then calling getC() on B is reaching through B to get to C. So that's violating "Only talk to your immediate friends." So the rule is: you should only call methods on objects that are directly accessible. So a.getB().doSomething() might be considered okay if you consider that you are directly using B, which is a friend of A. But you are not in A; you are in a client. The client's immediate friend is a, not B. The client obtains B from a, but B is not a friend of the client, it's a friend of a. So from the client's perspective, B is a friend-of-a-friend, so it should not be used. Many interpretations: The LoD applies to any method, not just methods of a class. So in a client method, if you have a reference to a, you are allowed to call methods on a, but not on objects returned from a's methods, because those objects are not your immediate friends. So a.getB().doSomething() is actually also a violation! Because you are calling getB() on a (allowed), but then you call doSomething() on the returned B. B is not your immediate friend; it's returned by a method of a. So that's a violation as well. That's the strict interpretation. However, many developers interpret the LoD as allowing a single dot: object.method(). Because it's common to see code like string.length() etc. Actually string is a direct object, not obtained via a method. The pattern a.getB().doSomething() is a chain of two method calls, but the first call is on a, the second is on the result. Some say that's okay if B is considered a part of A's interface? I'm a bit fuzzy. Let's recall the original definition by Karl Lieberherr, et al. The Law of Demeter for Functions says: "A function f of an object O should only call methods of O's immediate components: methods of O, O's parameters, O's fields, and objects created by f." It doesn't mention objects returned by those methods. So if you call a method that returns an object, you cannot then call methods on that returned object because that would be a second hop. However, some extended versions allow it if the returned object is a value (like a primitive) or if it's a method that is part of the interface of the immediate component? Actually, I need to check. The typical violation example is a.getB().getC().doSomething(). That's two hops beyond a. But a.getB().doSomething() is one hop beyond a? Actually a.getB() is a method call on a, returning B. Then we call doSomething() on B. That's two method calls: getB and doSomething. But the second call is on B, which is not a direct friend of a? But from the perspective of the code that does this, it's a chain of length 2 (a -> B -> doSomething). Some sources say that even a.getB().doSomething() is a violation because you're calling a method on an object returned by a method. However, many consider it acceptable because B is a direct component of A, and you're "asking" A for its component and then using it. That's still a violation of "Tell, Don't Ask"? Actually "Tell, Don't Ask" suggests you should tell the object to do something, not ask for its data and then do it yourself. So a.getB().doSomething() is asking a for its B and then doing something on B, rather than telling a to do something that involves B. So it's also a violation of that principle. But the LoD specifically targets chains of method calls. Many definitions say the allowed calls are only on the immediate object's methods, its fields, parameters, and objects created within the method. So you can call methods on a's fields directly if you have access. But if you have to go through a getter, that's still a method call on a, but then using the returned value as a receiver for another call is another hop. But if you have direct field access (like a.b.doSomething()), that's still two hops? Actually a.b.doSomething() - a.b is a field access, not a method call. Then .doSomething() is a method call. That's one method call, but two navigation steps. The LoD is often expressed in terms of "dots" in method calls: you should not have more than one dot per statement. That means you cannot have a.b.c.d(). Actually a.b is not a method call; it's field access. But many languages treat field access similarly. The principle says: "For any method, the code should only use methods of the object itself, its parameters, objects created in the method, and its direct fields." So if you have a reference to a, you can directly access its field b (if it's accessible) and call b.doSomething(). That would be a field access (b) and then a method call (doSomething). That's two steps, but the rule is about method calls on objects that are not immediate. Actually if you have a field b, then b is an immediate part of a. But if you are in a method that only has a reference to a (like a parameter), you might not have direct access to a's field because it's private. So you would need to call a.getB() to get b. That's a method call on a, but the returned b is not a field of your current object, it's a field of a. You are then using b. That's like accessing a's internals. The LoD says you shouldn't do that; instead you should tell a to perform the action itself. So the ideal is: a.doSomething() where doSomething() in A internally uses b. So the client never sees b. That's the fix: move the behavior to the object that owns the data.
So perhaps the refactoring should be: add a method in A that does what the original chain does, and call that. That's more in line with the principle: the client only talks to A, not to B or C. So the chain a.getB().getC().doSomething() becomes a.performTask() where performTask() is implemented by A using its B and C. That eliminates the chain entirely. That's a stronger refactor. But we could also do intermediate: add method in B that does the C work and have A call that, but still A knows about B. But the principle says A should only talk to its immediate friends. If A knows about B, that's okay because B is a direct component of A. But if the client knows about B, that's not okay. Actually the client is some other class. Let's define the scenario: We have an object a of class A. Some other class Client wants to make something happen that involves C. The client currently does a.getB().getC().doSomething(). This violates LoD because Client knows about B and C. The fix: move the responsibility to A, so Client does a.doSomething() and A internally coordinates with B and C. That reduces coupling between Client and B/C. Alternatively, if we want to keep Client's knowledge limited to B but not C, we could add a method in B that does C's job and have Client call a.getB().doSomething() but that still exposes B. If B is a direct component of A and we want to hide B too, maybe we should not expose B at all. So the best is to not expose internal structure: don't have getB() at all, or make it private. But if the design requires exposing B (e.g., for other reasons), then maybe it's okay to call B's methods. But the Law of Demeter is about any method; it doesn't care about the class of the method. So if Client's method does a.getB().doSomething(), it's still two hops: a -> getB() -> doSomething on returned B. That's considered a chain of length 2? Actually it's two method calls: getB on a, then doSomething on the result. So it's a chain of length 2? But if B is a direct component of A, is it allowed to call methods on B? According to the strict definition, the allowed objects are: the current object (Client's this), its parameters (a is a parameter), and objects created within the method. B is not the current object; it's not a parameter (a is the parameter); it's returned by a method call on a. So it's not directly allowed. However, some argue that if B is a "part" of A, it's okay to use it after obtaining it via a getter. But the original Demeter paper says: "We want our objects to be independent of the internal structure of other objects." So if we call a.getB(), we are making our code dependent on the fact that A contains a B. That's already some coupling. But the chain a.getB().doSomething() still depends on B's interface. So it's not ideal.
But many sources show the simplest violation as a.getB().getC().doSomething() and the fix as a.getB().doSomethingOnC() by moving the method to B. They also accept that a.getB().doSomething() may be okay if B is a direct component and you have to use it, but the principle encourages that you tell the object to do it.
Let's check typical resources: Wikipedia: "The Law of Demeter (LoD) or principle of least knowledge is a design guideline for developing software, particularly object-oriented programs. In its general form, the LoD is a specific case of loose coupling. The guideline states that a given object should only interact with a limited set of objects: its own instance variables, parameters passed into the method, any objects it creates, and its immediate component objects (i.e., its fields). The set does not include objects returned by methods of other objects that are not parameters, unless those objects are also immediate components." Actually the exact phrase: "The phrase 'only talk to your immediate friends' is often used to describe the principle." They give the formal specification: "A method M of an object O should only call methods of the following kinds of objects: 1) O itself; 2) M's parameters; 3) any objects it creates/instantiates; 4) O's direct component objects; and 5) any objects returned by methods of (1)-(4)." Wait, Wikipedia version includes (5): "any objects returned by methods of (1)-(4)". That would allow chaining? Actually (5) says you can call methods on objects returned by methods of (1)-(4). That sounds like you can chain, but only one level: you can call a method on the returned object, but you cannot then call another method on the result of that because that result would be returned by a method of an object that is not in the original set? Let's think: If you call a.getB(), a is O (1). getB() is a method of O. The returned object B is then an object returned by a method of (1), so it's allowed to be used as a receiver for a method call. But then if you call getC() on B, B is not in (1)-(4) originally; B is allowed because it was returned by a method of (1). But then getC() is a method of B, which is in the allowed set because B is an object returned by a method of O. Then the result C is returned by a method of an allowed object (B). But is B considered a kind of object that is allowed to have its methods called? Yes, because B is returned by a method of O, so B is in the set? Actually the set includes "any objects returned by methods of (1)-(4)". That means after a call to a.getB(), B is now an object that is in this set. So you can call methods on B. Then if you call B.getC(), that's a method of B, which is allowed because B is in the set (returned from a method of O). Then the result C is returned by a method of B, and B is in the set, so C is also an object returned by a method of an allowed object (B). So you could then call C.doSomething(). That would be allowed by the formal rule if it includes recursive chaining? Actually (5) says "any objects returned by methods of (1)-(4)". It doesn't say you can continue recursively. But if you think about it, after you get B, B becomes an object you have. But is B considered a "direct component object"? No. It's returned by a method of O. So B is in the set. Then you call a method on B, which is allowed because B is in the set. That method returns C, which is then returned by a method of an allowed object (B). So now C is also an object returned by a method of an object in the set, and thus allowed? That would lead to unlimited chaining, which defeats the purpose. So I think the proper interpretation is that the set of allowed objects is dynamic: when you obtain a new object via a method call from an allowed object, that new object is allowed for a single further call? Actually the original Demeter paper likely had a more limited phrasing: "Only use methods of the following: the current object, method parameters, objects created within the method, and direct component objects." It explicitly excludes objects returned from other method calls. The version with (5) is a later refinement? Let's check my memory. I recall that the canonical LoD statement is: "A method M of an object O should only call methods of the following objects: O itself, M's parameters, O's fields, and objects created by M." No mention of returned objects. This is the strict "no chains" rule. However, some sources include "objects returned by those methods" but they often mean that you can use the result, but not call further methods on it? Actually, it's ambiguous. Let's check a reliable source: In "The Pragmatic Programmer", they mention "The Law of Demeter" and say: "For any object, the methods of that object should only call methods of: itself, its parameters, any objects it creates, and its direct component objects." That's it. They also show a chain example: a.getB().getC().doSomething() is violation. They suggest refactoring by moving the call into one of the objects. They don't mention that a.getB().doSomething() is acceptable, but it's still a chain of length 2 if you count method calls. Actually a.getB().doSomething() is a chain of two method calls: getB and doSomething. That would be violation if you cannot call methods on returned objects. But is it? Many would say you should avoid that as well. But the rule as stated would forbid it because doSomething is called on B, which is not one of the allowed objects: it's returned by getB, which is a method of a, but B is not a direct component (field) of the current object (the method's receiver). So it's not allowed. However, some practical implementations of LoD check the number of consecutive method calls: they allow at most one dot. That would allow only one method call on the receiver, like a.doSomething(). It would not allow a.getB().doSomething() because that's two calls. But that's a stricter interpretation: no chaining at all. But I've often seen LoD described as "don't use more than one dot" i.e., avoid chains like a.b.c.d() but a.b is okay? Actually a.b is not a method call; it's a field access. So one dot would be a.b.c? That's two dots: a.b then .c. That's two. So "one dot" means you should not have more than one dot in a row? The typical adage is "If you see more than one dot, you're probably violating the Law of Demeter." So a.b.c.d would be three dots. a.getB().doSomething() has two dots (after a, after getB). That's two. That would be more than one dot. So even a.getB().doSomething() might be considered violation if you strictly adhere to "no more than one dot". But I've seen examples where they say that a.getB().doSomething() is okay because getB returns a direct component? Actually I need to recall typical teaching. Let's think: In Java, you often have getters that return other objects. If you call object.getFoo().getBar().baz(), that's clearly a chain. But if you call object.getFoo().bar(), that's also a chain of two method calls. Many style guides would flag that as a chain. I think the LoD says it's not allowed. But in practice, sometimes it's allowed if getFoo() is just a simple accessor and the returned object is part of the object's responsibility. But the principle encourages you to move behavior to the object that holds the data. So you'd have object.doSomethingWithFooBar() instead.
Thus our refactoring should ideally eliminate the chain entirely. So we could have class A provide a method that does the work: a.performTask() which internally gets B and C and calls doSomething(). Then the client just calls a.performTask(). That's the cleanest.
But the user specifically says: "provide a code example that violates the law (e.g., a.getB().getC().doSomething()), and show how to refactor the code to adhere to the principle." So they gave an example with three objects. We can provide a similar chain. For refactoring, we could either move the operation to A, or to B, depending on where the knowledge resides. Both reduce coupling. But I'll show both possibilities: either add a method in B that delegates to C and then have A.getB().doSomethingInC(), but that still exposes B. Better to add method in A that directly does the job without exposing B and C. But that may not be possible if we need to use C from multiple places. But we can also have A have a method that uses B internally. That's fine.
I think the typical demonstration is: we have a chain, and we refactor by adding a method to the object that is the start of the chain (A) that encapsulates the whole operation. For example:
class Order {
private Customer customer;
// getter
public Customer getCustomer() { return customer; }
}
class Customer {
private Address address;
public Address getAddress() { return address; }
}
class Address {
public void printLabel() { ... }
}
// Violation:
order.getCustomer().getAddress().printLabel();
Refactor:
class Order {
// other stuff
public void printShippingLabel() {
customer.getAddress().printLabel();
}
}
Then client does order.printShippingLabel();
That reduces coupling: client doesn't know about Customer or Address.
Alternatively, we could have Customer provide printLabel() that uses its address, and then call order.getCustomer().printLabel(). That's a shorter chain (order.getCustomer().printLabel()), still one dot after order? Actually order.getCustomer().printLabel() has two method calls: getCustomer and printLabel. That's still a chain of length 2. According to LoD, that's still violation because client is calling printLabel on Customer, which is returned by getCustomer. So it's not fully adhering. But maybe if we consider that Customer is a direct component of Order and we allow that? Many say that order.getCustomer().printLabel() is also a violation because you're reaching through order to get customer and then telling it to print. The tighter principle is to ask order to print the label itself. So order.printShippingLabel() is the best.
Thus I'll go with that.
I'll produce code with three classes: A, B, C. And a client class Main. Show the violation in Main. Then refactor by moving the operation to A. I'll also show how B and C remain unchanged but A gets a new method. Or we could also refactor by making the chain shorter but still some exposure. I'll present the clean version.
But the user may want the refactoring to show only one step: "refactor the code to adhere to the principle." They didn't specify which way. So I'll choose the typical solution: add a method in A that encapsulates the call to C, thus the client only talks to A.
I'll also mention the principle of "Tell, Don't Ask" as part of the solution.
Thus my answer:
-
State LoD: "Each method should only interact with its immediate friends: itself, its parameters, any objects it creates, and its direct component objects (fields)."
-
Goal: reduce coupling, increase encapsulation, make code more maintainable and robust to changes.
-
Code example (before):
class A {
private B b;
public B getB() { return b; }
}
class B {
private C c;
public C getC() { return c; }
}
class C {
public void doSomething() { System.out.println("Doing something"); }
}
// Client code:
A a = new A();
a.getB().getC().doSomething(); // violation
class A {
private B b;
public B getB() { return b; }
public void doSomethingThroughC() {
// Delegate to B, or directly use c?
b.doSomethingThroughC(); // if we add in B
// Or better: we can do it directly if A has access to c? But to keep encapsulation we should not expose c.
}
}
class B {
private C c;
public C getC() { return c; }
public void doSomethingThroughC() {
c.doSomething();
}
}
// Now client code:
a.doSomethingThroughC(); // no chain
But note that client still calls a.doSomethingThroughC(), which is one method call. That's good. However, we added a method in B as well, so now B knows about C, but that's fine because B owns C. The client only knows about A.
Alternatively, we could simplify: add in A:
class A {
private B b;
private C c; // maybe not, if only B has C.
// Actually A could directly use B's internal C if it had access, but better to keep B's encapsulation.
public void doSomething() {
b.getC().doSomething(); // But that's still a chain inside A, but that's internal to A; LoD applies to A's methods as well. So A's method should also not chain. So we need to fix A's method as well. So the method inside A should also adhere to LoD. So if we implement doSomething() in A as b.getC().doSomething(), that's a chain of two in A's own method, which is also a violation. So we need to either give A a direct reference to C (which might be bad) or have B expose a method that does C's job. So B should have doSomethingInC() and then A can call b.doSomethingInC(). That's just one dot after b. So A's method would be:
public void doSomething() {
b.doSomethingInC();
}
That's okay: inside A, we call a method on its direct component b. So that's allowed.
Thus the refactoring: add method in B that delegates to C, and add method in A that delegates to B. Then client calls a.doSomething(). This way, no method contains a chain of more than one dot.
We could also have A's method directly call c.doSomething() if we expose c? Not good.
Alternatively, we could move the whole operation to B and have A getB().doSomething() but then client still calls a.getB().doSomething(), which is a chain of two in client. So we need to ensure the client doesn't chain either. So the refactoring should be: The operation that originally required navigating through A, B, C should be encapsulated in a method in A (or perhaps a new mediator) so that the client only calls a method on A. This is the typical guideline.
Thus we should show:
Original chain in client: a.getB().getC().doSomething();
After refactor: we add to A a method:
public void performTask() {
// Implementation that uses b and c internally without chaining
// Since A has a direct reference to B, it can call b.performSubTask() where B has method that uses C.
b.performTaskWithC();
}
And in B:
class B {
private C c;
public void performTaskWithC() {
c.doSomething();
}
}
Now client simply calls a.performTask();
But note: inside A's performTask, we call b.performTaskWithC(). That's a single call on b. Good. Inside B's performTaskWithC, we call c.doSomething(). That's a single call on c. So no method has more than one dot.
Thus the chain length across multiple objects is reduced to a single call at each level, and the client only deals with A.
We should also discuss that if the operation is something that C does and B or A are just containers, maybe the operation belongs to C. But the point is to hide the structure.
Thus answer:
- Definition
- Goal
- Example: define classes and show violation
- Refactoring steps: add methods to appropriate classes to encapsulate the chain; show code
- Explain how this reduces coupling: client no longer depends on B and C; changes in B/C won't affect client.
Also mention that sometimes returning value from deep chain can be handled by adding a method that returns that value.
I'll write the answer in a clear, structured way.
Let's outline:
1. The Law of Demeter (LoD) or Principle of Least Knowledge:
- Also known as "only talk to your immediate friends."
- Formal statement: A method of an object O should only invoke methods of: O itself, O's parameters, objects O creates, O's direct component objects (fields), and (in some formulations) objects returned by methods of the above. (Strictly, to avoid chains, we limit to these without further dispatch.)
But the common practical version: Avoid sequences of method calls longer than one dot: `a.getB().getC().doSomething()` is a code smell.
2. Goal:
- Minimize coupling between objects.
- Increase encapsulation: objects hide their internal structure.
- Improve maintainability: changes inside a class won't ripple through the system.
- Make code more robust and easier to understand.
3. Violation example: Provide code in Java (or a generic OOP). We'll define classes A, B, C as above. In a client class, we call a.getB().getC().doSomething(); which is a chain of three method calls (or two intermediate hops). This violates LoD because the client knows about the internal structure of A (that it contains a B) and B (that it contains a C). It also directly uses C's behavior.
4. Refactoring:
- We move the responsibility of coordinating with C to B, and responsibility of coordinating with B to A.
- Add a method in B that performs the operation on C: `void performTask() { c.doSomething(); }`
- Add a method in A that delegates to B: `void performTask() { b.performTask(); }`
- The client now simply calls `a.performTask();`
- Alternatively, if the operation logically belongs to A, we could add in A a method that internally uses B's method, but ensure no chaining inside A's method: call b.performTask() (as we did).
- This adheres to LoD: each method only interacts with its immediate friends.
- Optionally, we could also remove the getters if they are not needed externally, or make them package-private, further reducing exposure.
5. Explanation: After refactoring, the client depends only on A. If the internal structure of A (like B) or B (like C) changes, the client code remains unaffected. The coupling is reduced, and each class encapsulates its own collaborators.
We could also show a diagram.
We'll produce the answer with code blocks and explanation.
Now, I'll write the final answer accordingly.</think>
**Law of Demeter (Principle of Least Knowledge)**
The Law of Demeter (LoD) – also known as the *Principle of Least Knowledge* – is a design guideline that aims to reduce coupling between objects. It states that a method of an object should only interact with a limited set of objects:
- The object itself (`this`)
- The method’s parameters
- Objects created or instantiated inside the method
- The object’s direct component objects (usually its fields)
- *(In some formulations) Objects returned by methods of the above objects, but only for a single further invocation.*
A more colloquial phrasing is **“only talk to your immediate friends.”** In practice, this means avoiding long chains of method calls like `a.getB().getC().doSomething()`. Such a chain exposes internal structure and leads to tight coupling.
**Goal**
- **Reduce coupling**: Clients depend only on the immediate collaborators they need.
- **Increase encapsulation**: Objects hide their internal structure; only the necessary behavior is exposed.
- **Improve maintainability**: Changes inside a class or its sub‑structure do not ripple through the codebase.
- **Make code easier to understand** and less fragile.
---
### Code Example That Violates the Law of Demeter
```java
class A {
private B b;
public B getB() { return b; }
}
class B {
private C c;
public C getC() { return c; }
}
class C {
public void doSomething() {
System.out.println("Doing something");
}
}
// In some client code:
A a = new A();
a.getB().getC().doSomething(); // Violation: long chain of calls
Here the client reaches through A to obtain B, then through B to obtain C, and finally invokes behavior on C. The client is now coupled to the internal structure of both A and B.
Refactoring to Adhere to the Principle
We move the operation up the chain so that each class only talks to its immediate friend. The client will eventually call a single method on A. Inside A, we delegate to B; inside B, we delegate to C.
class A {
private B b;
public B getB() { return b; } // may be kept if other code needs B
// New method that encapsulates the whole operation
public void performTask() {
b.performTask(); // one call to a direct component
}
}
class B {
private C c;
public C getC() { return c; } // may be kept if other code needs C
// New method that performs the work using C
public void performTask() {
c.doSomething(); // one call to a direct component
}
}
class C {
public void doSomething() {
System.out.println("Doing something");
}
}
// Client code after refactoring:
A a = new A();
a.performTask(); // Single, well‑named call; no chain
Why does this fix the violation?
- The client now depends only on
A. It no longer knows about B or C.
- Inside
A.performTask(), the only object we call a method on is b, which is a direct field (an immediate friend).
- Inside
B.performTask(), we call c.doSomething(); c is a direct field of B.
- No method contains a chain of two or more “dots”; every call is made on an immediate collaborator.
If the getters (getB(), getC()) are not required elsewhere, they can even be made package‑private or removed entirely, further reducing exposure.
Additional Remarks
- The Law of Demeter is a guideline, not an absolute rule. There are acceptable exceptions (e.g., simple data‑transfer objects, builder patterns, or when dealing with immutable value objects). However, long chains should be treated as a code smell.
- The principle is closely related to Tell, Don’t Ask: instead of “asking” an object for its data and then operating on that data, you “tell” the object to perform the requested action itself.
- Applying LoD leads to more robust designs where internal changes (e.g., replacing
C with a different implementation) only affect the immediate neighbor, not the entire call chain.