I just recently became aware of the Law of Demeter.
Like a lot of things, I realized that it was something that I was already doing but did not have a name for. There are a few places though that I seem to violate it.
For example...
I might have an Address object:
public class Address : IAddress
{
public string StreetAddress { get; set; }
public string City { get; set; }
public int Zip { get; set; }
}
and a Customer object:
public class Customer : ICustomer
{
private IAddress address;
Customer()
{
Address = null;
}
public string Name { get; set; }
public IAddress
{
get
{
if (address == null)
{
address = new Address();
}
return address;
}
set
{
address = value;
}
}
}
Ok, this is fake code so you probably do not have to jump on me to use IoC to eliminate the new Address()
or anything but it is pretty much an example of what I am doing. I did not include the interfaces as I am hoping they are obvious.
I would then use it in my code for stuff like int zip = customer.Address.Zip;
and customer.Address.City = "Vancouver";
As I understand it, I am violating the Law of Demeter by manipulating details of Address from Customer.
Then again, it seems like the framework does as well. After all, wouldn't address.City.Length be a violation? Should I be adding methods to Address to handle accessing string properties? Probably not. So, why clutter up Address?
I cannot really just add methods to Address that relate only to customer. I have Member, Employee, Dependent, Vendor, Employer, etc. objects that all have addresses too.
Is there a better way to handle this? What kinds of problems am I risking if I use Address the way I am now?
For the Java folks, the Address class might look something more like the following if it helps:
public class Address extends AddressInterface
{
private String m_city;
public String getCity() { return m_city; }
public void setCity(String city) { m_city = city; }
}
I must admit that customer.getAddress().setCity("Vancouver");
rings more alarms than customer.Address.City = "Vancouver";
did for me. Maybe I should switch to Java for a while.