Skip to content

Instantly share code, notes, and snippets.

@OtavioHenrique
Last active December 11, 2017 00:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OtavioHenrique/f646018ca2286dfe95b17fe0b0001680 to your computer and use it in GitHub Desktop.
Save OtavioHenrique/f646018ca2286dfe95b17fe0b0001680 to your computer and use it in GitHub Desktop.

Law of Demete

Why?

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

What is?

(Short Answer) — Basically LoD say that your object can only talk with their neighbors. On some OOP languages, simplify thinking "Use only one dot".

Law od Demeter (LoD) is a design guideline that was proposed by Ian Holland in 1987. Remeber 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 neightbors, you should avoid call method of a object returned by another method.

At programming languages that uses dot as field indentifier, you can simple use the law of "use only one dot".

For example, the fallowing 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

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.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment