Domain Modeling

Tactical Patterns

Basic Concepts: Entities, Value Objects, and Aggregates

Entities

  • Entities instances are objects whose state changes over time,
    but whose identity remains the same

The same Person, 7 Years Later
Figure 1. The same Person, 7 Years Later

Entities (1/2)

  • Entities are classes that represent domain concepts

  • They should have business logic

  • Their instances have an unique identifier,
    which remains the same throughout its lifecycle.

  • They are mutable

The Book Entity
Figure 2. The Book Entity

Entities (2/2)

  • Identities should be different from Object Ids (OID)

  • Entities are persistence agnostic

The Credit Card Entity
Figure 3. The Credit Card Entity

Value Objects

  • Value Objects are containers of attributes

  • They are immutable and have no identity

  • They may be shared between different entities

The Account Number Value Object
Figure 4. The Account Number Value Object

Value Objects

Immutable
  • Attributes must be read only

  • Operations must not have side-effect

The Money Value Object
Figure 5. The Money Value Object

Value Objects

  • Value Objects have their own behavior and significance to the model

The Email Address Value Object
Figure 6. The Email Address Value Object

Value Objects

  • Sometimes, Value Objects are Entities in different contexts

Addresses
Figure 7. Addresses

Value Objects and Entities

Value ObjectEntity

Identity

No (but may be an identifier)

Unique

Mutability

Should be immutable

Usually mutable

Equality

Comparison by value

Comparison by Identity

Scale

Typically small

Any size

Operation behavior

No side-effects

Can have side-effects

Serializable

Should be serializable

No need

Defaults

Often have a natural default

No natural default

User Interface

Dedicated widget

Tailored (hand coded)

Business rules

Limited/No

Encapsulates behavior and rules

Aggregates

  • Cluster of entities and value objects

  • An aggregate defines the boundaries,
    its components are only accessible through an Aggregate Root


Diagram

Aggregates

  • The objects inside an aggregate are persisted together (within the same transaction)

  • The aggregate ensures that consistency rules are applied synchronously

The Order Aggregate
Figure 8. The Order Aggregate

Aggregate Root

  • An Entity that has the responsibility of ensuring the aggregate invariants

  • The only entry point of the aggregation


Diagram

Aggregate Rules

  • External classes can only have associations with the Aggregate Root

  • External classes can use the other aggregated classes (temporary links)

    • For instance, as the return type of an operation

The Book Aggregate
Figure 9. The Book Aggregate

Aggregates Simplify Things

  • Since aggregated objects cannot be modified from outside, invariants are simpler to implement

    • for instance, bidirectional associations

  • Aggregates may be nested

Diagram

Aggregates: Summary

  • A cluster of objects treated as a single unit

  • Only accessed through its Root Entity

  • Often associated to a State Machine

  • The atomic unit for any transactional behavior.

  • Responsible for maintaining business invariants.

More Concepts: Factories, Repositories, Modules, and Services

Factories

  • Creating aggregates may be complex: several objects must be created and connected during the creation

  • In this case, developers use Factory Methods

The Book Factory
Figure 10. The Book Factory

Factories

  • Factories may also be used to create Value Objects

  • See the Flyweight design pattern

    • Minimizes object creation

The Book Factory
Figure 11. The Book Factory

Who implements the Factory Methods?

  • In most cases, the root is a good choice

    • The root controls all aggregated objects

  • Otherwise, use a separate factory

    • When the root is not responsible for some aggregated objects

Factories and Constructors

  • In some cases, a factory method is not needed:

    • The construction is simples

    • All required attributes are available

    • The construction is for Value Objects

Repositories

  • Abstraction that encapsulates a storage mechanism

  • Provides the illusion of an in-memory collection of Aggregate Root objects

  • A way to retrieve and store domain objects

  • Provide methods that select objects based on criteria meaningful to domain experts

The Book Repository
Figure 12. The Book Repository

Repository Approaches

  • One Repository per Aggregate (very explicit)

  • Generic Repository

  • One Repository per aggregate built upon Generic Repository Strategy

  • Generic Repository with Specifications

One Repository per Aggregate

  • Provides explicit methods

The Book Repository
Figure 13. The Book Repository
AdvantagesDrawbacks
  • Very explicit and intentional interface so it reads better

  • Restrict data access to what you want to allow developers

  • Can more easily optimize each query

  • Very manual process to create

  • Cannot reuse methods for other purposes

  • Extension requires editing the class

Generic Repository

  • Provides generic, open query methods

Generic Repository
Figure 14. Generic Repository
AdvantagesDrawbacks
  • Very re-usable; write once, use everywhere

  • Easy to code-gen for extension using partial classes

  • More directly mimics database operations against a table

  • Not intentional

  • Little control over what happens on insert, delete, etc.

  • Exposes methods you may not want exposed

One Repository per Aggregate with Generic Strategy

  • Mixes the best of both worlds

Generic Repository
Figure 15. Generic Repository
AdvantagesDrawbacks
  • Very explicit and intentional interface so it reads better

  • Restrict data access to what you want to allow developers

  • Can more easily optimize each query

  • Standardize data access mechanics

  • Simplify query construction in the repository

  • Easier to swap out persistence technology (database / in-memory)

  • Composition over Inheritance

  • More code than Generic Repository

  • More moving pieces

Generic Repository with Specifications

  • Generic functionality with explicit query functionality

Generic Repository
Figure 16. Generic Repository
AdvantagesDrawbacks
  • Extremely intention revealing

  • Same reusability as Generic Repository

  • Extend by creating new specifications

  • Specifications can be used for more than querying (e.g. rules, etc.)

  • Add, Remove, etc. may still be limited

  • May be difficult to tie into your ORM

Specifications

Specification
Figure 17. Specification
  • Simple interface for defining criteria

  • Similar to the Query Object pattern

  • Easy to test

  • Easy to chain together for more complex queries: And, Or, Not

Modules

  • aka packages

  • Contains cohesive set of concepts

    • Break up your domain to reduce complexity

  • Becomes part of the ubiquitous language

  • Helps with decoupling

  • Aids in extensibility

When you place some classes together in a Module, you are telling the next developer who looks at your design to think about them together.

Service

  • The first client for the domain model

  • Assembles stateless operations that do not conceptually belong to Entities nor to Value Objects

  • Services are a natural part of a model

  • Domain services should be distinguished from other services (application, infrastructural)

Service

Application Service
Figure 18. Application Service

Service Examples

Services
Figure 19. Services
Best practices
  • Use domain services sparingly

  • Focus on domain logic, not application or infrastructure concerns

  • Name services using verbs or verb phrases to reflect their behavior

Events

Domain Events

Something happened that domain experts care about

  • Event captures a change to the model so different model components can observe these changes and react accordingly

  • A record of a business-significant occurrence within a Bounded Context

Examples:
  • New Borrowing

  • Buy Book

Motivation

  • Entities are responsible for tracking their states

    • Often, changes are not explicit

    • Changes can be tracked, but are hard to explain

  • In a distributed system

    • Changes must be propagated to ensure consistency

Using Domain Events

  • Events model actions as a series of discrete events

  • Represented as domain objects

  • Full-fledged part of the domain model

Modeling Domain Events

  • Immutable

  • Contains a domain description and entity identifiers

  • Sometimes contain timestamps and sender id

  • Sometimes contains an id

Domain Events
Figure 20. Domain Events

Domain Modeling