Thursday, February 21, 2008

Encapsulation or Law of demeter

When I was designing a C# class to do some work, I had a design choice to choose between a dictionary to be returned or not from a Utility class. My requirement was that I needed a dictionary to be used wherever this Utility.Function class is called. I found an nice and interesting article by Thomas Johansson at http://tomas.oo-systemutvecklare.se/articles/encapsulation.php.

The Law of Demeter as defined in Wikipedia suggests that a Method say M of an Object obj will have access to only the following.
  1. The object obj
  2. Method's parameters
  3. The fields of the object
  4. The variables declared inside the method
Reflecting on what could be the advantages of the approach, let us assume that we have a File maintenance project in which we keep a List and we allow all others to modify this field freely.

public class MyNonEncapsulatedClass
{
public List stringvalues;
}

This obviously leads to a dependency issue. If I want to now convert this class to use a Dictionary because it offers some additional advantages, then we have a problem. Had we kept this as a private field with only the object's functions modifying it, we can choose to return the old type without breaking any code which depends on this.

public class MyNonEncapsulatedClass
{
private Dictionary stringvaluesDictionary;

public List ReturnList()
{
return new List(stringvaluesDictionary.Values);
}
}

Ofcourse there is other option of using immutable keyword.

Any comments?

No comments: