1

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
RobertPorter
  • 542
  • 6
  • 16

1 Answers1

1

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".

Community
  • 1
  • 1
utnapistim
  • 26,809
  • 3
  • 46
  • 82