Domain Driven Design

68
Introduction To Domain Driven Design Nader Albert

description

An introduction to the concepts of domain driven design

Transcript of Domain Driven Design

Page 1: Domain Driven Design

Introduction To Domain Driven Design

Nader Albert

Page 2: Domain Driven Design

References

Domain Driven Design Eric Evans

Page 3: Domain Driven Design

Agenda

Domain Driven Design Definition Problem Definition Key Terms and Concepts Principles and Objectives Domain Driven Design Patterns Domain Model Unification Domain Driven Design in Action Tips and Warnings

Page 4: Domain Driven Design

Domain Driven Design Definition

Page 5: Domain Driven Design

Problem Definition

Page 6: Domain Driven Design

Fractured Language

Developer Domain Expert

Project Manager

Vaguely understandsnew domain

Vaguely describes what he wants

Struggles to become bilingualand starts to translate

Page 7: Domain Driven Design

• Domain• Model• Domain Model• Domain Context• Ubiquitous Language

Key Terms and Concepts

Page 8: Domain Driven Design

Domain

Sphere of Knowledge.

Subject Area of InterestDomain Model Domain Model Context Ubiquitous

Language

Page 9: Domain Driven Design

Domain

Health Care Domain Education Domain

Domain Model Domain Model Context Ubiquitous Language

Page 10: Domain Driven Design

Model

Domain Model Domain Model Context Ubiquitous Language

Represent Behavior in different shape

Distillation of knowledge

Language Backbone

Page 11: Domain Driven Design

Model

Domain Model Domain Model Context Ubiquitous Language

Static behavior

Dynamic behavior

Page 12: Domain Driven Design

Domain Model

• Extracts domain essential elements, relevant to a specific use.

• Layer of abstractions representing selected aspects of a domain.

• Contains concepts of importance and their relationships in a certain domain.

• Not concerned with physical data storage or processing.

Domain Model Domain Model Context Ubiquitous Language

Page 13: Domain Driven Design

Domain Model

• May include concepts that are not currently computerized.

• Consistent logical model and a shared glossary of terminology.

• Starting point for more detailed analysis.

• Validates I.T. understanding of the business domain and its concepts.

Domain Model Domain Model Context Ubiquitous Language

Page 14: Domain Driven Design

Domain Model

M a p o f t h e F o r e s t

Domain Model Domain Model Context Ubiquitous Language

Page 15: Domain Driven Design

Domain Context

The setting in which a word or a statement appears with a specific meaning.

Domain Model Domain Model Context Ubiquitous Language

Page 16: Domain Driven Design

Ubiquitous Language

Domain Model Domain Model Context Ubiquitous Language

Page 17: Domain Driven Design

Ubiquitous Language

Domain Model Domain Model Context Ubiquitous Language

UNIVERSAL

REFINED

VOCABULARY

DOMAIN MODEL

BOUNDED CONTEXT

CONTINUOUSLY

Page 18: Domain Driven Design

Ubiquitous Language

Verbs NounsGeneric

Vocabulary

Domain Model Domain Model Context Ubiquitous Language

GenericVocabulary

GrammarRules

General Purpose

Language

Page 19: Domain Driven Design

Ubiquitous Language

Operations Models Domain Vocabulary

Domain Model Domain Model Context Ubiquitous Language

Domain Vocabulary

Business Rules

Models relationships

Model BasedLanguage

Page 20: Domain Driven Design

Principles and Objectives

Page 21: Domain Driven Design

Principles

Domain Model Drives Design.

Focus on Model of

the Domain, rather than

TechnologyDomain

Model is a Backbone

of a Domain

Language

Speak a Ubiquitou

s Language within a bounded context

Ubiquitous Language used in all

project aspects

discipline

understanding

Page 22: Domain Driven Design

Objectives

Software and Domain

practitioners can

collaborate.

A Domain Specific

Language (DSL) can be formulated.

Model Driven Architecture (MDA) can be

applied.

Robust application

Page 23: Domain Driven Design

Defined Application Layers

Defined Application Models

Defined Application Contexts

Domain Driven Design Patterns

Page 24: Domain Driven Design

Defined Application Layers

Domain Driven Design Patterns

Page 25: Domain Driven Design

Layered Architecture

Layered Application Architecture

Page 26: Domain Driven Design

Layered Architecture

Concentrate domain code in one layer, isolated from user interface, application, and infrastructure code.

Clean separation of concerns keeps the design of each layer easy to understand, maintain and extend.

Domain objects (models and services) becomes focused on expressing the business domain.

Page 27: Domain Driven Design

Layered Architecture

Online Banking use case

Page 28: Domain Driven Design

Defined Application Models

Domain Driven Design Patterns

Page 29: Domain Driven Design

Entity Model

Distinguished by its identity rather than its attributes.

Identity maintained immutable across all forms (formats) of an object.

Equal attribute values doesn’t indicate Identical objects.

Non equal attribute values doesn’t indicate Non Identical objects.

Page 30: Domain Driven Design

Entity Model

Java Runtime Domain Every object instance is an Entity.

Identity is the object location in memory.

Banking DomainTwo deposits of the same amount to the same account onthe same day, triggered by the same person are two Separate Deposit Operations.

Identity is an auto-generated key, guaranteed to be unique.

Page 31: Domain Driven Design

Entity Model

Same real-world thing might / might not be represented as an entity in a domain model

Identity might / might not be of interest to the application user

Page 32: Domain Driven Design

Value Model

Describes the characteristics of a thing.

Represents a descriptive aspect of the domain with no conceptual identity.

Two markers of the same color and same shape are the same markers.

Page 33: Domain Driven Design

Value Model

Same thing can sometimes be considered as Value object and some other times as Entity object.

Retailer Application Money Printer Application

Page 34: Domain Driven Design

Value Model

Address model is a Value object or an Entity Object?

Postal Service Application

Electrical Utility Application

Value Entity

Page 35: Domain Driven Design

Value Model

Value objects can reference Entity objects

Page 36: Domain Driven Design

Value Model

A person is an Entity and its name is a Value.

Value objects are interchangeable.

Value objects are immutable (name shouldn’t change in every person)

Usually found by traversal from some entity.

Finding a Value with specific properties = Creating a new instance with the same properties.

Page 37: Domain Driven Design

Service Model

Refer to an activity (verb) rather than an entity (noun).

Services are stateless.

Banking Domain Services

Transfer Balance From one Account to another Account

Export Balance to Excel

Send Email

Page 38: Domain Driven Design

Aggregate Model

A cluster of associated objects treated as a unit for the purpose of data change.

Has a root (Entity) and a boundary (defines what is inside).

Root entity has a global identity.

Non-Root entities have local identity.

Page 39: Domain Driven Design

Aggregate Model

Nothing outside the aggregate boundary can hold a reference to anything inside, except to the root entity.

Only aggregate roots can be obtained directly with database queries.(other objects must be found by traversal of associations)

Root entity can expose references to the internal entities. Usage is only transient, and references shouldn’t be held.

Objects within an aggregate can hold references to other aggregate roots.

A delete operation removes everything within the aggregate boundary at once. (cascade delete).

Car Model

Page 40: Domain Driven Design

Defined Application Contexts

Domain Driven Design Patterns

Page 41: Domain Driven Design

Domain Bounded Context

Different models apply in different contexts.

Same entity appears in different contexts with different shapes.

Context boundaries are a set of conditions (business functionality - application layer – database).

Model shall be strictly consistent within a specific bound.

Bounded contexts are not modules.

A bounded context can enfold other bounded contexts.

Name of a bounded context is part of the Ubiquitous Language.

Page 42: Domain Driven Design

Continuous Integration

Tackles the problem of model fragmentation:

Developers may not fully understand the intent of some object or interaction modeled by someone else.

Developers may not realize that a concept is already embodied in another part of the model and they start duplicating concepts and behaviors.

Work within a context is frequently merged and made consistent.

Applied within a single bounded context.

Page 43: Domain Driven Design

Context Map

Gives a wider and more global vision.

Highlights the points of contacts.

Standardizes the communication between different contexts.

A coherent Context Map, places all the work into Bounded Contexts, with explicit relationships between all connected models.

Translation Map

Page 44: Domain Driven Design

Context Map

Translations required: Route Specification List of location codes List of Node IDs Itinerary

Translator (adapter) can be externalized to a separate entity, falling in the shared area between the two contexts (translation map).

A typical two way translator would supply: convertSpec (RouteSpecification) : List<LocationCode>. convertPath (List<nodePath>) : Itinerary Two Bounded Contexts

Page 45: Domain Driven Design

Context Map

public Itinerary route(RouteSpecification spec) {

Booking_TransportNetwork_Translator translator = new Booking_TransportNetwork_Translator();

List constraintLocations = translator.convertConstraints(spec);

List pathNodes = traversalService.findPath(constraintLocations);

Itinerary result = translator.convert(pathNodes);

Way 2 translation

Way 1 translation

Page 46: Domain Driven Design

Shared Kernel

Enfold a subset of the domain decided to be shared between the different contexts.

Can not be changed as freely as the bounded contexts.

Amendment decisions involve consultations with another team.

Represents the core domain.Shared Kernel

Page 47: Domain Driven Design

Anti Corruption Layer

A way to link two bounded contexts, where one of them is a legacy system.

Provides clients with functionality in terms of their own domain model, with little modification to the legacy system.

Facade Adapter Translator

Page 48: Domain Driven Design

Separate Ways

Integration is expensive

Integration is not always required

Decouple bounded contexts from each others

When No sharing of logic is required

If No sharing of data is required

Page 49: Domain Driven Design

Seeing Same Thing Differently

Seeing Different Things Similarly

Domain Model Unification

Page 50: Domain Driven Design

Seeing same thing differently

◦ Different bounded contexts or use cases may have different perceptions about the same physical entity.

◦ Different perceptions may be complementary or contradictory.

Page 51: Domain Driven Design

Seeing same thing differently

Complementary perceptions: Common parts Shared kernel Each context extends (inherits/aggregates) the core part and enrich it with

his own perception.

Parts of a larger whole Common parts Shared kernel

Contradictory perceptions: Bounded contexts doesn’t accept each other’s model. Nothing to share in common Agree on not to agree (Separate Ways). Something to share in common Adapt to each other (Context Map).

Page 52: Domain Driven Design

Unifying the Model

Tire Model (complementary perceptions)

Tire

Car-Tire

Factory-Tire

Retailer-Tire

Shelf id

Buying date

Selling date

Machine IDRow material defects count

Scheduled QA Date

Wheel ID

Weight RadiusSpeed

Manufacturing date

Page 53: Domain Driven Design

Unifying the Model

Crude Model Deeper model

Elephant Model (parts – larger whole)

Page 54: Domain Driven Design

Unifying the Model

Elephant Model (the contradictory perceptions)

4 contexts – no integration

Page 55: Domain Driven Design

Unifying the Model

Elephant Model (the contradictory perceptions)

4 contexts – minimal integration

Translations: wall.location = tree.place = Snake.location = rope.tie-down

Page 56: Domain Driven Design

Seeing different things similarly

Ubiquitous language: Assigning the same name to different models.

General language: Same Word with different meanings in different sentences.

pool of candidate crosses pool of plantspool of reference crosses

Page 57: Domain Driven Design

• Ubiquitous Language in Action• Bounded context in Action• Aggregates in Action• Values in Action• Entities in Action

Domain Driven Design Into Action

Page 58: Domain Driven Design

Ubiquitous Language in Action

Established a Robust communication channel with the business domain experts.

Page 59: Domain Driven Design

Bounded Context in Action

MI Shared Kernel

Analysis Context Execution Context Selection Context

executionqmats

execution

mats

executionshared kernel

selectionqmats

selectionmats

selectionshared kernel

executionorchestration

analysis qmats

analysis mats

analysis shared kernel

analysis orchestration

Page 60: Domain Driven Design

Aggregate Models in Action

◦ Advantages: Hide irrelevant details. Self documented. Prevents mistaken access to incorrect entities.

◦ Disadvantages: Increased complexity with data retrievals. Can have a negative impact on memory utilization, If not well designed.

Page 61: Domain Driven Design

Value Models in Action

Without Value Objects List<String> identifyCandidatePopulation (String gnc, String gny, String brc){ //do the job here ..... return new Vector<String>(); }

With Value ObjectsList<CrossNumber> identifyCandidatePopulation (GenerationCode gnc, GNAYear gny, GNABreedingCode brc){ //do the job here ..... return new Vector<CrossNumber>();}

Page 62: Domain Driven Design

Value Models in Action

public class GenerationCode extends StringValueObject implements Serializable {

public GenerationCode (String value) {

super(value);

// do any extra logic here.....

}

public String getName(){

return "generation code";

}

public boolean validate (String value){

if ( (true == value.isEmpty() ) || (false == value.startsWith("F"))){

return false;

}

return true;

}}

public abstract class StringValueObject implements Serializable {

private String value;

public StringValueObject (String value){

if (!this.validate(value)) {

throw new IllegalArgumentException(getName() + " syntax invalid ");

}

this.value = value;

}

public String getValue() {

return value;

}

public abstract boolean validate (String value);

public abstract String getName();

}

Page 63: Domain Driven Design

Value Models in Action

Encapsulating domain values in well defined Value objects.

Advantages: Self documented. Compile time validation Increased Code Robustness Good place for runtime validation logic. Serves the Ubiquitous Language.

Disadvantages: Increased complexity (creation time / object relational mapping time). Additional class object and instance objects.

Page 64: Domain Driven Design

Entity Models in Action

public interface EntityService<T> {public int add(T entityResource) throws BusinessException;public int update(T entityResource) throws BusinessException;public T retrieve(int entityId) throws BusinessException;public int remove(T entityResource) throws

BusinessException;public int remove(int entityResourceId) throws

BusinessException; }

Page 65: Domain Driven Design

Entity Models in Action

Encapsulating entities in well defined Entity objects.Advantages:

Basic Object Behaviour can be encapsulated and reused. Serves the Ubiquitous Language.

Page 66: Domain Driven Design

Tips and warnings

Deep understanding of the domain business is

essential.

Discipline is key.

Real value comes only with complex business

domain.

May introduce additional

unnecessary complexity.

Page 67: Domain Driven Design

Questions

Page 68: Domain Driven Design