nabilunfarhanun's avatar

Law of demeter.

I am new to programming and got introduced to the law of demeter. I am having trouble understanding it.

For example, I have developed a ecommerce related page. In that page, a list of product will be showed with its supplier address. Naturally only supplier's id is in the product page.

So, my solution was to show it like this, {{$product->supplier->address()}}

The product and supplier relation was defined well. So the output was working without any problem.

However, one of the fellow developers suggested I should use something like, {{$product->supplierAddress()}}. And from inside the supplier function I should ask the supplier in question to return it's address.

I understand the idea behind the law of demeter is to create loose coupling. But I feel like still the product object and supplier object are still related to each other.

My question is two fold. Is the other solution better and follow the law of demeter? If yes, then can you provide a scenario where my code will be problematic and not adaptable to change?

Thanks in advance

0 likes
1 reply
JohnBraun's avatar

If you're new to programming, my advice would be to focus on other things first. These "laws" are things you can worry about later. First get things working and slowly improve your code style along with your learning curve.

My question is two fold. Is the other solution better and follow the law of demeter? If yes, then can you provide a scenario where my code will be problematic and not adaptable to change?

In this case, I don't really feel like it would matter and it completely depends on the preferences within your company/team.

However, maybe my view is too simplistic.

Please or to participate in this conversation.