How I did it (in .NET): idiomatic Domain Driven Design

Post on 05-Dec-2014

1,640 views 0 download

description

 

transcript

idiomatic Domain Driven Design

Andrea Saltarello

C.T.O. @ managed/designs http://blogs.ugidotnet.org/pape

http://twitter.com/andysal74

http://creativecommons.org/licenses/by-nc-nd/2.5/

Grazie!

managed/designs

Leggere attentamente le

avvertenze…

(Quasi) Tutte le demo saranno basate su NSK, un framework di e-commerce sviluppato in bottega e scaricabile qui con licenza open source.

N.B.: NSK è come il galeone di Dylan Dog: non è mai terminato, quindi non tutti i check-in sono come la caramella Polo (cioè «riusciti col buco» )

Andrea Saltarello! Chi era

costui? 1. C.T.O. di Managed Designs, alla ricerca della

«sostenibilità dello sviluppo software» – Il cliente «deve» essere soddisfatto e pagare

– Il fornitore «deve» avere un margine ragionevole

– Il team «deve» essere soddisfatto del proprio lavoro

2. Fondatore e presidente di UGIdotNET: ho bisogno di condividere esperienze a causa del bullet precedente

3. (Co)Autore di .NET: Architecting Applications for the Enterprise di Microsoft Press – Il #NAAE è il mio giornale di bordo, nel quale (nel 2008)

ho cercato di «sintetizzare» i punti 1 e 2

Once upon a time…

1. Acquistai il [P of EAA] a febbraio 2003, lo lessi

e… «estiqaatsi?»

2. Acquistai il «Blue Book» appena uscito (2004),

lo lessi e… «estiqaatsi?»

3. In poche parole: come «passo» dal libro al

mondo reale?

Innanzitutto…

• Ubiquitous Language

• Ubiquitous Language

• Ubiquitous Language

• Ubiquitous Language

• Ubiquitous Language

• Ubiquitous Language

• Ubiquitous Language

DEMO

Ubiquitous Language

One More Thing… (cit.)

Non è «Lascia o Raddoppia»

Blue Book: Architettura (1/2)

Blue Book: Architettura (2/2)

• è una layered architecture

• i layer Presentation e Infrastructure

compaiono «per sport» nel diagramma

• i layer Application e Domain costituiscono

quella che tipicamente chiamiamo «business

logic»

– Domain: logica invariante rispetto ai casi d’uso

– Application: logica specifica ai casi d’uso

DEMO

Domain vs. Application:

Amazon web site

Domain layer: Key Concepts

• Il Domain Layer contiene la domain logic ed è composto da

– Model: Entità (identità e stato) e Valori (solo stato)

– Servizi

• Il Model è «both data and behaviour» (cit.)

• La persistenza del Model è gestita da Repository

• Le istanze delle entità di dominio sono costruite da Factory

• Entità e Valori a runtime formano dei grafi di oggetti. I grafi dotati di “dignità propria” sono chiamati Aggregate e il sistema (es: i Repository) si “impegna” a gestirli correttamente ed atomicamente

DEMO

Domain Model

Da 0 ad Aggregate

• E' un insieme di elementi raggruppati in un’unità logica, quindi un grafo di oggetti

• Ha come radice l'entità principale dell'aggregato

• La radice è l’unico elemento che può essere referenziato fuori dai confini dell’aggregato

• Non è possibile agire direttamente sugli elementi senza passare dalla radice dell'aggregato

• L’aggregate ha la responsabilità di implementare la propria logica

DEMO

Aggregate

One More Thing… (cit.)

E’ DDD, non «Il Signore degli Anelli», quindi:

Assert.IsFalse(OneModelToRuleThemAll);

Repository pattern: in teoria

A system with a complex domain model often benefits from a layer, such as the one provided by Data Mapper (165), that isolates domain objects from details of the database access code. In such systems it can be worthwhile to build another layer of abstraction over the mapping layer where query construction code is concentrated. This becomes more important when there are a large number of domain classes or heavy querying. In these cases particularly, adding this layer helps minimize duplicate query logic.

You can also find a good write-up of this pattern in Domain Driven Design.

Repository pattern: in pratica

Mediates between the domain and data mapping layers

using a collection-like interface for accessing domain

objects. Ricapitolando: • Interfaccia “collection like” • Gestisce la persistenza degli Aggregate • LINQ! (siamo dei buongustai )

DEMO

Repository

Application Layer: in teoria

Application Layer: defines the jobs the software is supposed to do and directs the expressive domain objects to work out problems. The tasks this layer is responsible for are meaningful to the business or necessary for interaction with the application layers of other systems. This layer is kept thin. It does not contain business rules or knowledge, but only coordinates tasks and delegates work to collaborations of domain objects in the next layer down. It does not have state reflecting the business situation, but it can have state that reflects the progress of a task for the user or the program.

Application Layer: in pratica

E’ un catalogo di servizi in grado di effettuare il

mesh della logica presente nel domain layer

esponendola alla applicazione (es: presentation

layer) in una forma ad… Alta digeribilità.

DDD vs Real World

Avere a disposizione un domain layer «smart» è bello, ma costoso:

– Materializzazione degli oggetti

– Mesh della business logic

Tipicamente, si finisce per passare la vita a «fare DTO»:

– Application Layer <-> Presentation Layer

– («ma anche» cit.) Domain Layer <-> Application Layer

Layered Expression Trees (LET idiom)

Facciamo un gioco: invece di definire un «botto» di

DTO, facciamo che layer e servizi si scambino degli

IQueryable<YourFavouriteDomainEntity>, facendo

«emergere» la query e specificando la proiezione solo

all’ultimo momento?

L’espressione «Capra e cavoli» vi dice niente?

P.S.: Si, «botto» è un ordine di grandezza del S.I. Kilo-

>Mega->Giga->Tera->Peta->Botto

DEMO

Layered Expression Trees

LET idiom feat. Ubiquitous Language

LET aumenta la pervasività dell’Ubiquitous Language nel codice:

recommendedProducts = (from p in CatalogServices.GetAvailableProductsOnSale()

orderby p.UnitsInStock descending

select new ProductDescriptor

{

Id = p.Id,

Name = p.Name,

UnitPrice = p.UnitPrice,

UnitsInStock = p.UnitsInStock,

}).Take(3);

Questa query è «quasi» scritta nel linguaggio del Domain Expert

And now for something

completely different

Command Query Responsibility

Segregation

Command and Query Responsibility Segregation (CQRS) originated with Bertrand Meyer’s Command and Query Separation Principle. Wikipedia defines the principle as:

It states that every method should either be a command that performs an action, or a query that returns data to the caller, but not both.

Command and Query Responsibility Segregation uses the same definition of Commands and Queries that Meyer used and maintains the viewpoint that they should be pure. The fundamental difference is that in CQRS objects are split into two objects, one containing the Commands one containing the Queries.

[Fonte: http://cqrsinfo.com/documents/cqrs-introduction/ ]

Command Query Responsibility

Segregation

Query Command

DEMO

CQRS

Books & Publications

[DDD] Domain Driven Design, Eric Evans ,

Addison-Wesley

[P of EAA] Pattern of Enterprise

Application Architecture, Martin Fowler,

Addison-Wesley

[NAAE] Microsoft .NET: Architecting

Applications for the Enterprise, Andrea

Saltarello & Dino Esposito, Microsoft Press

[NSK] NSK, http://nsk.codeplex.com