2.4.5 How to Adhere to the Law of Demeter

The Law of Demeter states that a given object should "assume as little as possible about the structure or properties of anything else". What this means is that object should not have access to another object's information. Much like 'stranger danger', a stranger shouldn't be able to know anything about you or interact with you unless they have your say-so; so we only talk to our friends.

When fields and methods are public they are available to everything. That poses a gigantic problem, though, because anything that has access to that object can dig around and do things with it. The solution to keeping this from happening is using the visibility keyword private to limit the access of an object's members.

For example, a criminal has gotten into the Zoo and is going around snatching cash.

We can see that when we run the application, the criminal succeeds at taking all of Sam's money. Not good.

This is possible because the attendant's MoneyBalance field is public (i.e. available to anything that has access to it). We can fix this by making the MoneyBalance field private.

As soon as this happens, the criminal no longer has access to the attendant's MoneyBalance field.

But the Employee can still modify the field from within their class just fine.