Difference between dependency and composition?
Asked Answered
R

4

33

Definitions taken from here

Dependency

Change in structure or behaviour of a class affects the other related class, then there is a dependency between those two classes. It need not be the same vice-versa. When one class contains the other class it this happens.

Composition

Composition is a special case of aggregation. In a more specific manner, a restricted aggregation is called composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition.

Concrete examples in Java from here and here

Dependency

class Employee {
    private Address address;

    // constructor 
    public Employee( Address newAddress ) {
        this.address = newAddress;
    }

    public Address getAddress() {
    return this.address;
    }
    public void setAddress( Address newAddress ) {
        this.address = newAddress;
    }
}

Composition

final class Car {

  private final Engine engine;

  Car(EngineSpecs specs) {
    engine = new Engine(specs);
  }

  void move() {
    engine.work();
  }
}
Rolfe answered 9/1, 2014 at 13:47 Comment(3)
The quality of those definitions is quite poor. Example: "...dependency between those two classes" "It need not be the same vice-versa" But "between" is an undirected relationship---it is the same vice-versa by definition of the term between.Deanery
Can you give me an example in code please :)Rolfe
@MarkoTopolnik An example of dependecy and composition where I can clearly understand the differance. In code if possibleRolfe
S
56

The difference can be seen in the two constructors:

  • 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.

Sisto answered 9/1, 2014 at 13:54 Comment(2)
So dependency == aggregation? #11882052Rolfe
@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.Sisto
C
24

Simply put :

Thanks to Marko Topolnik for this...

  1. Dependency occurs when one object "is dependent" on another. It can occur with or without a relation between the 2 objects. Actually, one object might not even be knowing that another exists, yet they might be dependent. Example : The Producer-Consumer problem. The producer need not know that the consumer exists, yet it has to do wait() and notify(). So, "NO" , dependency is not a subset of association.

  2. Composition : Is a type of association in which the "child" object cannot exist without the parent class. i.e, if the child object exists, then it MUST BE IN THE parent Object and nowhere else.

    EG: A Car(Parent) has Fuel injection system(child). Now, it makes no sense to have a Fuel Injection system outside a car (it will be of no use). i.e, Fuel injection system cannot exist without the car.

  3. Aggregation : Here, the child object can exist outside the parent object. A Car has a Driver. The Driver CAN Exist outside the car.

Claque answered 9/1, 2014 at 13:54 Comment(14)
So you are saying a composition is a subset of a dependency?Rolfe
Yes... Dependency is a general term.. Composition/aggregation/inheritance lead to dependency. Though I think association is a better term to use instead of dependency.Claque
Can you show me the source of this? Because the two answers I've got contradict each other. Also, they appear differently in UML, which one should be used in class diagrams for instance?Rolfe
If the definition of dependency is "a change in structure/behavior influences a class", then there has to be no aggregation or any other type of relationship between the classes. They may both, for example, access the same third object, and must agree on the ways they are using that object. Typical example: the Producer/Consumer pattern.Deanery
@Claque I ctrl+f'd that document and there is no mention of dependency being a general form of aggregation/composition/association?Rolfe
@dani-h - See... Whenever a class A uses another class or interface B, then A depends on B. A cannot carry out it's work without B, and A cannot be reused without also reusing B. In such a situation the class A is called the "dependant" and the class or interface B is called the "dependency". A dependant depends on its dependencies.Claque
@MarkoTopolnik - Am I wrong in considering composition/aggregation/association as dependencies??Claque
@Claque Surely each of those creates a dependency, but the existence of any of them is not a prerequisite for the existence of a dependency.Deanery
@MarkoTopolnik - I thought. The fuel injection system is a dependency for the car as without it, the car cannot exist.Claque
@Claque Maybe you misunderstand me? Dependency as a relation may exist without there being any aggregation, composition, or association relation.Deanery
@MarkoTopolnik : How can 2 classes/objects be dependent if they dont have any relation?. Or how can a dependency exist without relations?Claque
Quoting myself from the above comment: Typical example: the Producer/Consumer pattern. Both producer and consumer aggregate a Queue object, but otherwise are completely decoupled and don't know about each other. However, changing the behaviour of the Producer will influence (and possibly break) the behaviour of the Consumer.Deanery
@MarkoTopolnik - This makes perfect sense.. Thanks :)Claque
There is a lot of contradictory documentation out there about this. As long as you find ways to define these terms such that they have different levels of dependency, and you remain consistent with those definitions, you'll be okay.Estremadura
E
1

Dependency refers to usage of objects only within a functions scope. In other words, instances of the class only exist within the functions (or methods) of the containing class, and are destroyed after functions exit.

The example you gave for Dependency is not a Dependency because the Employee class contains an instance of an Address, this is called an Aggregation. An aggregation is like a Composition except the object can also exist outside of the class which is using it. (It can be located outside the classes scope). In your example you are passing a copy of an Address to the Employee constructor. But since it is created outside of the Employee object, the Address may also exist else where in the program.

Just as with Aggregation, Composition is where the component object is available to the entire composite object. This means that all the methods/functions of the composite object can access the component object. The only difference between Aggregation and Composition is that in Composition the component object only exists inside the composite object and no where else in the program. So when the composite object is destroyed, the given component object is also destroyed, and can not exist anywhere else. In your example, The Car is a composite object and the Engine is a component because that instance of the Engine only exists in that particular Car and no where else.

Estremadura answered 11/2, 2018 at 18:49 Comment(0)
P
0

Composition will necessarily, always utilize dependency injection.

However, it is possible to do dependency injection without it constituting composition.

Practically speaking, if you get to concrete code, whether composition occurs or not is determined by whether your save the argument passed via dependency injection as a member variable in the instantiated object when instantiating or not. If you do, it's composition. If you don't, it's not.


Definitions

Dependency injection in simplified terms is adding a parameter to an capsulating chunk block of code (e.g. class, function, block, etc.), as opposed to using the literal procedural code that would be used without the parameter.

Composition is when you use a dependency injected parameter/argument upon instantiating the object being composed


Dependency injection with composition

The Syringe class is composed of Drug, since Syringe saves drug as a member variable.

Aside: Syringe could conceivably be composed of multiple dependencies, not just the single drug dependency (pun alert!), but even this degenerate case of a single-dependency composition constitutes composition nonetheless. If it helps, imagine if you had to compose a Syringe object from a Drug object as well as a Needle object, the needle object having a specific value among many possible gauges and lengths as well.

Class Drug
  def __init__(name)
    @name = name
  end

  def contents
    return @name
  end
end

Class Syringe
  def __init__(drug)
    @drug = drug
  end

  def inject()
    return @drug.name
  end
end

amoxicillin = Drug.new('amoxicillin')
#these two lines are the key difference. compare them with the 'same' lines in the other other example
syringe = Syringe.new(amoxicillin) 
syringe.inject() 

Dependency injection without composition

This next example is not composition because it does not save 'drug' when instantiating 'syringe'.

Instead, 'drug' is used directly in a member function.

Class Drug
  def __init__(name)
    @name = name
  end

  def contents
    return @name 
  end
end

Class Syringe
  def inject(drug)
    return drug.contents
  end
end

amoxicillin = Drug.new('amoxicillin')
#these two lines are the key difference. compare them with the 'same' lines in the other other example
syringe = Syringe.new()
syringe.inject(amoxicillin)
Pulmotor answered 26/7, 2023 at 1:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.