Practice
Solution
Step 1: Identify the problem with inheritance here
Inheritance leads to a combinatorial explosion of subclasses (FlyingCar, FloatingCar, FlyingFloatingCar), making the design rigid and hard to maintain.Step 2: Understand composition benefits
Composition allows attaching behaviors dynamically via separate classes (FlyBehavior, FloatBehavior), promoting flexibility and easier extension.Step 3: Analyze other options
Options A and C rely on inheritance, causing tight coupling and poor scalability. Use a single Vehicle class with flags indicating if it can fly or float uses flags, which leads to complex conditional logic and violates single responsibility.Final Answer:
Option C -> Option CQuick Check:
Composition supports adding new capabilities without modifying existing classes, enhancing maintainability and flexibility.
- Assuming inheritance is always better for code reuse
- Using flags instead of behaviors leads to messy conditionals
Tea().prepare_recipe()?Solution
Step 1: Trace prepare_recipe steps
Calls boil_water (prints 'Boil water'), then brew (prints 'Steep tea bag'), then pour_in_cup (prints 'Pour into cup').Step 2: Check hook method customer_wants_condiments
Tea overrides it to return False, so add_condiments is skipped.Final Answer:
Option A -> Option AQuick Check:
Condiments skipped due to hook returning False [OK]
- Assuming condiments always added
- Mixing order of steps
class PaymentProcessor:
def __init__(self, strategy: PaymentStrategy):
self.strategy = strategy
def pay(self, amount):
if isinstance(self.strategy, CreditCardStrategy):
print(f"Processing credit card payment of ${amount}")
elif isinstance(self.strategy, UPIStrategy):
print(f"Processing UPI payment of ${amount}")
else:
print("Invalid payment method")
Solution
Step 1: Analyze the pay method implementation
The pay method usesisinstancechecks and conditionals to decide behavior, which defeats the purpose of polymorphism.Step 2: Identify correct polymorphic usage
The correct approach is to callself.strategy.pay(amount)directly, letting each strategy handle its own payment logic.Final Answer:
Option A -> Option AQuick Check:
Using conditionals in pay() breaks the strategy pattern [OK]
- Using type checks instead of polymorphism
Solution
Step 1: Understand dynamic add/remove requirement
Need to add or remove decorators at runtime without subclass explosion or code changes.Step 2: Identify suitable data structure and pattern modification
Using a stack to track decorators allows pushing and popping decorators, updating the wrapped object reference accordingly.Step 3: Evaluate other options
Inheritance and flags lead to rigidity; caching all combinations is infeasible for many decorators.Final Answer:
Option C -> Option CQuick Check:
Stack structure supports dynamic decorator management efficiently [OK]
- Trying to use inheritance for dynamic behavior
- Modifying base class breaks open-closed principle
Solution
Step 1: Understand LSP behavioral contract
LSP requires that subclasses preserve the observable behavior of the superclass, including side effects.Step 2: Analyze covariant return type
Covariant return types are allowed and safe, but side effects must still comply with the superclass contract.Step 3: Evaluate options
Refactor the subclass to preserve the original side effects or weaken them, ensuring behavioral compatibility. correctly suggests refactoring to preserve or weaken side effects. Allow the side effect changes since the return type is covariant and thus safe. is incorrect; side effect changes can break clients. Ignore side effects as they are not part of the method signature and thus irrelevant to LSP. is false; side effects are part of behavior and relevant. Change the superclass method to accommodate the subclass's side effects. is risky and breaks superclass abstraction.Final Answer:
Option C -> Option CQuick Check:
Behavioral compatibility includes side effects, not just signatures.
- Ignoring side effects in LSP
- Assuming covariant return types cover all behavioral changes
- Modifying superclass to fit subclass
