Bird
Raised Fist0

Find the bug in this Command pattern code snippet:

medium📝 Analysis Q7 of Q15
LLD - Behavioral Design Patterns — Part 1
Find the bug in this Command pattern code snippet:
class Receiver {
  void action() { print('Done'); }
}

class Command {
  void execute();
}

class ConcreteCommand implements Command {
  Receiver receiver;
  ConcreteCommand(this.receiver);
  void execute() {
    receiver.action();
  }
}

void main() {
  Command c = ConcreteCommand(null);
  c.execute();
}
Aexecute method is missing override keyword
BReceiver is null, causing a runtime error
CCommand class should not have execute method
DNo bug, code runs fine
Step-by-Step Solution
Solution:
  1. Step 1: Check object initialization

    ConcreteCommand is created with null receiver, so receiver is null.
  2. Step 2: Analyze execute method call

    execute calls receiver.action(), but receiver is null, causing runtime null reference error.
  3. Final Answer:

    Receiver is null, causing a runtime error. -> Option B
  4. Quick Check:

    Null receiver causes runtime failure [OK]
Quick Trick: Null receiver causes runtime error on execute [OK]
Common Mistakes:
MISTAKES
  • Ignoring null initialization
  • Thinking override keyword is mandatory
  • Assuming code runs without receiver

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes