The Law of Demeter
The Law of Demeter, or the principle of least knowledge, states that a software component should have limited knowledge about the inner details of other components. More specifically, a component should not know about the internal details of another component.
Let us say there is a function that returns the city in the address of a person:
class Person(val name: String, val address: Address) { fun getAddressCity(): String { return address.city } } class Address(val city: String)
The Person
class directly accesses the city
property inside the Address
class. The Person
class should not have this knowledge, as this is a violation of the Law of Demeter.
This creates a coupling between Person
and Address
. The coupling dictates that if the city
property changes its data type, then both classes will need to change. It also means that the code change is bigger than...