Delegation and law of demeter

Suppose User has a address and address has a street name so instead of doing user.address.street_name we apply delegate: :street_name,to: :address.

How is this following the law of demeter? Doesnt user object still know that it has to go through the address to find the street_name?

1 Like

The law of demeter says that if you have A that calls B which has C, A should not know C.

In your example whoever’s calling user.address.street_name, probably a view, is A. The user is B, and the address is C.

street_name is a field on the address, so the user, being a neighbour of the address, can access it without violating the law of demeter.

1 Like

The view is A? Then the view is trying to access the C, isnt that a violation?
And if street_name was an object of another class then will user be violating the law?

Unless you delegate it somehow, it is violating. The view can know that the user has an address, it should not know how many layers are between the user and it’s address.

If street_name was an object, you’d probably have to call a method on it, like:

In this example the user would be violating the law of demeter, it should know that the address has a street_name, bu should not care where it comes from.

1 Like