2
votes

I'm doing an assignment on class diagram and the following shows the association between classes Order and Menu Item. Should the link be aggregation (weak) or composition (strong)?

enter image description here

I'm confused because I've seen example showing aggregation. I felt it should be composition as an Order must have at least 1 Menu Item added. Am I wrong?

2
The mileage of your instructor may vary, but one of my professors once said: "The distinction between aggregation and composition is extremely subtle, ill-defined, and completely subject to personal interpretation. When you draw a UML class diagram, decide to use either aggregation or composition, but do not waste any further thought of it. Whenever you encounter a diagram that includes both, do not assume that the author wanted to express anything specific by the distinction, but rather, that the author accidentally clicked different buttons at different times." Maybe this helps ;) - O. R. Mapper

2 Answers

1
votes

Should the link be aggregation (weak) or composition (strong)?

It can be both. The main difference is:

In case it's a composition:

  • MenuItem objects are instantiated at the instantiation time of the Order object.
  • The MenuItem objects are destructed as soon as the Order object is destructed.

  • C++ example:

    class Order {
        MenuItem menus[NUMBER_OF_MENUS];
    };
    

In case it's a aggregation:

  • The lifetime of the MenuItem objects is independent of the Order object lifetime.

  • C++ example:

    class Order {
        MenuItem* menus[NUMBER_OF_MENUS];
    };
    

So it's a design decision. And might also depend on the implementation language. In Java, for example, there is no distinction between both, all object variables are references.

0
votes

A lot is dependent on context. Let's use an example that should clarify the difference for you.

Suppose you are assembling a Car object in a car factory. The Car object has two Axle objects, four Wheel objects, a Motor object, and so on. All of those objects only have meaning within the context of the entire car (once you put them in, they stay there). That's composition.

Now, suppose you have a Car object in a junkyard. The Car object has the same stuff, but you can pull wheels or axles or the motor out of it and sell them separately. In that case, each part has a lifetime separate from that of the car. That's aggregation.