C
C#5mo ago
danyule

Aggregation vs Composition (UML)?

Hi there, I'm struggling to understand the difference between the terms composition and aggregation from UML in the context of C#? How would you implement a composite and how would that differ from aggregation? My understanding, based on what I've read, is that composites manage their components entire lifecycle. So would you typically implement a composite using private classes? For example as follows: Composition
public class Car
{
private Engine _engine;

public Car()
{
_engine = new Engine();
}

private class Engine
{

}
}
public class Car
{
private Engine _engine;

public Car()
{
_engine = new Engine();
}

private class Engine
{

}
}
I understand you can argue an engine can exist independently of a car, but for the purposes of this question, assume that it doesn't. The same example using aggregation would look something like this: Aggregation
public class Car
{
private Engine _engine;

public Car(Engine engine)
{
_engine = engine;
}
}

public class Engine
{

}
public class Car
{
private Engine _engine;

public Car(Engine engine)
{
_engine = engine;
}
}

public class Engine
{

}
I also have seen in the wild that both examples would be referred to as composition. So I'm a bit confused right now.
7 Replies
Anton
Anton5mo ago
I have only heard the term aggregation in the context of UML
jiniux
jiniux5mo ago
composition means that the child objects will only live as long as the father object lives or in other words, the childs cannot exist without the parent if we have a Car class and we draw a composition arrow connected from Car to Engine we are explicitly saying that the engine cannot exist as an object outside of a Car
blueberriesiftheywerecats
Isnt it composition?
danyule
danyuleOP5mo ago
Are you sure it’s not the opposite way around? It sounds like you’re talking about a composite. At least based on what I’m currently reading
jiniux
jiniux5mo ago
okay yeah you're right i swapped them xd
danyule
danyuleOP5mo ago
I’m reading Diving into Design Patterns by Alexander Shvets No worries haha I see what you mean anyhow. I’m just struggling to visualise how the code would actually look
jiniux
jiniux5mo ago
it looks the same remember UML is communication you are just explicitly saying to the reader that they cannot use the Engine outside of the Car if you don't need that you can just use a weaker form of association
Want results from more Discord servers?
Add your server