Part 8: Command Design Patterns (GoF)

Today, I discussed the Command Patterns under the Behavioral Design Patterns, you learned how to implement them, their similarities, and when to use which.

Hello ā€œšŸ‘‹

Welcome to another week, another opportunity to become a Great Backend Engineer.

Todayā€™s issue is brought to you by Masteringbackend ā†’ A great resource for backend engineers. We offer next-level backend engineering training and exclusive resources.

Before we get started, I have a few announcements:

If youā€™re like me, you probably spent hours watching YouTube tutorials, reading endless blogs, and following step-by-step guidesā€”only to find yourself still struggling to build real-world applications.

Itā€™s called ā€œtutorial hell,ā€ and itā€™s where a lot of backend engineers get stuck.

I know because I wasted 4 years there.

It wasnā€™t until I switched to Project-Based Learning that things started to change. Building real applications allowed me to finally connect the dots between concepts and implementation, gain confidence, and showcase my skills through tangible projects.

Thatā€™s why I created MBProjectsā€”to help backend engineers like you escape tutorial hell and gain real experience by working on practical, hands-on projects.

What is MBProjects?

MBProjects is a project-based learning platform designed specifically for backend engineers. Itā€™s your opportunity to work on 100+ real-world projects that mirror actual problems youā€™d encounter in the industry.

With MBProjects, youā€™ll get access to:

  • Pre-built Frontend: Skip the hassle of designing the Frontend and focus purely on building powerful backends.

  • Comprehensive Project Requirement Documents (PRDs): Know exactly what to build and why, with clear goals and specifications.

  • Starter Files & Complete Setup Guides: Jump right into coding with everything set up for you.

  • Task Breakdowns & Progress Tracking: Step-by-step instructions to guide you from start to finish.

  • Community Support: Connect with a group of builders like yourself to share progress, get feedback, and collaborate on projects.

  • Certificates of Completion: Showcase your skills to employers or on LinkedIn as you complete each project.

Why MBProjects?

Unlike traditional learning methods, MBProjects isnā€™t about memorizing syntax or following cookie-cutter tutorials. Itā€™s about building, problem-solving, and developing the skills you need to become a confident backend engineer.

I built this platform to be the solution I wish I had years agoā€”an environment where you can create, experiment, and gain practical experience that actually counts.

Are you ready to unlock your potential and build something amazing?

All of this is available for just $12/monthā€”but only for a limited time! After launch, the price will go up to $24/month.

Interested? Reply ā€œInterestedā€ or šŸ‘‰ Claim Your Special Launch Price Now šŸ‘ˆ

When you log in, click on ā€œUnlock Pro Nowā€

Now, back to the business of today.

In this series, I will explore Design Patterns, their types, the GoF design patterns, drawbacks, and benefits for backend engineers.

This comes from my new Vue.js book on ā€œVue Design Patternsā€. However, Iā€™m only transferring the knowledge to backend engineers in this series.

Today, we will explore the Command Design Patterns under the Behavioral Design Patterns.

Letā€™s get started quickly.

What is a Command Pattern?

The command pattern encapsulates a request as an object, thereby allowing for the parameterization of clients with queues, requests, and operations.

The Command Pattern is useful because it encapsulates requests or actions as objects, allowing you to parameterize methods with different requests, queue or log operations, and support undoable operations.

It helps decouple the object that invokes the operation from the object that performs it. This pattern is particularly beneficial when you need to execute, delay, undo, or store operations, making it a powerful tool for implementing features like transaction handling, macro operations, or task scheduling.

As an example, in a task scheduler, you might queue commands for execution at specific times or under certain conditions. The Command Pattern allows you to store and execute these tasks at the right time.

// Command Interface
class Command {
    execute() {
        throw new Error("Method 'execute()' must be implemented.");
    }
}

First, we start by creating the command interface with the execute method to be implemented.


// Receiver: Task Handler
class TaskHandler {
    runTask(taskName) {
        console.log(`Executing task: ${taskName}`);
    }
}

Next, we create a task handler class that will run all our tasks in the background.

// Concrete Command: Run Task
class RunTaskCommand extends Command {
    constructor(taskHandler, taskName) {
        super();
        this.taskHandler = taskHandler;
        this.taskName = taskName;
    }

    execute() {
        this.taskHandler.runTask(this.taskName);
    }
}

Next, we created the RunTaskCommand class and extended the Command class we had created before. This will allow us to override the execute function and perform individual tasks.

// Invoker: Task Scheduler
class TaskScheduler {
    constructor() {
        this.queue = [];
    }

    scheduleTask(command) {
        this.queue.push(command);
    }

    runTasks() {
        while (this.queue.length > 0) {
            const command = this.queue.shift();
            command.execute();
        }
    }
}

Next, we create the TaskScheduler class with the scheduleTask and runTasks methods which are responsible for pushing tasks to queue and running the individual tasks using the command pattern.

// Client code
const taskHandler = new TaskHandler();
const scheduler = new TaskScheduler();

scheduler.scheduleTask(new RunTaskCommand(taskHandler, "Backup Database"));
scheduler.scheduleTask(new RunTaskCommand(taskHandler, "Send Reports"));
scheduler.scheduleTask(new RunTaskCommand(taskHandler, "Run Security Scan"));

scheduler.runTasks();  // Output: Executing task: Backup Database
                       // Executing task: Send Reports
                       // Executing task: Run Security Scan

Lastly, this is how you can use the command pattern in your client code to run scheduled tasks.

The Command Pattern allows you to schedule tasks for execution and maintain a queue of commands, making it easy to delay, batch, or retry operations. It provides flexibility in executing commands at specific times or under certain conditions, making it ideal for task-scheduling systems.

Why the Command Pattern is Useful

The Command Pattern is particularly beneficial in scenarios where you need to decouple the sender of a request from the object that performs it. Its main advantages include:

  • Decouples sender from receiver: It separates the invoker from the receiver, promoting loose coupling and flexibility.

  • Supports undo/redo functionality: It makes it easy to implement undoable operations by storing commands and their states.

  • Enables queuing and logging: Commands can be queued, logged, or scheduled for later execution, supporting features like task scheduling and transaction management.

  • Encapsulates requests: Commands encapsulate requests as objects, making it easier to parameterize objects with different operations.

  • Supports macro commands: You can group multiple commands into a single macro command, allowing for composite operations.

By using the Command Pattern, you can build systems that are more modular, flexible, and easier to extend, especially when handling complex operations or user interactions.

That will be all for today. I like to keep this newsletter short.

Today, I discussed the Command Patterns, you learned how to implement them, their similarities, and when to use which.

Next week, I will explore the Chain of Responsibility Pattern under Behavioural Design Patterns.

Donā€™t miss it. Share with a friend

Did you learn any new things from this newsletter this week? Please reply to this email and let me know. Feedback like this encourages me to keep going.

See you on Next Week.

Remember to start learning backend engineering from our courses:

Top 5 Remote Backend Jobs this week

Here are the top 5 Backend Jobs you can apply to now.

šŸ‘Øā€šŸ’» Stripe
āœļø Backend / API Engineer, Local Payment Methods
šŸ“Remote, Dublin, Ireland
šŸ’° Click on Apply for salary details
Click here to Apply for this role.

šŸ‘Øā€šŸ’» LaunchDarkly
āœļø Backend Engineer - AI
šŸ“Remote, US
šŸ’° Click on Apply for salary details
Click here to Apply for this role.

šŸ‘Øā€šŸ’» Pinterest
āœļø Backend Software Engineer
šŸ“Remote, Worldwide
šŸ’° Click on Apply for salary details
Click here to Apply for this role.

šŸ‘Øā€šŸ’»Sportradar
āœļø Backend Engineer
šŸ“Remote
šŸ’° Click on Apply for salary details
Click here to Apply for this role.

Want more Remote Backend Jobs? Visit GetBackendJobs.com

Backend Engineering Resources

Whenever you're ready

There are 4 ways I can help you become a great backend engineer:

1. The MB Platform: Join 1000+ backend engineers learning backend engineering on the MB platform. Build real-world backend projects, track your learnings and set schedules, learn from expert-vetted courses and roadmaps, and solve backend engineering tasks, exercises, and challenges.

2. ā€‹The MB Academy:ā€‹ The ā€œMB Academyā€ is a 6-month intensive Advanced Backend Engineering BootCamp to produce great backend engineers.

3. MB Video-Based Courses: Join 1000+ backend engineers who learn from our meticulously crafted courses designed to empower you with the knowledge and skills you need to excel in backend development.

4. GetBackendJobs: Access 1000+ tailored backend engineering jobs, manage and track all your job applications, create a job streak, and never miss applying. Lastly, you can hire backend engineers anywhere in the world.

LAST WORD šŸ‘‹ 

How am I doing?

I love hearing from readers, and I'm always looking for feedback. How am I doing with The Backend Weekly? Is there anything you'd like to see more or less of? Which aspects of the newsletter do you enjoy the most?

Hit reply and say hello - I'd love to hear from you!

Stay awesome,
Solomon

I moved my newsletter from Substack to Beehiiv, and it's been an amazing journey. Start yours here.

Reply

or to participate.