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

Class Names and Method Names

7 07 2011

The naming of “things” in software is important. It’s important because it is everywhere. Variables, functions, arguments, classes, source files and directories all require names and tell a story of how the code works. In order to be useful names must be meaningful. When I say meaningful I mean a name should reveal the intent of that entity, its reason for existence. Creating meaningful names is harder than it sounds but in class and method naming there are some simple rules of thumb you can follow.

Classes and objects should have noun or noun phrase names like Customer, Book, AddressParser and CustomerComparer. Avoid words like Manager, Processor, Data, or Info in the name of a class, they don’t mean anything. A class name should not be a verb. Methods should have verb or verb phrase names like Save, Listen, or CompareDetails.