Don’t break the law of Demeter

…Or the OO cops will get you. The best summary of the law of demeter I saw was from c2.com. It goes something like this:

You can play with yourself.
You can play with your own toys (but you can’t take them apart),
You can play with toys that were given to you.
And you can play with toys you’ve made yourself.

That’s it. To recast in geek-speek:

An object can call its own methods.
An object can call methods on its own fields. (But not on it’s fields’ fields)
An object can call methods on parameters passed to it.
An object can call methods on objects it has instantiated.

That’s it. You can’t call methods on the fields of other objects. So anything that looks like foo.getBar().getBaz().doSomething() is not allowed. What you can do is add a method to foo called ‘doSomething’ which delegates to a method on its ‘bar’ field called ‘doSomething’ which delegates to its ‘baz’ field. That doesn’t break the law, because it prevents foo’s caller from knowing about bar and baz, and foo from knowing about baz.

Its all about preserving encapsulation.

If you take it to the extreme you find that getter methods break the law of demeter. Ask yourself why other objects need to get at your object’s fields. Can’t they just tell your object what they want it to do directly? Setter methods aren’t much better. They still expose an object’s state to the world.

Advertisements

One thought on “Don’t break the law of Demeter

  1. I have been known to go through phases where I’m REALLY anal about this. I’ve even gone so far as to replace getXXX() methods which are there “just for testing, guv”, with hasXXX( expected ) methods, which really ARE just for testing.

    this version:

    long lastMod = newsEntry.getLastModifiedTime();
    assertEquals( 123, lastMod );

    could be used for more than testing, but:

    assertTrue( newsEntry.hasLastModifedTime( 123 ) );

    certainly can’t šŸ™‚

Comments are closed.