Sobes.tech
Junior — Middle

What are the advantages and disadvantages of using composition in programming?

sobes.tech AI

Answer from AI

Composition is a way of building complex objects from simpler ones, where one object contains another as part of its structure.

Advantages of composition:

  • Allows creating flexible and easily extendable systems.
  • Improves code reuse, as components can be used in different places.
  • Avoids problems associated with inheritance, such as rigid hierarchy and unwanted inheritance of behavior.
  • Provides loose coupling between objects, which facilitates testing and maintenance.

Disadvantages of composition:

  • Can lead to more code, as calls to embedded objects need to be explicitly delegated.
  • Sometimes harder to understand the program structure due to the large number of objects and relationships between them.
  • In some cases, performance may be lower due to an additional level of indirection.

Example in Python:

class Engine:
    def start(self):
        print("Engine started")

class Car:
    def __init__(self):
        self.engine = Engine()  # composition

    def start(self):
        self.engine.start()  # delegation

car = Car()
car.start()  # Output: Engine started