What are Dependencies, Composition, Delegation, and Aggregation in Object-Oriented Programming?

Last updated May 31st, 2022
The four principles of object-oriented programming (abstraction, inheritance, encapsulation, and polymorphism) are features that - if used properly - can help us write more testable, flexible, and maintainable code.

Dependency: The Address object comes from outside, it's allocated somewhere else. This means that the Address and Employee objects exists separately, and only depend on each other.

Composition: Here you see that a new Engine is created inside Car. The Engine object is part of the Car. This means that a Car is composed of an Engine.

Composition is about the relationships between objects.

Delegation is about passing work from one object to another.

These are actually different (but sometimes related) concerns.

What you've got is B composed of A (B refers to A).

Aggregation & composition: An aggregation is an object that represents a concept as a whole and handles managing how its parts are accessed and changed. Composition is related but it adds an additional meaning to aggregation. Composition says that parts of the aggregation can’t exist independently (ie: a wheel can’t exist unless it belongs to a car).

So dependency == aggregation? stackoverflow.com/questions/11881552/… – danihodovic Jan 9, 2014 at 15:04 @dani-h No, aggregation and composition describe how things are build/structured, while dependency is more a property of a certain structure. See @TheLostMind's great answer



Discussion

Liked this? Sing it loud and proud 👨‍🎤.



Stay in touch!



About the author

Khalil Stemmler,
Software Essentialist ⚡

I'm Khalil. I turn code-first developers into confident crafters without having to buy, read & digest hundreds of complex programming books. Using Software Essentialism, my philosophy of software design, I coach developers through boredom, impostor syndrome, and a lack of direction to master software design and architecture. Mastery though, is not the end goal. It is merely a step towards your Inward Pull.



View more in Object-Oriented Programming



You may also enjoy...

A few more related articles

4 Principles of Object-Oriented Programming
The four principles of object-oriented programming (abstraction, inheritance, encapsulation, and polymorphism) are features that -...
Why You Have Spaghetti Code
Code that gets worse instead of better over time results from too much divergence & little convergence.
Reality → Perception → Definition → Action (Why Language Is Vital As a Developer)
As developers, we are primarily abstractionists and problem decomposers. Our task is to use language to decompose problems, turnin...
The Code-First Developer
As you improve as a developer, you tend to move through the 5 Phases of Craftship. In this article, we'll discuss the first phase:...