Understanding Law of Demeter

During my studies of object-oriented programming and good practices, one law/practice has gained my attention, and this was the Law of Demeter (LoD). But why this law has gained my attention so easily? Simple, when I read the principles of LoD I remembered a lot of codes, that I have coded that breaks this law.

Check my last post:

What is?

Short Answer) – Basically LoD says that your object can only talk with their neighbors. On some OOP languages, for simplifying just think “Use only one dot”.

The Law of Demeter (LoD) is a design guideline that was proposed by Ian Holland in 1987. Remember when your mom told you to not talk with strangers? It’s almost the same, but with your objects.

Imagine that you have an object, this object can only talk with your methods, or with your neighbors, you should avoid the call method of an object returned by another method. At programming languages that use dot as field identifier, you can simply use the law of “use only one dot”.

For example, the following code breaks the law, and throw it in the trash:

class Book
  ..
end

class ExampleClass
  def show_book_author_name
    book.author.name
  end

  ...
end

The fallowing code shows the most common way to not break the law:

class Book
  def author_name
    author.name
  end

  ...
end

Benefits

It’s simple, fast and brings many benefits to your code health. The benefits of fallow this law is:

  • You decrease dependencies of your class (loose coupling)
  • Your code is more adaptable and maintainable

And remember less coupling, less chance of breaking your application. It’s always good avoid problems.

Caution

Spread the rule on your project doesn’t work, sometimes your design is wrong, and law of demeter will not save your project of dependencies problem, you may just be changing the place of the problem.

Ending

That’s all for today folks, don’t forget to follow my blog and my twitter.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: