Domain Driven Design

Post on 10-May-2015

1.020 views 2 download

Tags:

description

An introduction to the concepts of domain driven design

Transcript of Domain Driven Design

Introduction To Domain Driven Design

Nader Albert

References

Domain Driven Design Eric Evans

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

Domain Driven Design Definition

Problem Definition

Fractured Language

Developer Domain Expert

Project Manager

Vaguely understandsnew domain

Vaguely describes what he wants

Struggles to become bilingualand starts to translate

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

Key Terms and Concepts

Domain

Sphere of Knowledge.

Subject Area of InterestDomain Model Domain Model Context Ubiquitous

Language

Domain

Health Care Domain Education Domain

Domain Model Domain Model Context Ubiquitous Language

Model

Domain Model Domain Model Context Ubiquitous Language

Represent Behavior in different shape

Distillation of knowledge

Language Backbone

Model

Domain Model Domain Model Context Ubiquitous Language

Static behavior

Dynamic behavior

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

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

Domain Model

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

Domain Model Domain Model Context Ubiquitous Language

Domain Context

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

Domain Model Domain Model Context Ubiquitous Language

Ubiquitous Language

Domain Model Domain Model Context Ubiquitous Language

Ubiquitous Language

Domain Model Domain Model Context Ubiquitous Language

UNIVERSAL

REFINED

VOCABULARY

DOMAIN MODEL

BOUNDED CONTEXT

CONTINUOUSLY

Ubiquitous Language

Verbs NounsGeneric

Vocabulary

Domain Model Domain Model Context Ubiquitous Language

GenericVocabulary

GrammarRules

General Purpose

Language

Ubiquitous Language

Operations Models Domain Vocabulary

Domain Model Domain Model Context Ubiquitous Language

Domain Vocabulary

Business Rules

Models relationships

Model BasedLanguage

Principles and Objectives

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

Objectives

Software and Domain

practitioners can

collaborate.

A Domain Specific

Language (DSL) can be formulated.

Model Driven Architecture (MDA) can be

applied.

Robust application

Defined Application Layers

Defined Application Models

Defined Application Contexts

Domain Driven Design Patterns

Defined Application Layers

Domain Driven Design Patterns

Layered Architecture

Layered Application Architecture

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.

Layered Architecture

Online Banking use case

Defined Application Models

Domain Driven Design Patterns

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.

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.

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

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.

Value Model

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

Retailer Application Money Printer Application

Value Model

Address model is a Value object or an Entity Object?

Postal Service Application

Electrical Utility Application

Value Entity

Value Model

Value objects can reference Entity objects

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.

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

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.

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

Defined Application Contexts

Domain Driven Design Patterns

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.

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.

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

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

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

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

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

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

Seeing Same Thing Differently

Seeing Different Things Similarly

Domain Model Unification

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.

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).

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

Unifying the Model

Crude Model Deeper model

Elephant Model (parts – larger whole)

Unifying the Model

Elephant Model (the contradictory perceptions)

4 contexts – no integration

Unifying the Model

Elephant Model (the contradictory perceptions)

4 contexts – minimal integration

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

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

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

Domain Driven Design Into Action

Ubiquitous Language in Action

Established a Robust communication channel with the business domain experts.

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

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.

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>();}

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();

}

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.

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; }

Entity Models in Action

Encapsulating entities in well defined Entity objects.Advantages:

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

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.

Questions