As for my understanding, Composition means, if a class A has an object of another class B in the way of "composition", A is responsible for maintaining life cycle of the object of B.
Explaining further more: There are two classes named A and B. A has an object of B as a "composition". Therefore, A is in charge of maintaining life cycle of the object of B. Which means A has to create and destroy objects of B by itself. That violates Dependancy Inverstion principle which says,
High-level modules should not import anything from low-level modules. Both should depend on abstractions (e.g., interfaces).
If constructor of B changes, A also has to change its implementation as it creates objects of B. Here is a code example in C#
class B {
}
class A {
B b; // composition
A() {
b = new B() // makes tightly coupled to B constructor
}
}
I want to know if Composition violates Dependancy Inversion principle or if I have understood meaning of Composition or DI in a wrong way. I cannot find any reliable source in the internet to find an answer.
Composition is taught Computer Science and similar Degree Programs as a way of making relationsips between objects. If it violates DI I think it should not be taught. An accepted way to make relationships with objects can be Aggregation.
There is a similar question in this SO question. Accepted answer mentions like this,
The object that is owned by another is dependent of the lifetime of the owning object. That doesn't mean that you have to create the owned object inside the owning class.
Isn't that what aggregation does? Aggregation uses an object created by another party so it is not responsible for creating or destroying that object. As in the above answer it is suggested that composition does the same. Composition and Aggregation are two different forms of Association. Therefore I do not accept the above answer as the correct answer for this question.
Wikipedia post on Composition is not reliable. It has mentioned at begining of the post.