Search code examples
oopumlcompositionobject-oriented-analysis

Can two compositions own the same object?


I'm trying to make a class diagram for an Online Auction System and I'm having this problem. Bids belong to both the Auction and the Buyer (Correct me if i'm wrong). So can I say that User is composed of bid AND auction is composed of Bid or is this against the rules of UML? I'm confused


Solution

  • In general

    The term composition is ambiguous and this explains your confusion:

    • In OOP, object composition means to use an object in another one.
    • In UML, composition is a special kind of association that represents a part-whole relationship, with an exclusive ownership of the parts by the whole.

    So in the UML sense, it is not possible to have an object that is part of two different compositions, because the ownership would no longer be exclusive. But you could use the object in several aggregations, which are a whole-part relations allowing a shared ownership.

    In the OOP sense, there is no problem of having the same object used in (or using) several compositions. The object composition corresponds to a navigable UML association.

    In your practical case

    The situation is straight forward: A Bid has one Buyer, a Buyer may have several Bids, and an Auction has several Bids. You can model this with simple associations:

    enter image description here

    You could alternatively use an aggregation here, since one could argue that there is a whole-part relation between an Auction and the corresponding Bids (personally, I wouldn't see it like this):

    enter image description here

    You should however not see an aggregation on the other side, because there is no real whole-part relation between a Buyer and a Bid: a Buyer is not "made of several Bids".

    Additional remarks

    You could use also an association class here. But it's not required. And the semantic would be different: it would mean that there is a Bid association between a Buyer and an Auction:

    • Technically speaking, you'd still have three classes.
    • But the focus is different: the Bid is accessory to the Buyer and the Auction and cannot exist on its own (e.g. if the buyer disappears)