Learn
Domain
Scalars

Scalars

Scalars are the basic building blocks of a domain model. They are the primitive types that represent the data in your domain. They are the nouns of your domain model. They can have business rules attached to them.

They should be implemented using the Newtype pattern.

Examples of Scalars:

  • Email: Represents an email address, ensuring it meets specific format requirements.
  • JobTitle: Encapsulates the concept of a job title within the organization.
  • NonEmptyString: Guarantees that the string is not empty.
  • PositiveInteger: Represents an integer, ensuring it is positive.
  • UserId: Uniquely identifies a user within the system.

Defining a Scalar

domain/src/todolist_scalar.rs
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TaskName(pub String);

In this snippet, TaskName is a new type encapsulating a String. It represents the name of a task in a to-do list application.

Implementing Business Logic

domain/src/todolist_scalar.rs
impl TryFrom<String> for TaskName {
    type Error = String;
 
    fn try_from(value: String) -> Result<Self, Self::Error> {
        if value.is_empty() {
            return Err("Task name cannot be empty".to_string());
        }
 
        Ok(Self(value))
    }
}

Here, the try_from method enforces a business rule for the TaskName: it cannot be empty. If an empty string is provided, an error is returned, thus ensuring that every task has a meaningful name.