0

Example Code

class HumanEye {
 
  wink() {...}

  close() {...}
}

class Human {

  eye = new HumanEye();
}

Example Usage

var jose = new Human();

jose.eye.wink();
jose.eye.close();

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
  • 1
    This seems to violate the Law of Demeter or principle of least knowledge
    – Rik D
    Sep 1 '20 at 18:55
1

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.

2

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.

Paperboy.Customer.Wallet.GetMoney()

What might be better is something like this.

Paperboy.AddPayment(Customer.GetPayment());

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.

jose.leg[0].foot.toe[1].smells().bad()

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

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

1

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.