Monday, September 8, 2008

Law of Demeter’s, or please count your dots.

The “Law of Demeter” says that a method “M” should only invoke the methods of the following kinds of objects:

· Itself;

· Its parameters;

· Any object it creates;

· Its direct component objects.

When programming C# if more than two dots (excluding the this.) are typed then this law is broken. The study that gave birth to this law arguments that complying to it enhances the maintainability of the system being developed.

It is easy to empirically understand why, the more dots we enter the more details about how an object is built are we revealing and therefore increasing the possibility of breaking something when we change something of that implementation.

I read a lot of code and most people just ignore this problem, I used to as well. Now I break the rule a couple of times a day but I always do it after thinking a couple of seconds about what could I do to respect it. Most of the times it starts by increasing by one the number of arguments of a class constructor and replacing the class by a contract (abstract class or interface).

Why? Well if you can use this.a.b.c then you have set a reference to a contract that represents what c does in your current class. Imagine you do this all the time. Now imagine you replace you c’s contract by a Mock object. Its really easy to test… ;)

If once adding arguments to a constructor was putting effort into the guy that is going to create instances of it, today with the latest enhancements in dependency inversion and dependency containers it is not that bad.

Most containers also support injection in the instance properties and so there is a lot to win on following this simple principle and it is really not that hard. Please read on the article on containers to get your hands dirty.

No comments: