The Law Of Demeter strives to reduce coupling between objects following the principle of information hiding. In your example the method m
which contains the statement:
int numberOfFrigates = model.getSelectedPlanet().getFleet().getNumberOfFrigates();
is interested in the number of Frigates
only. But the chain of method calls do couple the method m
and hence the type T
owning m
to the types returned by getSelectedPlanet()
and getFleet()
.
A solution to avoid this introduced dependencies would be to add a method to your model
which directly returns the number of frigates of the currently selected plane like:
int numberOfFrigates = model.getNumberOfFrigates();
But most often the violation of the principal is an indicator of bad design or misplaced responsibilities. The real solution to this problem most likely is not to expose the information gained by the method chain directly at the consumer like the example shown above, but by moving parts or the whole responsibility of processing closer to the object which holds the required information.
To be as concrete as I can in your example, ask yourself:
Why do I need the number of frigates in my method m
?
May I move parts of processing done in m
closer to the types Planet
or Fleet
?
This way you would avoid the method chain as well.