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)