Some of you probably know the Law of Demeter, but a reminder doesn’t harm anybody:

The fundamental notion is that a given object should assume as little as possible about the structure or properties of anything else (including its subcomponents).

You will say: “Theory is nice but in practice how is it expressed?” Here is an example: I have an object (Auto) and I want to know if the car is running. Code that doesn’t respect the law:

car.getEngine().getState().IsRunning();

Code that respects the law:

car.isRunning();

  In the example above, the code is simpler to read because it respects the law. The code is also easier to maintain. Indeed, if I change the design and the “Running” state comes from the ‘Wheel’ object instead of ‘Engine’, you’ll have to replace car.getEngine().GetState().IsRunning() with car.getTire().GetState().IsRunning(), whereas if you obey the law you’ll just change the IsRunning() method. Another advantage appears during debugging. Indeed, if an object is null at runtime, you get a null pointer exception with the line number. But what is null? The ‘Car’, ‘Motor’, or ‘State’ object? These examples show that not following the law of Demeter is not really serious at first, but by respecting it your code will be clearer. Plus, you’ll also save time on maintenance or debugging. And, as you know, time is money!

gabriel bélanger

Previous post

Jurgen Appelo in Montréal to talk about Agile change management

Next post

comprendre-le-role-de-larchitecte-dans-une-transformation-agile-2