Bird
Raised Fist0

In a large-scale system where behaviors need to be dynamically changed at runtime, what is a key design consideration when using composition to avoid pitfalls that inheritance-based designs face?

hard🎤 Interviewer Follow-up Q15 of Q15
OOP & Design Patterns - Composition vs Inheritance - Favour Composition, Why & When
In a large-scale system where behaviors need to be dynamically changed at runtime, what is a key design consideration when using composition to avoid pitfalls that inheritance-based designs face?
AUse deep inheritance hierarchies to capture all behavior variations upfront.
BEnsure that composed behavior objects are immutable to prevent side effects.
CAvoid using interfaces and rely on concrete classes to reduce complexity.
DDesign behavior interfaces and use delegation so behaviors can be swapped without modifying the main object.
Step-by-Step Solution
  1. Step 1: Understand dynamic behavior change

    To change behaviors at runtime, the design must support swapping behavior implementations easily.
  2. Step 2: Analyze options

    Ensure that composed behavior objects are immutable to prevent side effects. is not practical; immutability limits dynamic changes. Avoid using interfaces and rely on concrete classes to reduce complexity. increases coupling and reduces flexibility. Use deep inheritance hierarchies to capture all behavior variations upfront. contradicts favoring composition and leads to rigid designs.
  3. Step 3: Confirm best practice

    Design behavior interfaces and use delegation so behaviors can be swapped without modifying the main object. promotes defining behavior interfaces and delegating calls, enabling runtime swapping without modifying main objects.
  4. Final Answer:

    Option D -> Option D
  5. Quick Check:

    Delegation with interfaces is key to flexible, dynamic composition.
Quick Trick: Use interfaces and delegation to swap behaviors dynamically, not inheritance or concrete classes.
Common Mistakes:
MISTAKES
  • Thinking immutability aids dynamic behavior changes
  • Relying on inheritance for runtime flexibility
Trap Explanation:
PITFALL
  • Candidates often confuse immutability with flexibility or think inheritance can handle dynamic behavior changes well.
Interviewer Note:
CONTEXT
  • Tests deep understanding of composition design for runtime flexibility beyond static inheritance.
Master "Composition vs Inheritance - Favour Composition, Why & When" in OOP & Design Patterns

2 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More OOP & Design Patterns Quizzes