Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

13. Programming Principles > Law of Demeter

Law of Demeter

Unfortunately, the LAW OF DEMETER has nothing to do with the Goddess of the harvest. It’s named for the Demeter Project at Northwestern University where it was developed. It’s also known as the PRINCIPLE OF LEAST KNOWLEDGE (but that’s not nearly as much fun, is it?)


Law of Demeter

image

An object should only reference its own members, and the members of objects it instantiates directly.


Like the OCP, the Law of Demeter addresses the issue of coupling between classes. It states, essentially, that you should only talk to the objects you instantiate, not the ones they instantiate. Let’s look at an example:

image

According to the Law of Demeter, it would be legal to do any of these things in MyClass:

aFriend = new MyFriend();
aFriend.aFriendlyProperty = 3;
aFriend.aFriendsFriend = new aFriendsFriend();


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free 10-Day Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint