0
0
LLDsystem_design~15 mins

Relationships (association, aggregation, composition) in LLD - Deep Dive

Choose your learning style9 modes available
Overview - Relationships (association, aggregation, composition)
What is it?
Relationships in system design describe how different parts or objects connect and interact with each other. Association means two objects know about each other but can exist independently. Aggregation is a special association where one object contains others, but those contained objects can still live on their own. Composition is a stronger form where one object owns others, and if it is destroyed, the owned objects are destroyed too.
Why it matters
Without understanding these relationships, systems can become messy and hard to maintain. Knowing how parts connect helps design clear, reusable, and reliable systems. It prevents bugs like accidentally deleting important data or creating confusing dependencies. This clarity improves teamwork and future changes.
Where it fits
Before learning this, you should understand basic object-oriented concepts like classes and objects. After this, you can explore design patterns and principles that use these relationships to build complex systems.
Mental Model
Core Idea
Relationships define how objects connect, share, or own each other, shaping system structure and behavior.
Think of it like...
Think of a family: association is like friends who know each other but live separate lives; aggregation is like a team where members belong but can leave and join other teams; composition is like a parent and child where if the parent is gone, the child cannot exist alone.
┌─────────────┐       ┌─────────────┐       ┌─────────────┐
│ Association │──────▶│ Aggregation │──────▶│ Composition │
└─────────────┘       └─────────────┘       └─────────────┘

Association: Objects linked but independent
Aggregation: Whole-part with independent parts
Composition: Whole-part with dependent parts
Build-Up - 6 Steps
1
FoundationUnderstanding Basic Association
🤔
Concept: Association means two objects know about each other but can exist independently.
Imagine a teacher and a student. They know each other but can exist separately. In code, this means one class has a reference to another without owning it. For example, a Teacher class may have a list of Student objects, but students can exist without that teacher.
Result
You get a flexible connection where objects interact but don't depend on each other's lifecycle.
Understanding association helps you model simple relationships without tight coupling, making your system more flexible.
2
FoundationExploring Aggregation Relationship
🤔
Concept: Aggregation is a special association where one object contains others, but contained objects can still exist independently.
Think of a library and books. The library has many books, but books can exist outside the library too. In code, a Library class holds Book objects, but deleting the library doesn't delete the books themselves.
Result
You model a 'whole-part' relationship with loose ownership, allowing parts to be shared or reused.
Knowing aggregation helps design systems where parts belong to a whole but maintain their own lifecycle.
3
IntermediateDefining Composition Relationship
🤔
Concept: Composition is a strong ownership where the whole controls the lifecycle of its parts.
Imagine a house and its rooms. Rooms cannot exist without the house. If the house is destroyed, rooms are destroyed too. In code, a House class creates and owns Room objects. When the House is deleted, its Rooms are deleted as well.
Result
You create tightly bound objects with clear ownership and lifecycle control.
Understanding composition ensures you model strong dependencies correctly, preventing orphaned parts.
4
IntermediateComparing Association, Aggregation, Composition
🤔Before reading on: Which relationship implies the strongest ownership and lifecycle dependency? Association, Aggregation, or Composition? Commit to your answer.
Concept: These three relationships differ mainly in ownership strength and lifecycle dependency.
Association: Objects know each other, no ownership. Aggregation: Whole owns parts loosely; parts can exist alone. Composition: Whole owns parts strongly; parts depend on whole's lifecycle. Example: Teacher-Student (Association), Library-Book (Aggregation), House-Room (Composition).
Result
You can choose the right relationship type based on how tightly objects are connected and their lifecycles.
Knowing these differences prevents design mistakes that cause bugs or rigid systems.
5
AdvancedImplementing Relationships in Code
🤔Before reading on: Do you think composition requires parts to be created inside the whole, or can parts be created externally and assigned? Commit to your answer.
Concept: How to represent these relationships in code affects system clarity and correctness.
Association: Use simple references or pointers. Aggregation: Use references but allow parts to be shared or passed in. Composition: Create parts inside the whole; parts are private and not shared. Example in code: class House { private List rooms = new ArrayList<>(); public House() { rooms.add(new Room()); // composition: house creates rooms } } class Library { private List books; public Library(List books) { this.books = books; // aggregation: books passed in } }
Result
You write code that clearly expresses ownership and lifecycle, reducing bugs.
Understanding implementation details helps enforce correct relationships and maintain system integrity.
6
ExpertSurprising Edge Cases in Relationships
🤔Before reading on: Can an object be part of multiple compositions at once? Yes or No? Commit to your answer.
Concept: Real-world systems sometimes challenge strict relationship rules with exceptions or complex cases.
Typically, composition means exclusive ownership; parts belong to one whole only. But in some designs, parts may appear shared or reused, blurring lines between aggregation and composition. For example, a GUI widget might be composed in multiple containers via cloning or proxies. Also, circular references in composition can cause memory leaks if not handled carefully.
Result
You learn to recognize and handle exceptions to textbook definitions in real systems.
Knowing these edge cases prepares you for complex designs and prevents subtle bugs in production.
Under the Hood
At runtime, these relationships are managed through references or pointers between objects. Association uses simple references without ownership, so garbage collection or destruction is independent. Aggregation holds references but parts can be shared, so lifecycles overlap but are not bound. Composition enforces ownership by creating and destroying parts within the whole, often using private fields and strict access control to prevent external references.
Why designed this way?
These distinctions arose to model real-world relationships accurately and manage object lifecycles safely. Early object-oriented designs needed clear rules to avoid memory leaks, dangling references, and unclear ownership. Alternatives like treating all relationships equally led to fragile systems. This design balances flexibility and safety.
┌───────────────┐        ┌───────────────┐        ┌───────────────┐
│   Association │────────▶│  Aggregation  │────────▶│  Composition  │
│  (loose link) │        │ (whole-part)  │        │ (strong whole)│
│               │        │               │        │               │
│ Objects exist │        │ Whole owns    │        │ Whole owns    │
│ independently │        │ parts loosely │        │ parts strictly│
│               │        │               │        │               │
└───────────────┘        └───────────────┘        └───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does aggregation mean the parts are destroyed when the whole is destroyed? Commit to yes or no.
Common Belief:Aggregation means the whole owns the parts and destroys them when it is destroyed.
Tap to reveal reality
Reality:In aggregation, parts can exist independently and are not destroyed with the whole.
Why it matters:Mistaking aggregation for composition can cause accidental deletion of shared parts, leading to data loss or bugs.
Quick: Is association always a one-way relationship? Commit to yes or no.
Common Belief:Association means one object knows about another, but not vice versa.
Tap to reveal reality
Reality:Association can be one-way or two-way; both objects can know each other.
Why it matters:Assuming association is always one-way can cause incomplete designs and missed interactions.
Quick: Can an object be part of multiple compositions at once? Commit to yes or no.
Common Belief:An object can be composed by multiple wholes simultaneously.
Tap to reveal reality
Reality:Composition implies exclusive ownership; parts belong to only one whole at a time.
Why it matters:Ignoring this can cause lifecycle conflicts and memory management issues.
Quick: Does composition always require parts to be created inside the whole? Commit to yes or no.
Common Belief:Parts in composition must always be created inside the whole object.
Tap to reveal reality
Reality:Parts can be created externally and assigned, but the whole controls their lifecycle thereafter.
Why it matters:Rigidly creating parts inside the whole limits flexibility and reuse in design.
Expert Zone
1
Composition often implies exclusive ownership, but in distributed systems, ownership can be logical rather than physical, requiring careful design.
2
Aggregation can be implemented with weak references to avoid strong coupling and memory leaks in complex object graphs.
3
Association relationships can be navigable in one or both directions, affecting system communication and data flow.
When NOT to use
Avoid composition when parts need to be shared or reused independently; use aggregation instead. Avoid aggregation when parts must be tightly controlled and destroyed with the whole; use composition. For loosely connected objects with no ownership, use association. In some cases, event-driven or message-passing patterns replace direct relationships.
Production Patterns
In real systems, composition is used for building complex objects like UI components or documents. Aggregation models collections like orders containing products. Association models collaborations like users and roles. Patterns like Composite, Observer, and Dependency Injection rely on these relationships to manage complexity and lifecycle.
Connections
Object-Oriented Design Principles
Relationships are foundational to principles like encapsulation and single responsibility.
Understanding relationships clarifies how to design classes that are modular, maintainable, and loosely coupled.
Memory Management
Ownership in composition relates to how memory is allocated and freed.
Knowing relationship types helps prevent memory leaks and dangling pointers in languages without automatic garbage collection.
Human Social Structures
Similar patterns of ownership and association exist in social groups and organizations.
Recognizing these parallels aids intuitive understanding of system relationships and their dynamics.
Common Pitfalls
#1Confusing aggregation with composition and deleting shared parts unintentionally.
Wrong approach:class Library { List books; void deleteLibrary() { for (Book b : books) { b.delete(); // wrong: deleting books that may be shared } } }
Correct approach:class Library { List books; void deleteLibrary() { books.clear(); // correct: just remove references, don't delete books } }
Root cause:Misunderstanding that aggregation parts have independent lifecycles.
#2Implementing composition by passing parts from outside, losing lifecycle control.
Wrong approach:class House { List rooms; House(List rooms) { this.rooms = rooms; // wrong: parts created externally } }
Correct approach:class House { List rooms = new ArrayList<>(); House() { rooms.add(new Room()); // correct: house creates and owns rooms } }
Root cause:Not enforcing ownership and lifecycle within the whole object.
#3Assuming association is always one-way and missing needed two-way communication.
Wrong approach:class Teacher { Student student; } // Student has no reference back to Teacher
Correct approach:class Teacher { Student student; } class Student { Teacher teacher; }
Root cause:Oversimplifying association directionality.
Key Takeaways
Relationships define how objects connect and depend on each other, shaping system design.
Association is a loose link with independent lifecycles; aggregation is a whole-part with shared lifecycles; composition is a strong whole-part with exclusive ownership.
Choosing the right relationship prevents bugs, improves clarity, and controls object lifecycles effectively.
Implementing relationships correctly in code enforces design intent and system robustness.
Real-world systems sometimes challenge strict definitions, so understanding nuances and edge cases is essential.