General OO - One to Zero or One

General OO - One to Zero or One

Old forum URL: forums.lhotka.net/forums/t/3396.aspx


juddaman posted on Friday, August 17, 2007

I have a situation where I have a BO that may or may not have an association with another BO. For the sake of discussion say Person hasPet Animal (in this 'world' a Person can only have up to one pet) and the inverse Pet ownerBy Person. Hence a person may or may not have a pet. When the association exists I am storing the identifier of the (in this case) Animal in the Person BO. However when the Person has no pet I'm just storing an empty Guid. I'm not keen on storing what is basically a null reference in a BO, has anybody got any better solutions to this? Or is this a valid solution? I did consider moving the reference to the Pet so it would keep reference its owner (which could be modelled as a must have association – i.e. a pet must be owned by someone). However in this case it is required that a Person knows its pet if it has one. Any suggestions?

richardb replied on Wednesday, August 29, 2007

Sounds like a valid solution to me if there is definately only ever 1 "Pet" allowed per "Person".  You could have a Property on the BO called Pet() which returns and sets the Pet object accordingly I guess.

You could also use a collection and child object which potentially allows you to assign many "Pets" if the Pet is a child object, but for now you could check and restrict it so only one Pet could be added at a time.  But that might be confusing.  I used this method once as Sales teams were creating a cost sheet quote and swore blind they only ever created one quote per "Sales deal" at a time.  I didn't believe them and wanted to have up my sleeve the ability to save multiple quotes (a history) so designed my object model that way but just let them add/edit one quote.

To be honest it wasn't much work to switch to either method.

Sounds like your Pet could be a switchable parent child object.

Hope that helps.

juddaman replied on Thursday, August 30, 2007

Hi Richard, thanks for replying.

I ended up adding methods to set and get the "Pet" (similar to what you suggested). This way I could just return null if there was no "pet". I also added a HasPet property. I realized my issue was with returning an empty Guid, which was ambiguous, could be NULL could be a pet. I didn’t consider the list but if more than one Pet ever made it on too the list the consequence would be dire. In my system a Pet is a root, Person just keep a reference to it.

On another note - Can One-to-One relationships exist within the CSLA / behavior driven philosophy? If the relationship always existed should all the properties be combined into 1 BO so the BO had all the data it needed?

 I.e. so A - B and B -C. Would become A (with all the properties of B) and C with all the properties of (B).

Thanks again,

George

 

Copyright (c) Marimer LLC