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.