Organizing domain logic and persistence: from transaction script to data mapper
Differentiate domain logic patterns from transaction script to domain model, and persistence patterns from active record to data mapper.
Contentsand lesson path
On this page
- The Enterprise Logic and Persistence Dilemma
- Organizing Domain Logic: Transaction Script vs. Domain Model
- Organizing Persistence: Active Record vs. Data Mapper
- Orchestrating Persistence: Repository and Unit of Work
Lessons of Design Patterns
- Patterns as named trade-offs: forces, solution, consequences Concept · 15 min
- Varying behavior: strategy, command and observer Concept · 25 min
- Shaping boundaries: adapter, facade and decorator Concept · 20 min
- Organizing domain logic and persistence: from transaction script to data mapper Concept · 25 min
- Replacing a conditional maze with strategy and adapter Lab · 30 min
- Pattern selection and overuse check Knowledge check · 8 questions
What you will learn
- Apply repository, unit of work and service layer to separate domain logic from persistence and transport.
- Choose between transaction script and domain model for a module's business logic, and between active record and data mapper persistence, from the domain's complexity and rate of change.
Prerequisites: Software Design Principles
01. The Enterprise Logic and Persistence Dilemma
In enterprise software development, two fundamental architectural challenges dictate system longevity and maintainability: how business logic is organized, and how that logic interacts with relational databases. Martin Fowler captured these recurring structural strategies in his seminal work, Patterns of Enterprise Application Architecture (PEAA).
Every engineering team makes choices along these two axes, often unconsciously. A startup team building an initial prototype might write procedural SQL queries directly inside HTTP route handlers. As the product scales into an enterprise platform managing millions of transactions across complex regulatory domains, that initial procedural approach becomes an unmaintainable swamp of duplicated validation checks and scattered SQL statements.
Understanding the architectural progression from Transaction Script to Domain Model, and from Active Record to Data Mapper, provides architects with the criteria needed to select the appropriate pattern based on business complexity and rate of change.
02. Organizing Domain Logic: Transaction Script vs. Domain Model
Business logic encompasses all calculations, validations, workflow routing, and state transitions that reflect real-world business rules. Fowler categorizes domain logic into two primary patterns:
1. Transaction Script
A Transaction Script organizes business logic into a single procedure for each distinct business transaction. When a user submits a "Cancel Subscription" request, the system executes a dedicated cancelSubscription() procedure that opens a database connection, performs validation checks, executes update queries, and triggers an email.
- Forces and Strengths: Simple to understand, straightforward to write, and carries minimal architectural overhead. For simple CRUD applications, reporting tools, or internal batch jobs with stable rules, Transaction Script is frequently the fastest and most cost-effective architecture.
- The Breaking Point: As business rules multiply, different transaction scripts inevitably require the same calculations (such as calculating tax or verifying customer credit). Because logic is trapped inside procedural scripts, developers copy-paste code. When a rule changes, engineers must hunt down and update fifteen separate scripts, inevitably missing several and introducing production bugs.
2. Domain Model
A Domain Model organizes business logic as an interconnected network of rich objects, where each entity encapsulates both state and the operations that guard that state. Instead of procedural scripts manipulating passive data transfer objects, domain entities (such as Order, Customer, and Policy) actively enforce their own business invariants.
- Forces and Strengths: Eliminates duplicated business logic by co-locating rules directly with data. Complex rules involving polymorphic calculations (e.g., varying interest calculations across loan types) are handled cleanly through object-oriented inheritance or strategy delegates.
- The Trade-off: High initial complexity. Building a Domain Model requires deep modeling expertise, object-relational mapping machinery, and disciplined separation between pure domain rules and external infrastructure.
03. Organizing Persistence: Active Record vs. Data Mapper
Once domain logic is structured, the system must persist state to durable storage. The two primary object-relational structural patterns are Active Record and Data Mapper:
1. Active Record
In Active Record, an object represents a single row in a database table or view, encapsulating both data access and business logic. An entity class typically includes properties matching the table columns alongside static lookup methods (User.findById()) and instance persistence methods (user.save(), user.delete()). Popularized by Ruby on Rails and Django, Active Record provides exceptional developer ergonomics for rapid prototyping.
- Architectural Coupling: Active Record establishes tight bidirectional coupling between the database schema and the in-memory object model. If the database schema is normalized into three separate tables, the developer is forced to mirror those tables in their class structure.
- Testing Friction: Because domain entities contain built-in SQL or database connection logic, unit testing business rules without spinning up a live test database is notoriously difficult.
2. Data Mapper The Data Mapper pattern establishes a layer of dedicated mappers that moves data between domain objects and database storage while keeping them completely independent of one another. The domain entity has zero knowledge of database tables, column names, or connection pools; it is a pure in-memory object (POJO in Java, plain dataclass in Python).
- Architectural Decoupling: The domain model and the database schema can evolve along completely separate trajectories. An aggregate root in the domain model can map onto five normalized database tables, or vice versa, without leaking relational details into business logic.
- Testability Superpower: Because domain entities possess zero database dependencies, unit tests execute purely in-memory at lightning speed without requiring database containers or mocks.
04. Orchestrating Persistence: Repository and Unit of Work
In systems employing a Domain Model and Data Mapper, two complementary patterns complete the architecture:
- Repository: A Repository mediates between the domain and data mapping layers, acting like an in-memory collection of domain aggregate roots. Client code interacts with the repository through domain-centric query methods (
orderRepo.findOpenOrdersByCustomer(customerId)) rather than raw SQL strings or database session handles. - Unit of Work: When a complex business operation modifies multiple domain entities across several repositories, saving each entity individually risks leaving the database in an inconsistent, partially updated state if a server crashes mid-flight. A Unit of Work maintains an active list of all objects affected by a business transaction and coordinates the writing out of changes in a single atomic database transaction at the conclusion of the use case.
Together, Repository, Unit of Work, and Data Mapper cleanly isolate business logic from transport protocols and storage mechanisms.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.