Commands and events

tl;dr: The difference between commands and events may be difficult to grasp in the beginning. In the end it comes down to three rules: Commands produce events. Events represent the past. Commands represent a possible future!

"Commands produce events."

Let's examine this a little more closely, if only for the reason that a command and an event in the code could look very similar:

RegisterUser {
  Email
}

RegisteredUser {
  Email
}

The main difference is what they are used for – their intention.

"Events represent the past."

An event is something that has already happened in the past, so by convention we name it in past tense – RegisteredUser. The event represents the past and will always have taken place no matter what else has happened. It never changes once it has happened – it is immutable.

"Commands represent a possible future!"

A command intends to create a change – an event – but it takes place before the event happens – or doesn't happen. For this purpose they are named with a commanding verb, RegisterUser.

The role of the command is to determine whether the event can happen based on what we currently know. Imagine we have the business rule that two users can not have the same email – it is then up to the command to validate and throw an error if we violate this business rule.

In the code example above, both the command and event look like data, but it makes more sense for the command to be a function. This way it can contain the business logic for email validation.

registerUser(Email) -> Boolean

RegisteredUser {
  Email
}

You may have noticed that the registerUser function returns a boolean value. This is intended and comes from CQRS. The command determines whether it is possible to register a user. If so, the next step is to transfer the event to the event log. However, I'm going to keep this for a future blog post.

This article was written as a guest contribution by Marcus Stenbeck, an enthusiastic JavaScript developer from Stockholm, Sweden. We thank him very much for his great contribution to our blog.

Twitter Facebook LinkedIn

Marcus Stenbeck

JavaScript developer

Writing good code is always going to be a challenge. Choose a simple mental model and you've already won half the battle. You owe it to yourself and your fellow programmers – and that includes you in two months!