Sobes.tech
Junior — Middle

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

sobes.tech AI

Answer from AI

Advantages of composition:

  • Flexibility: Allows creating complex objects from simple components, easily replacing or modifying parts without changing the entire system.
  • Code reuse: Components can be used in different classes.
  • Avoidance of inheritance issues: Composition helps avoid rigid class hierarchies and problems associated with multiple inheritance.
  • Explicit dependency management: Objects explicitly contain references to components, which improves code readability and maintainability.

Disadvantages of composition:

  • Increase in the number of objects: Can lead to a larger number of small objects, complicating their management.
  • Structural complexity: Excessive use of composition can make the code difficult to understand due to a large number of interconnected components.
  • Additional code for delegation: Sometimes, methods that simply call component methods need to be written, increasing the code volume.

Example of composition in Java:

class Engine {
    void start() {
        System.out.println("Engine started");
    }
}

class Car {
    private Engine engine;

    public Car() {
        this.engine = new Engine();
    }

    public void start() {
        engine.start(); // delegation
        System.out.println("Car is running");
    }
}