nus-cs2103-AY1920S1 / forum

Forum
1 stars 1 forks source link

Clarification for Law of Demeter #188

Closed Sahilgat closed 4 years ago

Sahilgat commented 4 years ago

Hi, can I check why the example given in the lecture below does not violate Law of Demeter while the second screenshot given below that in the textbook does violate the law? 1 2 Based on my understanding, it's because b.getGoo() method in the textbook may not be creating a new Goo object in the getGoo() method. Am I right to say if getGoo() creates a new Goo object which it returns, will it not violate the Law of Demeter (based on the example in the lecture)?

LiuZechu commented 4 years ago

If I'm not mistaken, the Law of Demeter is violated if you access an object in the internal structure of what the method receives as a parameter. In the lecture's example, the Label object doesn't reside in i's internal structure, but instead it's newly created. I think what you mentioned about "if getGoo() creates a new Goo object which it returns, will it not violate the Law of Demeter" is right.

However, a method that looks like getSomething() is probably a getter method that returns an attribute of the object being called.

damithc commented 4 years ago

Both @Sahilgat's initial speculation and @LiuZechu's answer are correct 👍 It's based on the assumption that getGoo() is returning an internal object rather than a new object.

Sahilgat commented 4 years ago

Thanks for the clarification!