Bird
Raised Fist0

In the following code, what is the main issue that prevents the Command pattern from working correctly?

medium📝 Analysis Q14 of Q15
LLD - Behavioral Design Patterns — Part 1
In the following code, what is the main issue that prevents the Command pattern from working correctly?
class Light {
  turnOn() { console.log('Light is ON'); }
}

class TurnOnCommand {
  constructor() { }
  execute() { this.light.turnOn(); }
}

const light = new Light();
const command = new TurnOnCommand();
command.execute();
AThe execute method should return a value
BThe Light class is missing the turnOff method
CThe TurnOnCommand constructor does not receive or store the Light object
DThe command object is not instantiated properly
Step-by-Step Solution
Solution:
  1. Step 1: Check TurnOnCommand constructor

    The constructor does not accept or assign the Light object to this.light, so this.light is undefined.
  2. Step 2: Analyze execute method call

    Calling this.light.turnOn() fails because this.light is undefined, causing an error.
  3. Final Answer:

    The TurnOnCommand constructor does not receive or store the Light object -> Option C
  4. Quick Check:

    Missing light reference in command = error [OK]
Quick Trick: Ensure command stores receiver object before execute [OK]
Common Mistakes:
MISTAKES
  • Ignoring missing receiver object in command
  • Thinking missing turnOff method causes error here
  • Assuming execute must return a value

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes