The Law of Demeter

8 07 2011

The Law of Demeter for functions states that any method of an object should call only methods belonging to:

  • itself
  • any parameters that were passed in to the method
  • any objects it created

Following the Law of Demeter tends to result in more maintainable and adaptable code. Since objects are less dependent on the internal structure of other objects, object containers can be changed without reworking their callers.

class Book
    public String Title { get; set; }
    public int NumCopies { get; set; }

    private void SaveDetails(BinaryWriter writer)
        StringBuilder details = new StringBuilder();

        details.Append(Title);             //method that belongs to Book
        details.AppendLine();              //details was created by SaveDetails
        details.Append(NumCopies);         //method that belongs to Book

        writer.Write(details.ToString());  //writer is a parameter that was passed in to SaveDetails



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: