Skip to content

Code Design Guidelines

These are ideas re. code design that I've come across:-

Reducing Coupling

Law of Demeter

wikipedia.org/wiki/Law_of_Demeter

The Law of Demeter summarized:

  • Each unit should have only limited knowledge about other units: only units "closely" related to the current unit.
  • Each unit should only talk to its friends; don't talk to strangers.
  • Only talk to your immediate friends.

In object oriented programming:

An object a can call a method of an object b but object a should not reach through object be to access another object c. Doing so would mean that a implicitly requires greater knowledge of b's internal structure.

More formally, with a method m of an object a, m may only invoke:

  • a
  • m's parameters
  • a's attributes
  • global varibles accessible by a in the scope of m

An object should avoid invoking methods of an object returned by another method.

An analogy for the Law of Demeter is; when you want a dog to walk, you ask the dog to walk, not each of the legs of the dog.

Tell Don't Ask

It's better to tell an object to do something, rather than interrogate the object about it's state and then decide whether to perform an action on the object. By 'telling' rather than 'asking' this means that you don't need to know as much about the object's internal structure.