Search code examples
pythonoopdependency-injectioncomposition

Why use composition at all?


What is the reason to create components and delegate behavior through them when we can add dependency directly to the method? To me, the latter seem to keep the door open for a behavior to change for existing objects, thus create looser couplings?

Composition/delegation:

class Human:
  def __init__(self, legs):
    self._legs = legs

  def run(self):
    self._legs.run()

  def walk(self):
    self._legs.run()

Inject dependency straight to method:

class Human:
  def run(self, legs):
    legs.run()

  def walk(self, legs):
    legs.walk()

Tell me, why should I bother with composition at all?


Solution

  • You should only use composition if it serves a purpose. In your example it serves no purpose since you could just call the methods directly on legs and don't bother with Human at all.

    Expanding on your example, composition would make sense if each Human instance had its own distinct legs instance. In that case you need to keep track of which legs belongs to which Human, and the first example solves that.