Tour d'horizon de Domain-Driven Design Avril 2012 autour d'un retour d'expérience - Aroll@fterwork...

Post on 26-Jun-2015

369 views 2 download

description

Vous avez entendu parler de Domain-Driven Design (DDD) et vous voulez en savoir plus ? Nous vous offrons un tour d'horizon de concepts importants de DDD et leur application en pratique, avec des retours d'un projet récent. Vidéo de la présentation disponible : http://www.dailymotion.com/video/xq62pf_aroll-fterwork-du-11-avril-domain-driven-design_tech

Transcript of Tour d'horizon de Domain-Driven Design Avril 2012 autour d'un retour d'expérience - Aroll@fterwork...

@cyriux @arollafr

Tour d’horizon Domain-Driven

DesignRetour sur un projet récent

http://fr.gta.wikia.com/wiki/Easter_Eggs

Executive Summary

Domain-Driven Design :

• Priorité au domaine, devant la technique• Parler le langage du métier, pour tout le

monde, dans le code et dans les tests• Le code est le modèle (et vice-versa)• Mon arme secrète sur mes projets depuis

2005

http://www.virtual-genius.com/blog/post/Domain-Driven-Design-Immersion-Course-e28093-Part-5.aspx

Seniors Developers

http://www.thisisio.ie/blog/article/149/hiring_senior_developer

I. Putting the model to work

II. Building blocks (Tactical DDD)

III. Refactoring toward deeper insight

IV. Strategic DDD

DDD + BDD +TDD = VERY GOOD FRIENDS!

http://www.alicia-logic.com/capspages/caps_viewall.asp?titleid=16

Souvent DénaturéSans outillage

spéci!que

CQRS: + populaire

Très respecté

Ambition

Objectif ambitieux

Grosse attente sponsor

Gros legacy

?

http://www.ratemyfunnypictures.com/index.php/8148/rate-my-one-at-a-time/

Agree on Maxims

“One at-a-time”

Visualize! Metaphors!

http://staff.bath.ac.uk/enssa/LPDev.htm

Asset Capture

1 seul concept d’intervention : “moteur”

http://martinfowler.com/bliki/AssetCapture.html

Moteur

Echappement

Transmission

Strangler application

Un nouveau moteur qui étranglera progressivement l’ancien

http://www.flickr.com/photos/louisfoecy/4114597043

http://martinfowler.com/bliki/StranglerApplication.html

Plan d’action

1 seul concept d’intervention : “produits financiers”

Strangler application sur ce concept seulement

Tout le reste : on garde sans modifier

DU *VRAI* MODEL-DRIVEN DESIGN

Et maintenant

UNE CURIOSITÉ SINCÈRE POUR LE MÉTIER

Au commencement :

http://jnchaintreuil.com/et-si-le-futur-appartenait-aux-curieux/

Changement culturel• Le métier c’est cool• Passer à la vitesse supérieure

http://rumors.automobilemag.com/feature-flick-2012-porsche-911-7-speed-manual-73509.html

Investir dans la connaissance métier

Mini-training 30mn bi-hebdo

http://www.femmeactuelle.fr/jardin/jardinage-les-conseils/arroser-son-jardin-pendant-les-vacances-00873

Accès à un expert du sujet

http://bakchich-old.static.ddz.fr/IMG/jpg_expert-2.jpg

Proxys d’experts métier

http://fr.m.wikipedia.org/wiki/Fichier:Crocodile_warning_sign_02.svg

Le langage compte!• La modélisation

commence avec le langage

• Attentions aux « synonymes » et aux mots centraux du métier

• Poser des bonnes (meilleures) questions

http://journalism.about.com/od/reporting/tp/Finding-And-Developing-Ideas-For-News-Stories-And-Articles.htm

Searching for the Ubiquitous Language

An instrument is effective for a period of time (its life), that is the date range between the effective date and the expiry dateA swap is made of legs, each of them being an independent instrument on its own. Each leg defines two counterpartiesA payoff is a cash flow given by one counterparty to the other counterpartyInstruments generate cash flows during their life, in particular at expiry date (redemption, zero coupon) and at regular datesThere may be a date offset for settlements, fixings and cash flows paymentsFloating rate devices generate cash flows according to observation expressions based on some observable referenceFixed rate devices generate cash flows according to a predefined couponInflation-linked devices modulate the coupon, coupon rate or notional amount by the variation of some (inflation) observable referenceRegular dates may be predefined explicitly as a dates list, or as repeated dates defined by a period and a time direction (backward or forward), with stub convention and date adjustment rules, and according to some holiday calendarDate adjustment rules are defined by a day roll convention and a business centerA funding leg is a fixed rate device or a floating rate deviceA return leg is a leg that reproduces the exact cash flows of another instrument

A credit leg observes credit events from some identified instrument and triggers either a physical settlement or to a cash settlement. Typical credit events are bankruptcy, failure to pay, restructuringForward and Future means that the effective date is in the future. The difference between forward and future is that the former is OTC whereas the later is cleared, more standard, and involves frequent margin calls (hence a convexity bias between them)From a legal perspective, an option is the right to exercise some transaction, typically to buy/sell the underlying instrument at a predefined strike and volume, or to receive a payoff. Since investors are rational, we may also consider options to be essentially instruments with conditional transaction, in general payoffsOption styles are typically European (exercise only at expiry date), American (exercise anytime), Bermuda (exercise at regular dates), Canary (exercise at regular dates after some date or period)An underlying instrument is an instrument used to condition the exercise (which may be automatic) and often used to calculate the amount of the payoff or more that is directly the object of an exchange, in the case of an exchange of assetsSome instruments are subject to conversion, i.e. they can be replaced with another instrumentSome instruments involve one, two or no exchange(s) of principal(s)Compounding swaps capitalize interests earned for each period payment period

Cash Flow

Bank HolidayInterest rate

Ubiquitous Language

• Nommer•Facile à chercher•Prononçables•Sans abréviation

• Définir•Définition partagée•Comprendre, pas juste un vocabulaire

http://scalin.fr/rubrique-technique/glossaire

Our brain is a compiler

CC: Gaetan Lee / http://en.wikipedia.org/wiki/File:Chimp_Brain_in_a_jar.jpg

Invariants, symétries, On peut déjà refactoriser des

duplications en langage naturel:• « A chaque date anniversaire, une

obligation paie un coupon »• « A chaque fin de période, une jambe de

swap paie les intérêts sur la période »

= Un seul scénario !

Invariants« Le marché des instruments dérivés est

à somme nulle »

Σ Cash Flows (toutes les contreparties) = 0

Agile ➜ Confiance

Mais pas dans les documents texte !

MS Word Docs Vs. POC’s

Vs.

http://www.hacknmod.com/wp-content/uploads/2008/12/dsc_2875.jpg

MS Word Docs Vs. POC’s

Vs.

ContradictionsOublis essentiels

Si ça marche pas ça se

voit !

Codeanalysis• Modéliser, en code• Bloc-notes exécutable• Domain-Model-first• Antidote Analysis Paralysis (Greg

Young)• Spike isolé, jetable (ou non)• Deliberate Discovery (Dan North)

http://dannorth.net/2010/08/30/introducing-deliberate-discovery/http://codebetter.com/gregyoung/tag/analysis/

*NOT* UML/MDA!

http://depinfo.u-cergy.fr/projets/close2u/fr/tag/uml/

No Translation: Code == Model

• Ubiquitous Langage dans le code• Noms de classes & interfaces• Noms de méthodes• Code lisible en prose autant que possible

•≥ 80% noms de classes & méthodes lisibles par le métier

Code = Medium

• Raconte le métier• Auto-formation métier• Auto-formation patterns aussi :

• Export documentation de référence métier (Doclet)

Exemple d’export

42

PipeAdmission

Vilebrequin

Injecte l'essence et l'aire dans le moteur et passant par le vilebrequin pour le graissage des roulements puis monte dans le cylindre par les transferts

Pièce sur laquelle est fixé le piston qui, grâce à l'explosion descend en faisant tourner le vilebrequin, qui fera tourner la roue en passant par l'embrayage et la boîte à vitesse (sur le ciao, la boîte à vitesse est placée dans la roue arrière

Bougie

Allumage

Carter

Cylindre

Piston

AxePiston

Le rôle de la bougie est de crée un petit arc électrique pour faire exploser, au bout du moteur, le mélange air-essence comprimé par le piston.

Déclenche l’étincelle dans la bougie

AllumageRupteur : bobine haute-tension pour allumage rustique

AllumageElectronique : circuit électronique haute-tension pour allumage précis

Coque fermée qui contient le vilebrequin

Le cylindre contient les transferts qui amènent l'essence dans la partie entre la fin du cylindre et la culasse où se passe la compression et de la lumière d'échappement (sortie des gaz vers le pot)

Elément clé du moteur qui subit la pression quand le mélange air-essence explose, il recule avec une force équivalente a 2000kg. et fait tourner le vilebrequin qui entraine le reste...

l'axe du piston sert à tenir le piston à la bielle.

Avantages

• Spécifications minces• Efficacité du langage partagé• Plus d’autonomie des développeurs / testeurs• Moins de malentendus

43

Avantages

• Economie grâce à la qualité de code: • pas de traduction : moins de gaspillage• moins de code (moins de cas particuliers)• meilleur rapport signal / bruit : lisible• code auto-documenté : facile à comprendre• concepts métier assez stables

44

• Plus de valeur livrée

• Initiatives développeurs : «et si... ?»

• Motivation des développeurs brillants

http://www.flickr.com/photos/8681025@N03/3249399322/

En code...

46

« DayShift by -2 WORKING days »

No getter/setter

Immutable

Enum

null

Code concentré en métier• 100% métier (ou presque)• No framework pollution

• Spring, Hibernate, logger• No javax.*• No SQL

• Only

http://code.google.com/p/guava-libraries/

Dans le modèle de domaine

Value Object• No particular identity, equality by value• Fowler patterns: ValueObject, Quantity,

Range• Immutable

• Constructor / Static Creator / Factory method

• Style FP• Side-effect-free

Mon choix par défaut,

sauf si vraiment pas

possible !

Equality by value

Value Object

• Functional programming style• Immutable, clone to mutate• Capture values (snapshot) • History object of every version

• Builder pour aider à la création• par exemple :• String & StringBuilder

Value Object

Value Object

// foreach(numberOfDays)

Défini par une identité arbitraire

Notion de continuité dans le temps

Entities

Une collection d’objets liés qui partagent une cohérence ensembles, avec une entité racine pour l’identité : Aggregate Root

Aggregates

http://www.boitearecettes.com/fruits_legumes/raisin-text.htm

Ni une valeur ni une entité

Services

http://www.andeka.co.cc/2011/07/postbox-251.html

Module (lib)

<<ValueObject

<<ValueObject

<<ValueObject>><<ValueObje

ct<<ValueObject>>

<<Service>><<SPI>>

<<Service>><<API>>

<<Entity>><<Aggregate>>

Module ==

library

Accès aux services

extérieurs

Module ==

library

Accès aux services

extérieurs

Façade sur le legacy

• Tout le code ne mérite pas la même attention et n'a pas vocation à être repris!

• Dette technique seulement si on paie des intérêts

<<ACL>><<Facade>>

En gros

• DDD : façon d’aborder les problèmes + solutions

•Focus sur le métier•Focus sur le langage du métier

AMBITIEUX == DANGEREUX

Big Bang == Big FailFrom Scratch == Casse-Gueule

StabilisationMaturationRetour des

bugs historiques

http://www.sciencesortof.com/2011/05/episode-84-the-big-bang/

Fort besoin d’un filet de tests complet

BDD

Stratégie de tests

“1000’s of unit tests”

“10% of unit tests number”

“10 overall”

Stratégie de tests

“1000’s of unit tests”

“10% of unit tests number”

“10 overall”

Blackbox

Whitebox

En pratiqueJunit

Predefined implementations of the external service: total control of scenario data

http://greenarrow.deviantart.com/art/The-Flash-Wally-West-35885287

http://nw.wea.org.uk/blogs/extending_learning_coversations.php

•Face to face IRL (travel)•Telephone•Chat•Email

3 amigos

BA Dev Tester

http://sanslignebleue.files.wordpress.com/2010/02/3-amigos.jpg

DONE criteria : DONE!Given a floating rate bond on EURIBOR 3MAnd a nominal of 15M EURAnd an issue date of 2011/06/15And an end date of 2012/06/14And an SEMI_ANNUAL calculation period

When the EURIBOR 3M evolves:| 2011/09/15 | 3.5% | | 2012/03/15 | 4.0% |

Then the cash-flows are:| 2011/12/13 | 23000 || 2012/06/14 | 25500 |

http://nxadm.wordpress.com/tag/bug/

Remarques• GUI & DB testing • BDD scénarios & BA

• Faire générique (cross-asset) moins expressif

• DDD difficile à expliquer, avancer couvert, montrer les bénéfices 

INTÉGRATION & LEGACY

Plus facile à intégrer par construction

lib sur-mesure

Hexagonal Architecture

http://pragprog.com/magazines/2009-12/going-naked

Depends on nothing

Hexagonal Architecture

Hexagonal Architecture

Scenario test data

Adapters

INTÉGRATION & LEGACY

Bounded Contexts!

“The delimited applicability of a particular model”

Context X

Context Y

Same concept• Different contexts• Different focus• => Different models

Context Game

“What's your ideal <customer>?”

• sales : il a beaucoup d’argent et beaucoup d’envies

• marketing : il aime notre produit et il le dit à tout le monde sur les réseaux sociaux

• shipping : il habite à coté de l’entrepôt et est toujours chez lui

• facturation : il paie d’avance sans sourciller même si le produit n’est pas en stock

Context Game

“What's your ideal <instrument>?”

• pre-trade : il est très liquide avec un faible écart entre bid et offer

• trading : il a un identifiant unique et uniforme facile à saisir

• risk : il est risqué sur un seul facteur de risque

• back-office : il a peu de cash-flows et les cash-flows sont certains et connus longtemps avant

Context Game

“What's your ideal <instrument>?”

• pre-trade : il est très liquide avec un faible écart entre bid et offer

• trading : il a un identifiant unique et uniforme facile à saisir

• risk : il est risqué sur un seul facteur de risque

• back-office : il a peu de cash-flows et les cash-flows sont certains et connus longtemps avant

Contexts & mappers

Trading<<legacy>>

Risk<<legacy>>

Cash-flows<<strangler>>

CRUD<<legacy POJO>>

DB<<legacy>>

Non DDD

(anémique)

Hibernate ORM

Multiple Models ≠ Duplication

Trading<<legacy>>

Risk<<legacy>>

Cash-flows<<strangler>>

CRUD<<legacy POJO>>

DB<<legacy>>

Non DDD

(anémique)

Hibernate ORM

Adapter = Shock Absorber

http://www.directindustry.com/prod/herwarth-reich/flexible-couplings-elastic-couplings-19991-374565.html

DDD: Anti-Corruption

Layer

Adapter = Shock Absorber

http://www.directindustry.com/prod/herwarth-reich/flexible-couplings-elastic-couplings-19991-374565.html

Adapter = Shock Absorber

http://www.directindustry.com/prod/herwarth-reich/flexible-couplings-elastic-couplings-19991-374565.html

Merci !

http://cathy313.centerblog.net/539-bisounours

Vos questions

@cyriux @arollafr