The Law of Demeter's Confusion in Java

Am I breaking the Law of Demeter? For example, I create a person of a class that contains a name, phone and ID, and it corresponds to a column in my database. When I want to fill out my order information using a user ID. I like it.

public static void fill(Order order) { DatabaseComponent databaseComponent = new DatabaseComponent(); Person person = databaseComponent.getById(order.getUserId()); order.setName(person.getName()); order.setPhone(person.getPhone()); } 

I use getName and getPhone return by databaseComponent. This breaks the LoD. Someone would recommend that I do this

  public void fill(Order order) { DatabaseComponent databaseComponent = new DatabaseComponent(); Person person = databaseComponent.getById(order.getId()); fillOrder(order,person); } private void fillOrder(Order order,Person person){ order.setPhone(person.getPhone()); order.setName(person.getName()); return; } 

But I think that in the public method, it still interrupts LoD. Some people use this method.

 public class Util { public static void fillOrder(Order order,Person person){ order.setPhone(person.getPhone()); order.setName(person.getName()); return; }} 

Yes, maybe this will not break LoD. But why? Maybe the Client is not associated with the Person.But class, it is associated with Util. What are the benefits of LoD in this case.

+5
source share
1 answer

LoD says:

More formally, the Demeter Law for functions requires that the method m of an object O can only call methods of the following types of objects: [2]

O myself

m parameters

Any objects created / created in m

O direct component objects

Global variable accessible by O in area m

You create objects in your method (order and person); and then you invoke methods on them. Or, to be precise: you create one and instantiate the other.

It seems to me good - there is no LoD violation here.

I would rather worry about what to tell do not ask here. You get all these properties of the Person to push them to the Order. Why not use an order class method like public void setRecipient(Person p) or something like that?

On the other hand, this may mean a violation of the sole responsibility of the Order. In this sense, your code may still be fine, for example, if it can be found in some support class SetupOrderService .

+4
source

Source: https://habr.com/ru/post/1271841/


All Articles