• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to do Composition?

 
shaun michael
Greenhorn
Posts: 7
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If Object A contains Object B and Object C needs to be able to send a message to Object B how should it be designed? Should it be something like C calls A.getB().doSomething() or should A have a method that completely hides the existence of B so C calls A.doSomething() which calls B.doSomething.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As a *heuristic*, you should more likely do the latter - it makes for much better decoupling. Google "Law of Demeter" for more info.

In the end, you will have to decide case by case. Do you have a concrete example?
 
shaun michael
Greenhorn
Posts: 7
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ilja Preuss:
As a *heuristic*, you should more likely do the latter - it makes for much better decoupling. Google "Law of Demeter" for more info.

In the end, you will have to decide case by case. Do you have a concrete example?


No example. I've gotten in the habit of doing it the first way and lately have been questioning if that was the right. But after reading up on LOD I guess I have affirmation that it is not the right way. Thanks.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome. Keep in mind that it's not really a law in the sense that you should follow it without question. Robert Martin is known for calling it the "rather good idea of demeter" for that reason...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic