Search code examples
javadesign-patternslaw-of-demeter

Best way of handling object composed of two other objects in terms of hiding implementation details?


For instance, I have a class named Car which contains of two fields of type AdminPart and PassengerPart correspondingly.

For client code using my code I want the client code to be able to do car.getLicense() and not car.getAdminPart().getLicense(). This of course is implemented as getLicense() in Car which in turn calls the relevant getter. Same for setters.

Is there a best practice for this? Something I've overlooked?


Solution

  • This problem sounds like it's related to the Law of Demeter (I added the tag to your question). It's not really a best practice -- many have claimed it's not really a "law" but rather an heuristic ("suggestion") that strives to reduce coupling in the same direction as information hiding. My favorite explanation is The Paperboy, the Wallet, and the Law of Demeter.

    Encapsulation states that clients of Car should not know the details of how a car is designed. Otherwise, if you change those details, the client code could break (and you usually want to provide stable APIs to clients). If you allow clients to do car.getAdminPart().getLicense() you are revealing the details of the object, violating the principle of information hiding and encapsulation.

    Here's a UML diagram that explains the two ways:

    UML class diagram