aspose file tools*
The moose likes OO, Patterns, UML and Refactoring and the fly likes How to do Composition? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring
Bookmark "How to do Composition?" Watch "How to do Composition?" New topic
Author

How to do Composition?

shaun michael
Greenhorn

Joined: Jan 05, 2005
Posts: 7
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

Joined: Jul 11, 2001
Posts: 14112
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?


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
shaun michael
Greenhorn

Joined: Jan 05, 2005
Posts: 7
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

Joined: Jul 11, 2001
Posts: 14112
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...
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: How to do Composition?