nus-cs2103-AY2021S1 / forum

20 stars 2 forks source link

Is this a violation of Law of Demeter? #355

Open damithc opened 4 years ago

damithc commented 4 years ago

[Question received from a student]

Can I ask if this is a violation of LoD? I was wondering if default java methods should be considered a violation of LoD such as toString or even Streams, which relies on method chaining heavily.

There is a class A which has an Item instance variable. B has a method:

test(A a) {

   a.getItem().toString();

}
GeNiaaz commented 4 years ago

I should think that the A class could have another dedicated method like getItemStringVal().

Though on balance, it may be impractical to implement that especially if there are many such method calls for a lot of attributes. So maybe this is the ideal way to do it since it would eliminate the need for potentially double the methods in the A class.

I'd guess that the right call here is to simply be consistent with either path chosen while considering the architecture of the over all program.

damithc commented 4 years ago

The purpose of the LoD is to prevent one object from knowing internal details of other objects that it comes into contact with. One thing special about this example is that toString() is a method all objects have i.e., it is an internal detail that is already known

GeNiaaz commented 4 years ago

Ahhh i see, time to refactor my own code then

damithc commented 4 years ago

Ahhh i see, time to refactor my own code then

Well, this is a special case where an exception can be made to the LoD. But it is OK (even preferred) to not treat it as a special case and apply the principle anyway. A bit of verbosity may be an acceptable price for better consistency. It's better to avoid special cases because every special case adds to the cognitive load of future maintainers.