60
April 2014 Domain Driven Design Arnaud Bouchez

Delphi Domain-Driven Design Presentation

Embed Size (px)

DESCRIPTION

The Domain-Driven Design (DDD) is a great set of methodology able to leverage your business knowledge into innovative software. Introduces DDD patterns and ORM / SOA, in the context of modern Delphi applications and the Open Source Synopse mORMot framework.

Citation preview

Page 1: Delphi Domain-Driven Design Presentation

April 2014

Domain Driven DesignArnaud Bouchez

Page 2: Delphi Domain-Driven Design Presentation

April 2014

Domain Driven Design (DDD) Is DDD good for you? Modeling your objects Patterns Architecture practice

Domain Driven Design

Page 3: Delphi Domain-Driven Design Presentation

April 2014

Domain Driven Design

Domain Driven Design

Sounds pretty much nice and easy

Page 4: Delphi Domain-Driven Design Presentation

April 2014

Domain Driven Design

Domain Driven Design

Model-Driven

Design

UbiquitousLanguage

definemodel with

BoundedContexts

identifyscope with

Services

processmodel with

Entities

expressmodel with

Value Objects

expressmodel with

Clean/Layered/Hexagonal

Architecture

isolatedomain with

Events

express statechanges with

RAD

exclude

Repositories

access with Aggregates

encapsulate with

Factories

instantiated by

encapsulate with

instantiated by

access with instantiated by

What the fox says

Page 5: Delphi Domain-Driven Design Presentation

April 2014

Domain Driven Design Focus on the Domain Define Bounded contexts within this domain Create an evolving Model of the domain Use Ubiquitous Language in model and code Identify objects: Values, Entities, Aggregates Isolate the domain from other kind of concern Publish the domain as well-defined Services Integrate the domain services with existing

Domain Driven Design

Page 6: Delphi Domain-Driven Design Presentation

April 2014

DDD pre-requisites

Identified and well-bounded domain e.g. your business target should be clearly

identified Access to domain experts

need iterative creative collaboration Skilled team, able to write clean code

more about code expressiveness than technology You want your internal team to accumulate

knowledge of the domain therefore, outsourcing may be constrained

to applications, not the core domain

Domain Driven Design

Page 7: Delphi Domain-Driven Design Presentation

April 2014

Role of Patterns

In your code: once: it’s a fluke, twice: its coincidence, three times: it’s a Pattern!

Discovered (observed), not invented Except for their name

Elevate effectiveness of our communication A ‘shorthand’ for more complex ideas

Domain Driven Design

Page 8: Delphi Domain-Driven Design Presentation

April 2014

DDD: the premise

Writing software is actually straightforward

Determining what to write is hard! The Key to success is understanding

the Problem Domain intimately Not to use the latest shiny technology

Domain Driven Design

Page 9: Delphi Domain-Driven Design Presentation

April 2014

Check your concerns

You have a specific problem to solve Your goal is identified , but your business is exploring

You do not know how to accomplish your goal You need to bring clarity, and solve inner complexity

e.g. modeling a lot of rules DDD is not to build simple applications – RAD is there

DDD meets your strategic goals DDD is to be used where you will get your business money,

and make you distinctive from your competitors You don't have all of these, but at least one or two

Domain Driven Design

Page 10: Delphi Domain-Driven Design Presentation

April 2014

Domain Driven Design

Domain Driven Design

Model-Driven

Design

UbiquitousLanguage

definemodel with

BoundedContexts

identifyscope with

Services

processmodel with

Entities

expressmodel with

Value Objects

expressmodel with

Clean/Layered/Hexagonal

Architecture

isolatedomain with

Events

express statechanges with

RAD

exclude

Repositories

access with Aggregates

encapsulate with

Factories

instantiated by

encapsulate with

instantiated by

access with instantiated by

What the fox says

Page 11: Delphi Domain-Driven Design Presentation

April 2014

Ubiquitous Language

Developers and Business People move in different worlds have different languages to express their

ideas the other 10th kind of people

how do not know about binary… use company- or industry-standard terminology

Domain Driven Design

Page 12: Delphi Domain-Driven Design Presentation

April 2014

Ubiquitous Language

Developers and Business People

Domain Driven Design

Page 13: Delphi Domain-Driven Design Presentation

April 2014

Ubiquitous Language

Language should be Ubiquitous In classes, methods, variables, even in tests Behavior-Driven Development

Conversing using the same language ‘Solution smells’ detected by Domain Experts Discovery of new domain concepts by

developers Shared learning by all involved Model must evolve: always remove ambiguities

Domain Driven Design

Page 14: Delphi Domain-Driven Design Presentation

April 2014

Ubiquitous Language

The best of both worlds

Domain Driven Design

Page 15: Delphi Domain-Driven Design Presentation

April 2014

Domain Driven Design

Domain Driven Design

Model-Driven

Design

UbiquitousLanguage

definemodel with

BoundedContexts

identifyscope with

Services

processmodel with

Entities

expressmodel with

Value Objects

expressmodel with

Clean/Layered/Hexagonal

Architecture

isolatedomain with

Events

express statechanges with

RAD

exclude

Repositories

access with Aggregates

encapsulate with

Factories

instantiated by

encapsulate with

instantiated by

access with instantiated by

What the fox says

Page 16: Delphi Domain-Driven Design Presentation

April 2014

Modeling a Domain

What do we call Domain here? The domain represents a sphere of

knowledge, influence or activity As a result

The domain has to be clearly identified Your software is expected to solve a set of

problems related to this domain You may have several domains to

modelize

Domain Driven Design

Page 17: Delphi Domain-Driven Design Presentation

April 2014

Modeling

DDD is some case of Model-Driven Design Its purpose is to create a model

of a given domain The code itself will express the model:

as a consequence, any code refactoring means changing the model, and vice-versa

Domain Driven Design

Page 18: Delphi Domain-Driven Design Presentation

April 2014

Modeling

Be honest: reality is just too big Modeling is about filtering the reality

for a given use context “All models are wrong, some are useful”

G. Box, statistician Several models may coexist for a given

reality, depending of the knowledge level involved

what we call a Bounded Context

Domain Driven Design

Page 19: Delphi Domain-Driven Design Presentation

April 2014

Modeling

Bounded Context The same reality will appear several times

in several models Don't be afraid if the same reality is defined

several times in your domain code, each class for its context

You need to identify your current model Just as in Google Maps the zoom level or the kind

of map shows several models of the same world Even models could be abstracted

This is what DDD does: code abstracts a model

Domain Driven Design

Page 20: Delphi Domain-Driven Design Presentation

April 2014

Modeling

Modeling is about forgetting the details Focus on the essentials Given an objective knowledge level Specific to a bounded context

Domain Driven Design

Page 21: Delphi Domain-Driven Design Presentation

April 2014

Modeling

Model State Static

To abstract a given state of the reality Dynamic

To abstract how reality evolves (i.e. its behavior) Changes are mostly continuous in reality Dynamic modeling will create

static snapshots of the reality (called state transitions)

It will embrace the deterministic nature of computers

Domain Driven Design

Page 22: Delphi Domain-Driven Design Presentation

April 2014

Modeling

State brings complexity It is a fact we won’t argue So our code should be as stateless as possible

Some patterns Try to always separate value and time in state Reduce statefulness to only the necessary Implement your logic as state machines

instead of blocking code or sessions Persistence should handle one-way

transactions

Domain Driven Design

Page 23: Delphi Domain-Driven Design Presentation

April 2014

Modeling

DDD expresses static model state using Immutable Value Objects

To define a static value Entity Objects (or Entities)

To refer to a given state of given identity For instance, the same identity (named "John

Doe") may be, at a given state, single and minor, then, at another state, married and adult. The model will help to express the given states, and the state transitions between them (e.g. John's marriage)

Domain Driven Design

Page 24: Delphi Domain-Driven Design Presentation

April 2014

Modeling

DDD expresses dynamic model state Via Factory / Repository / Unit Of Work

patterns Code will get given state of the model Then process its domain knowledge And return the new state

Via Events When a system does change its state very

often See Event-Driven Design or Event Sourcing

Domain Driven Design

Page 25: Delphi Domain-Driven Design Presentation

April 2014

Modeling

To express the modularity of the model Partitioning

the more your elements have a separated concern, the better, since the model will be more stateless

we will create a lot of objects (interface segregation) not abuse of inheritance

are you focusing on the domain, or on your code?

Grouping to express constraints, elements may be grouped usually, no more than 6/8 elements per diagram Aggregate Root to group objects to model constraints

Domain Driven Design

Page 26: Delphi Domain-Driven Design Presentation

April 2014

Domain Driven Design

Domain Driven Design

Model-Driven

Design

UbiquitousLanguage

definemodel with

BoundedContexts

identifyscope with

Services

processmodel with

Entities

expressmodel with

Value Objects

expressmodel with

Clean/Layered/Hexagonal

Architecture

isolatedomain with

Events

express statechanges with

RAD

exclude

Repositories

access with Aggregates

encapsulate with

Factories

instantiated by

encapsulate with

instantiated by

access with instantiated by

What the fox says

Page 27: Delphi Domain-Driven Design Presentation

April 2014

Value Objects and Entities

Model-level structures Reduce the model into objects or structured

types May be class or record

Make the implicit explicit Naming should follow the Ubiquitous language Define dedicated types

e.g. a TPhoneNumber instead of plain RawUTF8 Use dynamic structures like TDocVariant

Especially during initial exploring phase

Domain Driven Design

Page 28: Delphi Domain-Driven Design Presentation

April 2014

Value Objects and Entities

Model-level representation will define Value Objects

contain attributes (value, size) but no conceptual identity e.g. money bills, or seats in a Rock concert

Entity objects are not defined by their attributes (values),but their thread of continuity, signified by an identity e.g. persons, or seats in most planes, as each

one is unique and identified.

Domain Driven Design

Page 29: Delphi Domain-Driven Design Presentation

April 2014

Value Objects and Entities

Value objects are immutable by definition So should be handled as read-only They are incapable of change once they are

created Seeking side-effect-free functions

concept borrowed by DDD to functional languages

Domain Driven Design

Page 30: Delphi Domain-Driven Design Presentation

April 2014

Value Objects and Entities

Entities will very likely have an ID field To identify a given reality To model the thread of continuity of this

identity But this ID is an implementation detail

Only used at Persistence Layer level At the Domain Layer level, you should not

access Entities individually,but via a special Entity bounded to a given context, named Aggregate Root

Domain Driven Design

Page 31: Delphi Domain-Driven Design Presentation

April 2014

Value Objects and Entities

Aggregates are a particular case of Entities Defined as collection of objects

nested Values and/or Entities That are grouped together by a root Entity

otherwise known as an Aggregate Root which scope has been defined by execution context Allow composition (or grouping) in the model

For persistence, are the transactional boundary May be NoSQL, or at least via ORM

Domain Driven Design

Page 32: Delphi Domain-Driven Design Presentation

April 2014

DTO & Events

Isolate the domain from the outer world But if your domain is properly defined, most

of your Value Objects may be used with no translation, so could be used as DTO classes

Even Entities may be transmitted directly since their methods should not refer to

anything but their internal properties In short: be realistic/lazy, but paranoid

Domain Driven Design

Page 33: Delphi Domain-Driven Design Presentation

April 2014

DTO & Events

Data Transfer Objects (DTO) are transmission objects not send the domain objects across the

wire Anti-Corruption Layer i.e. separate your layers Create gatekeepers that work to prevent non-

domain concepts from leaking into your model

Domain Driven Design

Page 34: Delphi Domain-Driven Design Presentation

April 2014

DTO & Events

Commands and Events are some kind of DTO since they communicate data about an

event and they themselves encapsulate no behavior in mORMot, we try to let the framework do all

the plumbing, letting those types be implemented via interfaces, avoiding the need to define them by hand

Domain Driven Design

Page 35: Delphi Domain-Driven Design Presentation

April 2014

Factory & Repository

Factory pattern is used to create class instances

In strongly-typed OOP (like in Delphi, Java or C#), this pattern is in fact its constructor method and associated class type definition, which will define a fixed set of properties and methods at compilation

not as e.g. in JavaScript or most other script languages

is used to create interface instances See SOLID principles (mainly Liskov substitution)

Domain Driven Design

Page 36: Delphi Domain-Driven Design Presentation

April 2014

Factory & Repository

Repository pattern used to save and dispense each Aggregate Root

Can use e.g. TSQLRecord “Layer Supertype” ORM / CRUD interface

Or dedicated repository classes Dedicated interfaces Following Ubiquitous domain language (not CRUD pattern)

Saving data is a concern orthogonal to the model DDD architects claim that

persistence is infrastructure, not domain Domain layer should be abstracted (via IoC/injection) from it

Domain Driven Design

Page 37: Delphi Domain-Driven Design Presentation

April 2014

Domain Driven Design

Domain Driven Design

Model-Driven

Design

UbiquitousLanguage

definemodel with

BoundedContexts

identifyscope with

Services

processmodel with

Entities

expressmodel with

Value Objects

expressmodel with

Clean/Layered/Hexagonal

Architecture

isolatedomain with

Events

express statechanges with

RAD

exclude

Repositories

access with Aggregates

encapsulate with

Factories

instantiated by

encapsulate with

instantiated by

access with instantiated by

What the fox says

Page 38: Delphi Domain-Driven Design Presentation

April 2014

Services

Aggregate roots’ methods Aggregate roots are the only kind of entities

to which your software may hold a reference Tend to be the main access point of any

process from the application layer point of view

Often end up as state machines with all their methods

It could be handy to publish those methods as stateless Servicesisolated at Application layer level

Domain Driven Design

Page 39: Delphi Domain-Driven Design Presentation

April 2014

Services

Domain services are used to model primary operations i.e. publish tools for modeling processes

that do not have an identity or life-cycle in your domain that is, that are not linked to one particular aggregate

root, perhaps none, or several

In this terminology, services are not tied to a particular person, place, or thing in my application, but tend to embody processes

Main rule is to let the Domain layer focus on the business logic

Domain Driven Design

Page 40: Delphi Domain-Driven Design Presentation

April 2014

Services

Domain services They tend to be named after verbs or business

activities that domain experts introduce into Ubiquitous Language

They should be exposed as dedicated client-oriented methods Following Interface segregation principle Do not leak your domain! Develop your Application

layer services directly from the needs of your client applications,

Main rule is to let the Domain layer focus on the business logic

Domain Driven Design

Page 41: Delphi Domain-Driven Design Presentation

April 2014

Services

Unit Of Work Can be used to maintain a list of objects affected

by a business transaction Coordinates the writing out of changes and the

resolution of concurrency problems Persistence Ignorance or Database agnosticism

At application layer level Implements transactions for Domain entities and

services May be implemented by ORM to “hydrate” Aggregate

roots class instances as abstractly as possible

Domain Driven Design

Page 42: Delphi Domain-Driven Design Presentation

April 2014

Domain Driven Design

Domain Driven Design

Model-Driven

Design

UbiquitousLanguage

definemodel with

BoundedContexts

identifyscope with

Services

processmodel with

Entities

expressmodel with

Value Objects

expressmodel with

Clean/Layered/Hexagonal

Architecture

isolatedomain with

Events

express statechanges with

RAD

exclude

Repositories

access with Aggregates

encapsulate with

Factories

instantiated by

encapsulate with

instantiated by

access with instantiated by

What the fox says

Page 43: Delphi Domain-Driven Design Presentation

April 2014

Clean / Layered Architecture

Domain Driven Design

DDD 4-tier layered architecture Presentation Layer Application Layer Domain Layer Business Layer

and cross-cutting / vertical layer

With proper isolation of the Domain layer To focus on the domain To not let the domain be polluted

by technical stuff, application particularities…

Page 44: Delphi Domain-Driven Design Presentation

April 2014

DDD n-Tier Architecture

Domain Driven Design

Page 45: Delphi Domain-Driven Design Presentation

April 2014

Clean DDD architecture

From the physical point of view N-layered DDD architecture

Domain Driven Design

Layer Description

Presentation MVC UI generation and reporting

Application Services and high-level adapters

Domain Model Where business logic remains

Data persistence ORM and external services

Cross-Cutting Horizontal aspects shared by other layers

Page 46: Delphi Domain-Driven Design Presentation

April 2014

Clean DDD architecture

From the physical point of view Still looks like a classic 4-tier layered design But DDD does its best

to isolate the Domain Modelfrom any dependency Abstract from technical details Do not be tied to the application layer

To modelize a “clean” architecture

Domain Driven Design

Page 47: Delphi Domain-Driven Design Presentation

April 2014Domain Driven Design

Technical

Implementations

ApplicationServices

DomainServices

DomainModel

Unit Tests

Aggregates

ValueObjects

Entities

Third PartyInterfaces

RepositoryInterfaces

DomainInterfaces

Workflows

execute get/saveobjects

useobjects

Behavior Tests

validate

Infrastructure

implements

User Interface

exposes

DBORM

FileSystem

WebServices

MocksStubs

FakeDatasets

RichClient

WebAJAX

Page 48: Delphi Domain-Driven Design Presentation

April 2014

Clean DDD architecture

From the logical point view Onion-like more than layered-like Domain at the core

Should stay as stable as possible Stay as uncoupled as possible Define domain objects

Value Objects, Entities, Aggregate Roots Define domain services consumed outside Define abstract services implemented outside

e.g. persistence interface

Domain Driven Design

Page 49: Delphi Domain-Driven Design Presentation

April 2014

Clean DDD architecture

From the logical point view Onion-like more than layered-like Application services layer

Will change very often and evolve a lot Typical workflow:

Dehydrate Aggregate Roots using persistence service

Call the Domain services Call external services, commit persistence (Unit of

work)

Domain Driven Design

Page 50: Delphi Domain-Driven Design Presentation

April 2014

Clean DDD architecture From the logical point view

Onion-like more than layered-like Presentation services layer

For each end-user application Depending on each technology (VCL, HTML, AJAX)

Infrastructure services layer Persistence depending on database back-ends (SQL) External services (SOA)

Tests Regression and integration tests are part of the

design

Domain Driven Design

Page 51: Delphi Domain-Driven Design Presentation

April 2014

Clean DDD architecture

Clean, since it controls coupling Coupling is toward the center

All code can depend on layers more central But cannot depend on layers further out from the

core This architecture is unashamedly biased toward

OOP, which puts objects before all others Relies on the Dependency Inversion principle

Uses interface for behavior contract Force the externalization of infrastructure

Domain Driven Design

Page 52: Delphi Domain-Driven Design Presentation

April 2014

Clean DDD architecture

Clean, since it is upside-down Database is not the center of your logic Nor the bottom of your physical design

Database is external There is no such “database application” in

DDD As any other third-party service

Domain Driven Design

Page 53: Delphi Domain-Driven Design Presentation

April 2014Domain Driven Design

Technical

Implementations

ApplicationServices

DomainServices

DomainModel

Unit Tests

Aggregates

ValueObjects

Entities

Third PartyInterfaces

RepositoryInterfaces

DomainInterfaces

Workflows

execute get/saveobjects

useobjects

Behavior Tests

validate

Infrastructure

implements

User Interface

exposes

DBORM

FileSystem

WebServices

MocksStubs

FakeDatasets

RichClient

WebAJAX

Page 54: Delphi Domain-Driven Design Presentation

April 2014

DDD commitments

I shall collaborate with domain experts I shall focus on using our ubiquitous language I shall not care about technical stuff or framework,

but about modeling the Domain I shall make the implicit explicit I shall use end-user scenarios to get real and concrete I shall not be afraid of defining one model per context I shall focus on my Core Domain I shall let my Domain code be uncoupled from any external

influence I shall separate values and time in state I shall reduce statefulness to only the necessary I shall always adapt my model as soon as possible,

once it appears inadequate

Domain Driven Design

Page 55: Delphi Domain-Driven Design Presentation

April 2014

DDD & mORMot

Domain Driven Design

Page 56: Delphi Domain-Driven Design Presentation

April 2014

DDD & mORMot

DDD may be implemented with mORMot Value objects as record

or TPersistent with published properties Entities (and Aggregate Roots) as PODO

class or directly TSQLRecord

Data Transfer Objects as record or TDocVariant Depending if the schema is fixed or variable

Domain Driven Design

Page 57: Delphi Domain-Driven Design Presentation

April 2014

DDD & mORMot

DDD may be implemented with mORMot Services as interface-based services

At domain or application layer To be accessed locally or remotely

Services as method-based services At domain layer, for Aggregate root methods

Persistence as TSQLRest or dedicated service With BATCH mode as Unit-Of-Work

Domain Driven Design

Page 58: Delphi Domain-Driven Design Presentation

April 2014

DDD & mORMot

DDD may be implemented with mORMot User Interface

With optional auto-generation of the layout Including grids, i18n and interaction with the

VCL Code-driven reporting

ORM oriented, with integrated PDF export All cross-cutting features are available

Filtering/validating, security, cache, logging JSON, transmission, RTTI, tests, stubs/mocks

Domain Driven Design

Page 59: Delphi Domain-Driven Design Presentation

April 2014Domain Driven Design

Presentation

Application

Data persistence

DomainModel

Cross-Cutting

AJAX

REST Client

REST Server

HTTP 1.1

Cache

UI

i18n

FilteringValidation

Reporting

ORM

Services(interface-based)

SecuritySessions SQLite3

External DB

Value Objectsas record

Entitiesas TSQLRecord

Aggregatesas TSQLRecord

TestsMocks/Stubs Logging

Page 60: Delphi Domain-Driven Design Presentation

April 2014

Domain Driven DesignArnaud Bouchez

Thanks to Bill Meyer for his review

Any feedback is welcome athttp://synopse.info