Junior — Middle
What alternative approaches exist for code reuse besides inheritance?
sobes.tech AI
Answer from AI
Instead of inheritance, code reuse is often achieved through:
- Composition — creating objects from other objects, delegating functionality. It allows flexible behavior combination without a strict hierarchy.
- Interfaces and abstractions — defining contracts that are implemented by different classes, increasing flexibility and testability.
- Delegation — an object delegates a task to another object, reducing coupling.
- Mixins — in some languages, allowing to add functionality without inheritance.
- Utility functions and libraries — extracting common code into separate functions or modules for reuse.
For example, instead of inheritance, you can create a class that contains an object with the desired behavior and calls its methods as needed.