nus-cs2103-AY1920S1 / forum

Forum
1 stars 1 forks source link

Class Diagrams: differentiating Composition and Aggregation #187

Open KendrickAng opened 4 years ago

KendrickAng commented 4 years ago

Regarding composition and aggregation, is it correct to say that:

class Foo {
    private Foo1 x;
    private Foo2 y; 
    Foo() {
        this.x = new Foo1();
        this.y = new Foo2();
    }
}
Foo foo = new Foo();

In this case, Foo has a composition relationship with Foo1 and Foo2 since upon destruction of the Foo object, there is no reference to Foo1 and Foo2 and hence they are garbage-collected.Also, in this case:

class Bar {
    private Bar1 x; 
    Bar(Bar1 x) {
        this.x = x;
    }
}
Bar1 temp = new Bar1();
Bar bar = new Bar(temp);

Bar has an aggregation relationship with Bar1 since even after the Bar object is destroyed, there still exists a reference to Bar1 and hence it is not destroyed (garbage-collected)?

damithc commented 4 years ago

Given a composition relationship, we should delete the parts when the whole is deleted. However, the reverse is not necessarily true. The question to ask is, is this really a whole-part relationship? In this case, the code does not have enough information to answer that question. It may be, but it may not be. The fact the certain objects are deleted when certain others are deleted can be just a coincidence.

The second case is an aggregation (to play devil's advocate, it can also be an incorrectly implemented composition).

The bigger point is, composition/aggregation is more about the conceptual relationships, rather than how the code works.

In the exam, there will be additional hints to indicate composition if I expect you to identify it from code. I will not penalize if you mark the first case as a composition because it can very well be but I will not penalize for not marking it as a composition either (no effect either way).