Skip to main content

Sign in to CleanKata

Track your progress, earn XP, and unlock every lesson.

By signing in you agree to our Terms of Use and Privacy Policy.

Design Patterns80 XP8 min

Command: Encapsulating Requests

Transform a request into a standalone object — enabling undo/redo, queuing, logging, and deferred execution of operations.

Why this matters

When you call a method directly, the action evaporates — there is no record, no way to reverse it, no way to defer or queue it. The Command pattern turns each operation into an object with execute() and undo(). A history stack of Command objects gives you Ctrl+Z for free. The same approach enables scheduled tasks, job queues, audit logs, and transaction rollbacks.

Beyond undo/redo

Command objects can be serialized and stored — enabling deferred execution (run this at midnight), distributed task queues (Celery, Bull), and event sourcing (the entire history of changes is a list of commands that can be replayed). Every git commit is a Command. Every database migration is a Command. The pattern is ubiquitous once you see it.

💡Key takeaway

Whenever you need undo/redo or operation history, Command turns actions into objects that can be stored, replayed, and reversed — the history stack does the rest.

🔧 Some exercises may still have errors. If something seems wrong, use the Feedback button (bottom-right of the page) to report it — it helps us fix it fast.

Hint: Whenever you need undo/redo or operation history, Command turns actions into objects that can be stored, replayed, and reversed.

✗ Your version