javascriptclasscoding-stylelaw-of-demeter

Law of Demeter - is it really communicating only to friends?


I read some article on Law of Demeter and it gets me confused.

It states that something like this:

var width = mapControl.get_mapState().getMapRange().getSize().get_width();

Should be replaced by this:

var mapState = mapControl.get_mapState();
var mapRange = mapState.get_mapRange();
var width = mapRange.get_width()

I am a little confused here cause the latter one is just the same as the first one but written differently. In both cases I am eventually accessing "width" which is not a direct friend of my current class.

So why is the second way really better?


Solution

  • I am a little confiused here cause the latter one is just the same as the first one but written differently. In both cases I am eventually accessing "width" which is not a direct friend of my current class.

    So why is the second way really better?

    It's not really better. A Law of Demeter approach would be to refactor the code, so the client code looks like this:

    var width = mapControl.get_width();
    

    In this case, client code doesn't need to know that mapControl has a "state", which has a "range", which has a "width". It just needs to know it exposes a "width".