Law of Demeter

The Law of Demeter is a design guideline with as goal to create loose coupling between objects.  It is also know as the principle of least knowledge. This is the law for methods. The less a method knows about other objects methods, the less coupling you have.

The Demeter Rules

So the rules we should follow for this law are the following:

  • A method of an object can call methods of that object
  • A method can call a method of its parameters
  • A method can call a method of any objects created or instantiated by that method
  • A method can call a method of objects that are dependencies of the methods object
  • A method can call a method of a global variable that is accessible by the object of the method

Well this means that a method should be able to call methods on an object that it has available according to these rules. But you can only call a method one level deep. You should not nest method calls because then you are knowing to much. To much knowledge in this case means to much coupling in your code.

Some Example

<?php
class Class1
{

    private $class2;

    public function __construct(Class2 $class2)
    {
        $this->class2 = $class2;
    }

    public function badMethod()
    {
        return $this->class2->badMethod()->methodClass3();
    }

    public function goodMethod()
    {
        return $this->class2->goodMethod();
    }
}

class Class2
{
    private $class3;

    public function __construct(Class3 $class3)
    {
        $this->class3 = $class3;
    }

    public function badMethod()
    {
        return $this->class3;
    }

    public function goodMethod()
    {
        return $this->class3->methodClass3();
    }
}

class Class3
{
    public function methodClass3()
    {
        // Code for this method
        return true;
    }
}

$class3 = new Class3();
$class2 = new Class2($class3);
$class1 = new Class1($class2);

if ($class1->methodBad()) {
    echo 'The bad method was true!';
}

if ($class1->methodGood()) {
    echo 'The good method was true!';
}

In this example you can see the bad and good method. You should not expect Class1 to call a method from Class3. Class1 should not have the knowledge about Class3 methods because its not passed directly as a parameter, is not a direct dependency or is instantiated by Class1. Instead you should handle any logic for Class3 in Class2 itself.

Conclusion

This was a quick overview of the Law of Demeter. This is one of the laws you should follow and understand for creating decoupled code. The advantage here is that by following this law your code becomes more maintainable and adaptable which is important when creating object oriented code. Every class should be able to work on its own and should not know about the details that it should not know. You can only go one level deep. So always think before coding!