Guard

A set of code to ensure some business conditions are met. It uses to be a method called before the execution of the code which is changing the domain, and throws an exception when the conditions fail.

Examples

A method checking whether a UUID already exists in the system:

public function handle(CreateArticleCommand $command): void
{
    $this->checkUUIDAlreadyExists($command->id());
    $article = Article::create($command->id(), $command->title());
    $this->repository->save($article);
}

private function checkUUIDAlreadyExists(UUID $id): void {
    if($this->repository->contains($id)) {
        throw new \InvalidArgumentException("$id already exists in the repository.");
    }
}

Back to the glossary