liveBook · Manning

CanExecute/Execute pattern

As explained in Unit Testing Principles, Practices, and Patterns

The CanExecute/Execute pattern separates a domain operation's precondition checks from the execution of the operation while keeping both decisions in the domain model.

Separates a domain operation’s precondition check from its execution while keeping both decisions in the domain model. A CanDo() method reports whether Do() may proceed; Do() enforces that result as a precondition. section 7.6 section 7.4

Balances three competing concerns:

  • Keeps business decisions out of controllers, which can act on the domain model’s result. section 7.4
  • Avoids unnecessary external reads when the operation is already known to be invalid. section 7.4
  • Adds a separate decision step and therefore increases controller complexity rather than preserving maximum controller simplicity. section 7.6

Changing a confirmed email

Defines CanChangeEmail() to return an error when IsEmailConfirmed is true and null otherwise. The controller checks this method before loading Company; ChangeEmail() then requires the check to succeed before updating the user. If the email changes, the domain object can record an EmailChangedEvent for later notification.

How Unit Testing Principles, Practices, and Patterns covers it

How deep it goes
Defines the pairing, demonstrates its precondition mechanics, and stops short of a general implementation taxonomy.
Examples
Uses confirmed-email validation, conditional company loading, email-change events, and a test of corporate-to-noncorporate conversion.
What it assumes
Assumes domain models, controllers, external dependencies, and unit testing while teaching their responsibility trade-offs through refactoring.
What you can do after
Apply it by pairing each domain operation with a precondition query and enforcing that query before execution.
How it connects
Connects domain models, controllers, performance, domain events, external dependencies, and unit testing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Unit Testing Principles, Practices, and Patterns. The section links point to the parts of the book it draws on.