Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Aggregation vs Composition in Object-Oriented Databases

1. Definition

Aggregation and Composition are two types of associations in object-oriented databases that define relationships between objects. Understanding these concepts is crucial for effective data modeling.

Note: Both concepts are used to model relationships but differ in terms of ownership and lifecycle management.

2. Key Concepts

2.1 Aggregation

Aggregation is a "has-a" relationship where a child (part) can exist independently of the parent (whole). For example, a Library has many Books, but the books can exist without the library.

2.2 Composition

Composition is a stronger relationship where the child cannot exist independently of the parent. For instance, a House comprises Rooms, and if the house is destroyed, the rooms are also destroyed.

3. Code Examples

3.1 Aggregation Example


class Book {
    String title;
    String author;

    Book(String title, String author) {
        this.title = title;
        this.author = author;
    }
}

class Library {
    List books = new ArrayList<>();

    void addBook(Book book) {
        books.add(book);
    }
}
            

3.2 Composition Example


class Room {
    String name;

    Room(String name) {
        this.name = name;
    }
}

class House {
    List rooms = new ArrayList<>();

    House() {
        // Rooms are created with the House
        rooms.add(new Room("Living Room"));
        rooms.add(new Room("Bedroom"));
    }
}
            

4. Best Practices

  • Use Aggregation when the lifecycle of the child is independent of the parent.
  • Use Composition when the child lifecycle is tied to the parent.
  • Clearly define relationships to avoid ambiguity in the model.
  • Document relationships in the code for better maintainability.

5. FAQ

What is the main difference between aggregation and composition?

The main difference lies in lifecycle management: in aggregation, the child can exist independently, while in composition, the child cannot exist without the parent.

Can a class have both aggregation and composition relationships?

Yes, a class can have both types of relationships, depending on the design requirements.

How do I choose between aggregation and composition?

Consider the lifecycle of the objects involved: if they should be tightly coupled, use composition; if they can exist independently, use aggregation.