phanalist

Law of Demeter (e14)

The Law of Demeter (LoD) or principle of least knowledge is a design guideline for developing software, particularly object-oriented programs. In its general form, the LoD is a specific case of loose coupling.

This rule checks for method chaining, which is a common violation of the Law of Demeter. Specifically, it flags calls to methods on the result of another method call or function call.

Violation

$object->something()->else(); // Violation
getSomething()->else(); // Violation

Correction

Assign the intermediate result to a variable before calling a method on it. This makes the dependency explicit and easier to debug/mock.

$something = $object->something();
$something->else();

Exceptions