The Law of Demeter
The Law of Demeter aims to remove navigation trains (dot counting), and it also aims to provide good encapsulation with loosely coupled code.
A method that understands a navigation train breaks the Law of Demeter. For example, have a look at the following code:
report.Database.Connection.Open(); // Breaks the Law of Demeter.
The line of code report.Database.Connection.Open();
is used to open a database connection to run a report.
The Law of Demeter is a software design principle that states that an object should not have direct knowledge of the internal structure or implementation of other objects. This means that a method should only call methods of its own class or of objects that it owns, not of objects that are obtained through other objects.
In this case, the report
object is calling the Open()
method of the Connection
object, which is obtained through the Database
object. This violates the Law of Demeter because the report
object is directly accessing...