• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

OO Design - Composition vs Storing ids

 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all.

I've been asked recently "Is it better to store objects within another object, or store an id which allows us to look up the other object?"
My initial instinct is that presuming the lifecycle of the nested object is dependent on the containing object, nest the object itself. But I realised I couldn't actually explain in clear words why.

Can anyone give reasons why one method is better than the other:

example:



or


 
Ranch Hand
Posts: 237
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Kevin McMahon wrote:
I've been asked recently "Is it better to store objects within another object, or store an id which allows us to look up the other object?"
My initial instinct is that presuming the lifecycle of the nested object is dependent on the containing object, nest the object itself. But I realised I couldn't actually explain in clear words why.



This is the difference between ordinary composition and another form of composition called aggregation. The difference is the duration of the relationship. Ordinary composition is forever whereas aggregation is temporary. Compare for example the different relationship a Car has with its Parts and with its Passengers. Both are has-a relationships but if a Part is missing the Car is broken while Passengers come and go without compromising the Car. Parts are forever (it's the very fabric of a Car) whereas Passengers are temporary. The former is ordinary composition, the latter is aggregation.

But note that these relationships are modelling relationships. It doesn't really matter how they're implemented (direct with an object reference or indirect via some other identity representing the object). That wouldn't change the nature of Part's and Passenger's relationships with Car. Whether you use a "bald" reference or some id is more a matter of convenience - which fits the design or implementation better.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic