CommandVSStrategy
The Problem
Scenario A β Command territory: Your task queue accepts jobs: send email, resize image, generate report. Each job must be serializable, retryable, and undoable. You need a history log of what was executed and the ability to replay failed jobs.
Scenario B β Strategy territory: Your pricing engine calculates discounts differently for free, premium, and enterprise customers. The caller picks which pricing algorithm at checkout. No undo, no history, no queuing β just swap the algorithm.
Why They Look Alike
Both encapsulate behavior inside an object with an execute() method. Both let you pass behavior as a parameter. The class diagrams are nearly identical.
The Core Difference
| Aspect | Command | Strategy |
|---|---|---|
| Purpose | Encapsulate an action as an object | Encapsulate an algorithm as an object |
| Undo | Yes β commands carry undo() | No β strategies just compute |
| History | Commands are stored, logged, replayed | Strategies are swapped, not stored |
| Queuing | Commands can be queued and deferred | Strategies execute immediately |
| Serialization | Commands are often serialized (job queues) | Strategies are runtime objects |
| Who decides | Invoker triggers; command knows the receiver | Client picks strategy; context delegates |
| Analogy | A restaurant order slip (can be queued, cancelled) | Choosing which route to take (just pick one) |
One sentence: Command is about what to do (queue it, undo it, log it); Strategy is about how to do it (swap the algorithm).
Side-by-Side Code
Command β Task queue with undo
| 1 | interface Command { |
| 2 | execute(): Promise<void>; |
| 3 | undo(): Promise<void>; |
| 4 | serialize(): string; |
| 5 | } |
| 6 | |
| 7 | class SendEmailCommand implements Command { |
| 8 | constructor( |
| 9 | private emailService: EmailService, |
| 10 | private to: string, |
| 11 | private body: string, |
| 12 | ) {} |
| 13 | |
| 14 | async execute(): Promise<void> { |
| 15 | await this.emailService.send(this.to, this.body); |
| 16 | } |
| 17 | |
| 18 | async undo(): Promise<void> { |
| 19 | await this.emailService.retract(this.to, this.body); |
| 20 | } |
| 21 | |
| 22 | serialize(): string { |
| 23 | return JSON.stringify({ type: 'send-email', to: this.to, body: this.body }); |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | class TaskQueue { |
| 28 | private history: Command[] = []; |
| 29 | |
| 30 | async run(command: Command): Promise<void> { |
| 31 | await command.execute(); |
| 32 | this.history.push(command); // stored for undo/replay |
| 33 | } |
| 34 | |
| 35 | async undoLast(): Promise<void> { |
| 36 | const cmd = this.history.pop(); |
| 37 | if (cmd) await cmd.undo(); |
| 38 | } |
| 39 | } |
Strategy β Pricing algorithms
| 1 | interface PricingStrategy { |
| 2 | calculate(basePrice: number, quantity: number): number; |
| 3 | } |
| 4 | |
| 5 | class FreeTierPricing implements PricingStrategy { |
| 6 | calculate(basePrice: number, quantity: number): number { |
| 7 | return basePrice * quantity; // no discount |
| 8 | } |
| 9 | } |
| 10 | |
| 11 | class PremiumPricing implements PricingStrategy { |
| 12 | calculate(basePrice: number, quantity: number): number { |
| 13 | return basePrice * quantity * 0.9; // 10% off |
| 14 | } |
| 15 | } |
| 16 | |
| 17 | class CheckoutService { |
| 18 | constructor(private pricing: PricingStrategy) {} |
| 19 | |
| 20 | getTotal(items: { price: number; qty: number }[]): number { |
| 21 | return items.reduce( |
| 22 | (sum, item) => sum + this.pricing.calculate(item.price, item.qty), |
| 23 | 0, |
| 24 | ); |
| 25 | } |
| 26 | |
| 27 | // No history, no undo β just a different calculation |
| 28 | setPricing(strategy: PricingStrategy): void { |
| 29 | this.pricing = strategy; |
| 30 | } |
| 31 | } |
Decision Rules
| Signal | Choose | Why |
|---|---|---|
| Need to queue, defer, or schedule operations | Command | Commands are data β store and replay |
| Need undo/redo | Command | Commands carry reverse logic |
| Need to log or audit what was done | Command | Commands are serializable records |
| Need to swap an algorithm at runtime | Strategy | Just plug in a different strategy |
| The behavior is stateless computation | Strategy | No need for undo/history machinery |
| Operations have a receiver (target object) | Command | Command binds to its receiver |
| BullMQ job, cron task, event-sourced action | Command | Jobs are commands |
| Choosing between sort/filter/pricing algorithms | Strategy | Pure algorithm swap |
The Trick Question
"Your notification service chooses between email, SMS, or push at runtime based on user preference. Is this Strategy or Command?"
If you're just choosing which channel to use and sending immediately β that's Strategy. The notification service delegates to the chosen channel strategy.
But if you need to queue notifications for later delivery, retry on failure, and log what was sent β now each notification is a Command. The test: do you need to store, undo, or replay it?
Interview Angles
Q: Can a Command contain a Strategy?
Yes. A Command might use a Strategy internally. For example, a ProcessPaymentCommand (queueable, undoable) might use a PaymentGatewayStrategy (Stripe vs Razorpay) to determine how to process.
Q: How does BullMQ relate to Command pattern? Each BullMQ job is a serialized Command. The job data is the command payload, the processor is the execute() method, and the queue is the invoker. Failed jobs can be retried (re-executed).
Q: In functional programming, are these just functions? Strategy is often a function (a callback). Command is harder to reduce to a function because it carries state (receiver, undo logic, serialization). A closure can be a lightweight command, but you lose serializability and undo.
Q: What's the "Macro Command" variant? A command that contains a list of sub-commands and executes them in sequence. Undo reverses the entire list. This is Command + Composite. Useful for batch operations.