Example Code

class HumanEye {
  wink() {...}

  close() {...}

class Human {

  eye = new HumanEye();

Example Usage

var jose = new Human();


My understanding is that this pattern is cleaner than jose.eyeWink().

Although, it feels like I am doing something wrong... I don't know why!

  • 1
    This seems to violate the Law of Demeter or principle of least knowledge
    – Rik D
    Sep 1 '20 at 18:55

The design of compound objects is called composition. The action of setting the new object inside the composite object is called dependency injection. It is bad for a number of reasons for the composite object to create their own components, so they're built in a factory and injected into the receiver object.

The idea is that the injected object has functionality that the composite object needs and cannot do by itself.

Dependency injection can be done thru a constructor method or thru a setter method.


Here is an article that expands on the law of Demeter. https://www2.ccs.neu.edu/research/demeter/demeter-method/LawOfDemeter/paper-boy/demeter.pdf

The articles uses the example of a paperboy asking you, a Customer, for payment. Do you give the paperboy your wallet or do you protect the wallet and give the paperboy only the money he's due?

class Wallet, 
class Customer
class Paperboy

Law of Demeter example is like this; notice in the following example that the paperboy has direct access to the Customer's Wallet. Not good. Not good at all.


What might be better is something like this.


See how the paperboy knows nothing of the Wallet. Much better.

In your code the Human class knows about the Eye class.

It actually reads very well but that can be a problem.

Keep it in mind because you might end up writing code like this.


Then you are in trouble. That's a nightmare to manage.

The article is good. Keep it in mind. Happy coding.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.