practicing ddd

Upload: ricardo-cruz

Post on 18-Jan-2016

48 views

Category:

Documents


0 download

DESCRIPTION

DDD na prática

TRANSCRIPT

  • Practicing Domain-Driven DesignPractical advice for teams implementing the developmentphilosophy of Domain-Driven Design. With code examplesin C# .NET.

    Scott Millett

    This book is for sale at http://leanpub.com/Practicing-DDD

    This version was published on 2013-02-04

    This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishingprocess. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools andmany iterations to get reader feedback, pivot until you have the right book and build traction onceyou do.

    2012 - 2013 Scott Millett

    http://leanpub.com/Practicing-DDDhttp://leanpub.comhttp://leanpub.com/manifesto

  • Tweet This Book!Please help Scott Millett by spreading the word about this book on Twitter!

    The suggested hashtag for this book is #Practicing-DDD.

    Find out what other people are saying about the book by clicking on this link to search for thishashtag on Twitter:

    https://twitter.com/search/#Practicing-DDD

    http://twitter.comhttps://twitter.com/search/#Practicing-DDDhttps://twitter.com/search/#Practicing-DDD

  • Contents

    About The Author i

    Introduction ii

    Why You Should Read This Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ii

    Who Should Read This Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ii

    Domain-Driven Design In A Nutshell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iii

    A Problem Space . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iii

    A Solution Space . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iii

    How This Book Is Structured . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iv

    Other Books On Domain-Driven Design . . . . . . . . . . . . . . . . . . . . . . . . . . . v

    I The Theory: Introduction To The Philosophy 1

    1 The Need For Domain-Driven Design 2

    1.1 A Philosophy Over A Framework Or Methodology . . . . . . . . . . . . . . . . . . 2

    1.2 Writing Large-Scale Complex Business Software Is Hard . . . . . . . . . . . . . . . 3

    Code Without Organisation Will Rot . . . . . . . . . . . . . . . . . . . . . . . . . . 4

    Developing In Mud . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

    2 Understanding Your Problem Space 6

    2.1 Knowledge Crunching : Finding The Model . . . . . . . . . . . . . . . . . . . . . . 7

    What Is A Domain Model? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

    Gaining Domain Knowledge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

    The Challenges With Upfront Design . . . . . . . . . . . . . . . . . . . . . 8

    Team Modelling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

    Techniques For Creating A Useful Model . . . . . . . . . . . . . . . . . . . . . . . . 13

    Capture Use Cases Of The System . . . . . . . . . . . . . . . . . . . . . . . 13

    Sketching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

    Defer The Naming Of Concepts In Your Model . . . . . . . . . . . . . . . . 14

  • CONTENTS

    Powerful Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

    Rapid Prototyping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

    Look For Existing Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

    2.2 Domain Experts: Your Guide To Deeper Understanding In Your Problem Domain . . 16

    Sit With Your Domain Experts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

    2.3 Knowledge Distillation : Breaking Down Large Systems To Find What Is Core . . . 17

    Subdomains . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

    Seeing The Wood In-spite Of The Trees . . . . . . . . . . . . . . . . . . . . . . . . . 18

    Core Domains . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

    Domain Vision Can Reveal What Is Core . . . . . . . . . . . . . . . . . . . 22

    Generic Domains . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

    Supporting Domains . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

    The Core Domain Doesnt Always Have To Be Perfect First Time . . . . . . . . . . 23

    Subdomains Exist In The Problem Space . . . . . . . . . . . . . . . . . . . . . . . . 24

    2.4 Model In Context . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

    Without Context We Are Nothing . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

    Context Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

    Multiple Models In A Subdomain . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

    2.5 Shifting Focus From The Project To The Product . . . . . . . . . . . . . . . . . . . . 28

    Less Hast More Speed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

    2.6 The Salient Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

    3 Speaking The Language Of Your Domain 30

    3.1 The Language Of Domain Experts . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

    3.2 Collaborating On An Enhanced Language . . . . . . . . . . . . . . . . . . . . . . . 30

    Enhancing The Language With Discovered Terms . . . . . . . . . . . . . . . . . . . 31

    3.3 Working With Concrete Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

    Teach Your Domain Experts To Focus On The Problem And Not Jump To A Solution 33

    Using Features And Scenarios To Demonstrate Domain Scenarios . . . . . . . . . . 33

    3.4 A Language Tied To A Context . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

    3.5 The Salient Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

  • CONTENTS

    4 Shaping Your Solution Space 36

    4.1 Retaining The Integrity Of Models In Subdomains . . . . . . . . . . . . . . . . . . . 36

    The Challenges Of Maintaining A Single Model: Blurred Responsibility . . . . . . . 37

    Bounded Contexts: Define A Boundary Of Responsibility Around A Model . . . . . 38

    Implementing A Bounded Context . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

    4.2 The Importance Of Bounded Contexts . . . . . . . . . . . . . . . . . . . . . . . . . 41

    A Bounded Context Can Cover More Than One Subdomain . . . . . . . . . . . . . 42

    More Than A Single Bounded Context Per Physical Deployment . . . . . . . . . . . 43

    Sizing Your Models And Bounded Contexts . . . . . . . . . . . . . . . . . . 44

    4.3 Architectural Patterns Apply To Bounded Contexts Not Systems . . . . . . . . . . . 45

    4.4 Understanding The Relationships Between Bounded Contexts . . . . . . . . . . . . 46

    Context Maps Clearly Show Business Process . . . . . . . . . . . . . . . . . . . . . 47

    Bounded Contexts Work Together To Solve Business Problems . . . . . . . . . . . . 47

    4.5 Integration Between Bounded Contexts . . . . . . . . . . . . . . . . . . . . . . . . 49

    Modules (aka .Net Namespaces) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

    Anti Corruption Layer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50

    Introducing Bounded Contexts Into Legacy Code . . . . . . . . . . . . . . . 51

    Shared Kernel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

    Open Host Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

    Publish-Subscribe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54

    4.6 Patterns For Team Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

    Customer-Supplier (Upstream/Downstream) . . . . . . . . . . . . . . . . . . . . . . 56

    Conformist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56

    Partnership . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57

    4.7 The Salient Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57

    5 Complex Core Domains Should Be Based On A Model 58

    5.1 The Domain Model: Expressing The Model In Code . . . . . . . . . . . . . . . . . . 58

    Model Only What Is Relevant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59

    A Clean Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59

    Persistence Ignorance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60

  • CONTENTS

    Dont Model Reality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61

    A Useful Abstraction On Reality . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62

    Reveal The Behaviour Of The Domain . . . . . . . . . . . . . . . . . . . . . . . . . 62

    The Code Model Is The Only Truth . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

    Hands On Modellers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

    5.2 Tactical Patterns: The Building Blocks Of Model Driven Design . . . . . . . . . . . 63

    Model Structure Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64

    Value Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64

    Entities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67

    Aggregates and Aggregate Roots . . . . . . . . . . . . . . . . . . . . . . . . 71

    Domain Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75

    Domain Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78

    Life Cycle Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78

    Factories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78

    Repositories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80

    Application Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81

    Infrastructure Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83

    5.3 Presentation Concerns: The Command Vs Query Paradox . . . . . . . . . . . . . . 83

    5.4 The Salient Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86

    6 Refactor for Deeper Design Insights 88

    6.1 Non Technical Refactoring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88

    6.2 Making The Implicit Explicit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88

    Give Things A Name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91

    6.3 Challenge Your Assumptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91

    6.4 Supple Code Aids Discovery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91

    6.5 The Salient Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92

    7 What DDD is not 93

    Patterns For Understanding The Problem Space Are Useful On All Projects, Model-Driven Design May Not Be . . . . . . . . . . . . . . . . . . . . . . . . . . . 93

    7.1 Code Is A Product Of DDD Not The Process . . . . . . . . . . . . . . . . . . . . . . 93

  • CONTENTS

    7.2 DDD Is Not For The Faint Hearted . . . . . . . . . . . . . . . . . . . . . . . . . . . 94

    7.3 Ask Yourself: Is It Worth This Extra Complexity? . . . . . . . . . . . . . . . . . . . 95

    Beware The Anemic Domain Model . . . . . . . . . . . . . . . . . . . . . . . . . . 95

    Not A Solution To Every Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95

    7.4 The Salient Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95

    II The Practice: Coding The Strategic And Tactical Patterns Of DDD 97

    8 Strategic Patterns of Domain-Driven Design 98

    9 The Building Blocks of Domain-Driven Design 99

    10 Domain-Driven Design Best Practices 100

    III Case Study: Putting Theory And Coding Patterns Into Practice 101

    11 A Modelling Example 102

    11.1 Case Study . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102

    Appendix 103

    Version History 104

  • About The AuthorScott Millett is an enterprise software architect working in London for Wiggle.co.uk, an e-commercecompany specializing in cycle and triathlete sports. He has been working with .NET since version1.0 and was awarded the ASP.NET MVP in 2010 and again in 2011. When not writing about orworking with .NET he can be found relaxing and enjoying the music at Glastonbury and many ofthe major music festivals in the UK during the summer. If you would like to talk to Scott aboutthe book, anything .NET, or the British music festival scene, feel free to write to him by email [email protected], or by giving him a tweet @ScottMillett.

    Scotts Books:

    Real World .NET, C#, and Silverlight: Indispensible Experiences from 15 MVPs (Chapter 13BDD) (Wrox, 2011)

    Pro Agile .NET Development with SCRUM (Apress, 2011) Professional ASP.NET Design Patterns (Wrox, 2010) Professional Enterprise .NET (Wrox, 2009) NHibernate with ASP.NET Problem Design Solution (Wrox, 2009)

    i

  • IntroductionWhy You Should Read This Book

    Writing software is easy, sorry writing greenfield software is easy. When it comes to modifiyingcode written by other developers or code you wrote six months ago, it can be a bit of a bore atbest and a nightmare at worst. The software works but you arent sure exactly how. It contains allthe right frameworks, patterns and has been created using an agile approach, yet introducing newfeatures into the code base is harder than it should be. Even business experts are of no use as thecode bears no resemblance to the language they use. Working on such systems becomes a choreleaving developers frustrated and devoid of any coding pleasure.

    Domain-Driven Design (DDD) is a process that aligns your code with the reality of your problemdomain. As your product evolves, adding new features is as easy as it was in the good old daysof greenfield development. Where DDD understands the need for software patterns, principles,methodologies and frameworks, it values developers and domain experts working together tounderstand domain concepts, policies and logic equally. With a greater knowledge of the problemdomain, and a synergy with the business, developers are more likely to build software that is morereadable and easier to adapt for future enhancement.

    Following the DDD philosophy will give developers the knowledge and skills they need to tacklelarge or complex business systems in an effective manner. Future enchancement requests wont bemetwith an air of dread and developers will no longer have stigma attached to the legacy application.In fact the term legacy will be recategorised in a developers mind as meaning; A system thatcontinues to give value for the business.

    Who Should Read This Book

    This short book introduces the main themes behind Domain-Driven Design (DDD), its practicesand principles along with my experiences and interpretation of the philosophy. It is intended tobe used as a learning aid for those interested in or are starting out with the philosophy. It is nota replacement for Domain-Driven Design: Tackling Complexity in the Heart of Software by EricEvans (Addison-Wesley Professional, 2003). Instead it takes the concepts introduced by Evans anddistils them into simple straightforward prose, with practical examples in order for any developerto get up to speed with the philosophy before going on to study the subject in more depth.

    This book is based on my experiences with the subject matter so you may not always agree with itif you are a seasoned DDD practitioner, but I do hope you still get something out of it. Either wayplease send me feedback on the book and let me know if you need any area explored in more detailor if I have not succeeded in my goal of explaining concepts simply and concisely.

    I look forward to receiving your feedback - [email protected].

    ii

  • Introduction iii

    Domain-Driven Design In A Nutshell

    A Problem Space

    Before you can develop a solution you must understand the problem. Domain-Driven Designemphasises the need to focus on the business problem domain; its terminology, the core reasonsbehind why the software is being developed and what success means to the business. The need forthe development team to value domain knowledge just as much as technical expertise is vital to gaina deeper insight of the problem domain.

    The figure below shows a high-level overview of the problem space of Domain-Driven Design thatwill be introduced in the first part of this book.

    A blueprint of the problem space of Domain-Driven Design.

    A Solution Space

    With a sound understanding of the problem domain strategic patterns of DDD can help you toimplement a technical solution in synergy with the problem space. Patterns enable core parts of yoursystem that are crucial to the success of the product to be protected from the generic areas. Isolatingintegral components allows them to be modified without having a rippling effect throughout thesystem.

  • Introduction iv

    Core parts of your product that are sufficiently complex or will frequently change should be basedon a model. The tactical patterns of DDD along with Model-Driven Design will help you to createa model. A model that is in synergy with the problem domain will enable your software to beadaptable and understood by other developers and business experts.

    The figure below shows a high-level overview of the solution space of Domain-Driven Design thatwill be introduced in the first part of this book.

    A blueprint of the solution space of Domain-Driven Design.

    How This Book Is Structured

    The first part of this book is an introduction on Domain-Driven Design. Its heavy on the prose andlight on the code samples. If you already have a good grounding in the philosophy then you canskip this part and go straight to the code in part II.

    Part II puts the theory of the strategic and tactical patterns of DDD into practice. I show youimplementations of the patterns contained within Erics book along with some best practices toaid you with Model-Driven Design.

    Part III is an end-to-end case study designed to show you how to put the practices of DDD togetherin order to design and build a complex system.

  • Introduction v

    Part I: The Theory: Introduction To The Philosophy

    The opening section of the book introduces you to the philosophy of DDD. You will learn whyDDD is needed when dealing with the creation of large complex systems and how it can helpyou to avoid an unmanageable code base.

    The importance of the collaboration with Domain Experts to gain domain knowledge isdiscussed next. Domain knowledge will enable you to understand the most important areasof the application you are creating and where to spend the most time and effort.

    The benefit of creating a shared Ubiquitous Language is then explored. The idea of a sharedlanguage is core to DDD and underpins the philosophy. A language describing the terms andconcepts of the domain, which is created by both the development team and the businessexperts, is vital to aid communication on complex systems

    Strategic coding patterns designed to protect the integrity of core parts of the domain arepresented after knowledge of the domain is gained along with patterns to aid team working.

    Tactical patterns for implementing the Model-Driven Design methodology for complex coreareas of your application are covered in depth.

    The last section of part I describes when not to use Domain-Driven Design, and why itsjust as important as knowing how to implement it. Simple systems require straight forwardsolutions. The end of this part looks at why applying DDD to simple problems can lead tooverdesigned systems and needless complexity.

    Part II The Practice: Coding The Strategic And Tactical Patterns Of DDD

    (TBC) Strategic Patterns of Domain-Driven DesignDetails on the options open for architecting Bounded Contexts.Code examples detailing how to integrate with legacy applications.Techniques for communicating across Bounded Contexts

    (TBC) The Building Blocks of Domain-Driven DesignImplementation patterns for the building blocks of DDD.

    (TBC) Domain-Driven Design Best PracticesBest practices for development.

    Part III Case Study: Putting Theory And Coding Patterns Into Practice

    (TBC) A Modelling ExampleWorking through the creation of an application based with a complex domain toshowcase all the practices of DDD.

    Other Books On Domain-Driven Design

    Evans original text on Domain-Driven Design:

  • Introduction vi

    Domain-Driven Design: Tackling Complexity in the Heart of Software by Eric Evans(Addison-Wesley Professional, 2003)

    Other good books on Domain-Driven Design are:

    Applying Domain-Driven Design and Patterns: Using .Net by Jimmy Nilsson (AddisonWesley, 2006)

    Implementing Domain-Driven Design by Vaughn Vernon (Addison Wesley, 2013) Growing Object-Oriented Software, Guided by Tests by Steve Freeman and Nat Pryce(Addison Wesley, 2009)

    Specification by Example: How Successful Teams Deliver the Right Software by Gojko Adzic(Manning Publications, 2011)

    Websites and groups on Domain-Driven Design:

    http://groups.yahoo.com/group/domaindrivendesign http://domaindrivendesign.org

  • I The Theory: Introduction To ThePhilosophy

    Whats in this part?

    Introduction to the philosophy of Domain-Driven Design The problem of blurred responsibilities in code resulting in the big ball of mud Collaborating with domain experts to gain domain knowledge Understanding the importance of identifying the core, supporting and generic domains insystem under development

    The benefit of creating a shared ubiquitous Language in order to describe the terms andconcepts in the domain

    Protecting the integrity of core parts of the domain Driving development of complex core domains with Model-Driven Design When not to use Domain-Driven Design

    1

  • 1 The Need For Domain-Driven DesignIt is not the strongest of the species that survives, nor the most intelligent thatsurvives. It is the one that is the most adaptable to change. Charles Darwin

    Domain-Driven Design (DDD) is a development philosophy defined by Eric Evans in his seminalwork Domain-driven design: tackling complexity in the heart of software (Addison-Wesley Profes-sional, 2003). DDD prescribes a set of principles and practices aimed at refocusing efforts alongwith investment around the most critical and key parts of large-scale business software; namelythe business logic, concepts, terminology, workflows and processes. The benefit of practicing DDDallows the software to be quickly adapted to support change in the business and deliver value to theareas that are most important.

    The three main practices that underpin the philosophy are:

    Understanding which part of a large system is fundamentally important to a business,i.e. what is considered core to its success, what will set this system apart from others inthe same market, and what gives it the edge; put another way, what part of the systemdoes your business consider its competitive advantage.

    Capturing concepts, communicating and writing code using a shared language based onthe domain you are working within.

    Basing the core area of the application on a model of the business problem domain usingthe tactical patterns of DDD and following a model-driven design. Whilst employ ingstrategic patterns of DDD to protect the integrity of the core area and subdomains ofthe system.

    1.1 A Philosophy Over A Framework Or Methodology

    DDD is not a strict methodology nor is it a framework that you can leverage to build applicationsupon. Instead it is, in its purest form, a development mind shift for teams writing complex orfrequently changing large-scale business software. Focus, investment and effort are placed deeplywithin the core business domain with technical considerations playing a mere supportingrole. DDD promotes collaboration, evolution and experimentation above everything else in orderto develop a useful model of the business domain which is placed at the heart of the software.What I love most about DDD is that its not an inhibitive methodology or framework; Its acollaboration philosophy focused on delivery.

    Strategic patterns of DDD can help you to identify and isolate the parts of the system that are definedas core to the success of the software. These patterns will enable you to retain the integrity of theseareas. If the core parts of your business software are sufficiently complex then tactical patterns ofDDD can help you to create software of a high quality by basing the core domains (the parts a system

    2

  • The Need For Domain-Driven Design 3

    that will give you the most value) on an abstract model that reflects the real business subdomain.This model will enable the core parts of the system to be flexible enough to change when criticalparts of the business change.

    ..

    What is a Problem Domain?A problem domain refers to the subject area that you are building software for. DDD stressesthe need to focus on the domain above anything else when working on creating softwarefor large-scale and complex business systems. Experts in the problem domain work withthe development team to focus on the areas of the domain that are useful to be able toproduce valuable software. For example when writing software for the health industry torecord patient treatment it is not important to learn to become a doctor. What is importantto understand is the terminology of the health industry, how different departments viewpatients and care, what information doctors gather and what they do with it.

    1.2 Writing Large-Scale Complex Business Software IsHard

    It doesnt take a lot of skill to get a program to work. The skill comes in whenyou have to keep it working. Robert C. Martin @unclebobmartin

    The challenge of writing and enhancing software for large-scale complex systems is not just abouttechnical considerations. In fact for complex domains the technical concerns could be very simple.The development team should focus as much enegery and effort on the domain logic as they doon the technical aspects. Teams should understand why theyre producing the software and whatit means for the software to be successful to the business. It is the appreciation for the businessintent that will enable the development team to identify and invest their time in the mostimportant parts of the system. As the business evolves, so in turn must the software; it needs tobe adaptable. Investment in the quality of code in the key areas of the system will help it to changeeasier with the business. If key areas of the software are not in synergy with business domain then,over time, it will rot and turn into a big ball of mud. Resulting in software which is hard to maintain.

    ..

    Before Creating A Solution You Must Understand The ProblemSoftware projects fail when we dont understand the business model. Typing is not thebottleneck for delivering a product; coding is the easy part of development. Understanding,analysis and discovering a solution to a problem is the hard part. The greater you understand

  • The Need For Domain-Driven Design 4

    ..

    your business domain the better equipped you will be when you are trying to solve problemswithin it.

    Code Without Organisation Will Rot

    A Big Ball of Mud is a haphazardly structured, sprawling, sloppy, duct-tape-and-baling-wire, spaghetti-code jungle. Brian Foote and Joseph Yoder

    By far the most popular software architectural design pattern for business applications is the Big Ballof Mud (BBoM) pattern. BBoM, as defined by Brian Foote and Joseph Yoder, describes an applicationthat appears to have no distinguishable architecture (think big bowl of spaghetti versus a dish oflayered lasagne). The issue with allowing software to dissolve into a BBoM becomes apparent whenroutine changes in workflow and small feature enhancements become a challenge to implementdue to the difficulties in reading and understanding the existing code base. In his book, Eric Evansdescribes such systems as containing code that does something useful but without explaining how.

    We typically find that the initial incarnation of a system that resembles BBoM was fast toproduce and a well-rounded success, however because there was little focus on business need,subsequent enhancements are troublesome. The code base lacks the required synergywith thebusiness behaviour to make change manageable.

    Developing In Mud

    Continuing to persist with an architectural spaghetti-like pattern can lead to a sluggish pace offeature enhancement. When newer versions of the product are released often they can be buggydue to the unintelligible mess of the code base that developers have to deal with. Over time thedevelopment team increasingly complains about the difficulty of working in such a mess. Even ifresource is added to the project, velocity cannot be increased to a level that satisfies the business.

    In the end, exacerbated by the situation, the request for the dreaded application rewrite is granted.Without due care and consideration however even the greenfield project can often fall fowl of thesame issues that created the original BBofM. This entire experience can be frustrating for the businessthat saw a great return on investment in terms of features and speed of delivery at the beginningbut over time, even with additional investment in resource, did not see the sustained evolution ofthe product to meet the needs of the business.

    ..

    The Ticking Technical Debt Time bombTechnical debt is the name given to poorly created and hastily written code. Technical debtis a result of quick and dirty changes instead of a considered and clean approach to software

  • The Need For Domain-Driven Design 5

    ..

    design. Technical debt is similar to financial debt in that if you do not pay it back quicklyyou will incur greater costs later when you try and deal with it. The problem with technicaldebt is that it makes future changes to the software very difficult as the code is constructedin an unorganised manner. Sometimes it is a pragmatic choice to incur some technical debtin order to hit a deadline. However it is important that after the deadline is met, and if thesoftware will be continued to be invested in, that the technical debt be paid back in the formof refactoring.

    ..

    What is Refactoring?Refactoring is the redesign of a softwares structure without altering its functionality. Thepurpose of refactoring is to make the software design easier to read and easier to change,as developers spend more time reading code than writing it. As teams iterate through thecreation of a product they learn more about the domain, and this knowledge needs to betransferred into code. Lots of small refactorings enable deeper insight into the problemdomain andwill enable other developers to understand andmodify the software with greaterease in the future. Unit and integration tests support refactoring by enabling developers toalter the design of software with the confidence that they wont break existing functionality.

  • 2 Understanding Your Problem SpaceAs you read the explanations of these terms, here and in the book [Evans, DDD],remember that all of these terms are first about how to organise the concepts thatare behind the design. From that follow techniques for organising the physicalimplementation of those concepts. Eric Evans, DDD Forum

    So what is required to tackle the creation of a complex application? How can we ensure we arebuilding solid systems that meet the wishes of the business? That will work with us in the future,rather than working against us when the business needs to quickly alter a process or policy? As theenablers we need to refocus our efforts when creating and designing software. We need to focus onthe problem that the business is trying to solve with the application, and not the next fashionabledevelopment practice or shiny new framework. We need a codebase that contains a model of thedomain in synergy with the business. Constantly evolving as the business changes. We needto align ourselves with the vision of the software. Clearly understanding what is core to thesuccess of the application.

    The aim of this chapter is to show you how you can align the development team to the intent andwishes of the business as you begin to capture requirements and break down the problem domain.

    The figure below shows the areas of the DDD that relate to understanding the problem space.

    http://tech.groups.yahoo.com/group/domaindrivendesign/message/1504

    6

  • Understanding Your Problem Space 7

    The problem space.

    2.1 Knowledge Crunching : Finding The Model

    If you cant explain it in simple terms, you dont know it well enough. Einstein

    Knowledge crunching is the art of soaking up information about the problem domain whilsthaving the ability to sift out whats not important in order to create an effective model ofthe domain, otherwise known as a domain model. Knowledge gathering occurs on whiteboards,working through examples with business experts and generally brainstorming together. It is thequest to discover and agree on a shared understanding of the problem domain.

    What Is A Domain Model?

    The domain model is at the centre of Domain-Driven Design. It is expressed as a code implemen-tation which represents a view, not the reality, of the problem domain. Its usefulness comes in itsability to represent complex logic and polices in the domain in order to solve business problems. Italso exists in a more abstract space, in the language the team speak and the diagrams they sketch.The model is built from the collaboration between the development team and business experts.

  • Understanding Your Problem Space 8

    The model contains only what is relevant to solve problems in the context of the application beingcreated. It needs to constantly evolve with the business in order to keep itself useful and valid.

    A domain model can be represented in UML or code as shown in the figure below.

    A domain model in code and UML.

    So where do we start when trying to create a domain model? How do we as developers get a greaterunderstanding of the problem domain we are creating software for?

    Gaining Domain Knowledge

    the key to expert performance in many fields is domain knowledge rather thanintelligence. Don Reinertsen

    Domain knowledge is key. Teams working in a business with complex processes and logic needto immerse themselves in the problem domain, and, like a sponge, absorb all the relevant domainknowledge. This insight will enable teams to create a model at the heart of their applications codebase that can fulfil the wishes of the business.

    The Challenges With Upfront Design

    Writing code is not the problem.

  • Understanding Your Problem Space 9

    Historically the capturing of requirements for software systems was seen as an activity that couldoccur long before coding was due to start. Business experts would talk to business analysts, who inturn would talk to architects who would produce an analysis model based on all of the informationfrom the problem domain. This analysis model would then be handed over to the developers, alongwith wireframes and workflow diagrams in order for them to build the system.

    ..

    What Is An Analysis Model?An analysis model is a collection of artefacts that describe the model of a system. Theseartefacts can be in the form of UML such as class diagrams and interaction sequencediagrams. The analysis model exists to understand the problem domain; it is not a blueprintfor the technical implementation.

    As developers start to implement the analysis model in code they would often find a mismatchbetween the high-level artefacts produced by architects and the reality of building the system.However at this stage there is often no feedback loop for developers to talk to the business andarchitects in order for the analysis model to be updated and their discoveries to be reflected.Instead the developers diverge from the analysis model and their implementation often overlooksimportant and descriptive domain terms and concepts that would have provided deeper insight andunderstanding of the domain.

    As the development team further evolves away from the analysis model it becomes less and lessuseful. Crucial insight into the model is lost as the development team focus on abstracting technicalconcerns instead of business concepts. In the end the job gets done but the code bares no reflectionto the original analysis model. The business still believe their analysis models are correct. Theyare unaware of the alterations within the code model required to fulfil the wishes of the businessapplication.

    The figure below shows how the analysis and code models can diverge from each other if thedevelopment team are not involved in domain knowledge crunching.

  • Understanding Your Problem Space 10

    The problems with upfront design.

    The reasonwhy this is a problem is revealed when later enhancements to the codebase are difficult toimplement. The difficulties are due to the business experts and developers having different modelsof the business. The code doesnt have a synergy with the business processes and is not rich indomain knowledge.

    TeamModelling

    DDD suggests a more collaborative method of capturing system requirements and understandingexisting workflow. Emphasis is placed on the entire team together with business experts andarchitects (as long as they code) having discussions around the problem space. Discussions caninclude any documentation or legacy code that is related to the system in question. The idea behindthe collaborative knowledge crunching sessions is for the developers, testers, business analyst,architects and business experts to work as a single unified team. This enables the developersand testers to learn about the meaning behind domain terms and understand complex logic inthe problem area. It will also enable business experts to experience the modelling techniquesemployed. With an understanding of modelling, business experts, will themselves, be able tomodel and validate designs with the development team.

  • Understanding Your Problem Space 11

    The sharing of information enables business experts to contribute to the software design as wellas providing a deeper insight and understanding of the domain to the development team. After aperiod of time developers, and business experts will discover the relevant information to build aninitial model of problem domain. This initial model is put to test by using domain scenarios; realproblems of the domain to validate its usefulness. Modelling out loud, using the terms and languageof the model can also help to validate early designs.

    The important aspect of modelling together is the constant feedback the development team get fromthe business experts. This leads to the discovery of important concepts and also allows the team tounderstand what is not important and can be excluded from the model. Breakthroughs in sessionsare manifested as simple abstractions that clarify complex domain concepts which lead to amore expressive model.

    Themodel is then expressed in code and the team, along with business experts can gain fast feedbackwith early versions of software. Feedback in turn fuels deeper insight which can be reflected in thecode and analysis models, as highlighted in the figure below.

    The code model and the analysis model are kept in synergy.

    During each iteration the development team may come across parts of the model that they thoughtwere useful and could solve a problem, but during implementation they had to change. Thisknowledge is fed back to the business experts for clarification and to refine their own understanding

  • Understanding Your Problem Space 12

    of the problem domain. In this process the code model and analysis model are one and a change inone will result in a change to the other

    The figure below shows how the analysis and code model are in synergy and evolve as one duringthe creation of a product.

    Team modelling.

    ..

    The Model DDD Cares AboutDomain-Driven Design doesnt advocate the removal of the analysis model. Far from itas there is much value to be gained from a model that describes the system. InsteadDDD emphasises the need to keep the code model; the implementation, in close synergywith the analysis model; the design. The utopia is a single model that has value in bothimplementation and design. To achieve this it is crucial to keep the code model clean oftechnical concerns and focused on the domain. In turn it is also important to have an analysismodel that can be implemented; not too abstract or high-level to be of any use.

  • Understanding Your Problem Space 13

    ..

    Modellers Block?Wake yourself up. Brainstorm in code by capturing business requirements as classes andmethods. Model on the whiteboard, on paper, with your colleagues or even your wife. Warmyour brain up by doing something, anything, and the design will eventually bubble up inyour consciousness. If that doesnt work perhaps ideas appear to you during times of quietcontemplation, and there is no better time for that then when getting the teas in for the team.Either way, invest in your problem by giving yourself time to think.

    Techniques For Creating A Useful Model

    All of the most creative professionals played with the problem longer before theyattempted to resolve it John Cleese

    Creating a useful model is a collaborative experience however business users can also find it tiringand can deem it to be unproductive. Business users are busy and have a lot to do. In order to makeyour knowledge crunching session fun and interactive you can introduce some facilitation games toengage with your business users.

    Capture Use Cases Of The System

    The best place to start when trying to understand a new domain is by mapping out use cases. A usecase lists the steps required to achieve a goal, including the interactions between users and systems.Work with business users to understand what users do with the current system, be it a paper basedprocess or computerised. Be careful to listen out for domain termingology as this will form thestart of your shared language for describing and communicating the problem domain. Remember,capture a process map of reality, understand the workflow as it is, dont try and jump to a solutiontoo quickly before you truely appreciate the problem.

    Sketching

    UML is a wonderfully useful language that can be used to communicate complex systems in anunderstandable manner with little or no technical expertise. Therefore its a good choice to capturethe initial analysis model. However during knowledge crunching sessions a model is a fluid entityand will be changing at a rapid rate. Therefore dont try and use elaborate packages such as Visioor Rational Rose to capture a moving model. Instead sketch out the model on the white board. Youwill be less precious about a sketch that took you minutes to draw than a diagram in Visio that tookyou most of the morning. If you must write up your knowledge crunching sessions do it at the endwhen you know the most about the problem domain.

  • Understanding Your Problem Space 14

    Team modelling on a whiteboard.

    Defer The Naming Of Concepts In Your Model

    Naming is very important when modelling a domain. However premature naming can sometimesbe a problem when we discover through further knowledge crunching that concepts turnout to bedifferent to what we first understood them to be. The issue is the association with the word thatwas chosen as the original name, and the way it shapes our thinking. Grey Young suggests thatwe make up words for areas of the model we are not sure about using gibberish . I tend to favourusing colours, but the idea is the same. Instead of giving areas or concepts of the model real namesuse gibberish until you have understood all the responsibilities, behaviour and data of a concern.Deferring the naming of concepts in your model will go a long way to helping you avoid modellingreality.

    Also look out for overloaded terms. The types of names that you want to avoid are XXXXServiceor XXXXManager. If you find yourself post pending service or manager to a concept think morecreatively, striving for real intent behind a name. When you feel you have really understood a partof the model you will be in a better place to give it a sensible and meaningful name.

    Powerful Questions

    Powerful questions are key to good analysis sessions. Greg Young

    What does good look like? What is the success criteria of this product? What will make it aworthwhile endeavour? What is the business trying to achieve? The questions you ask duringknowledge crunching sessions will go a long way to revealing a greater understanding of theimportance of a the product you are building and the intent behind it.

    Here are some examples to get your domain expert talking and revealing some deeper insight intothe domain:

    http://codebetter.com/gregyoung/2012/02/28/the-gibberish-game-4/

  • Understanding Your Problem Space 15

    Where does the need of this system come from? How will this system give value to the business? What would happen is this system wasnt built?

    Greg Young has a great blog post on powerful questions with comments offering many more goodexamples of questions that can unlock domain knowledge.

    Rapid Prototyping

    Favour rapid prototyping during knowledge crunching sessions. Business users like nothing morethan screen mock-ups, as it reveals so muchmore about the intent they have behind a product. Usersunderstand UI, they can interact with it and act out workflows clearly.

    Another form of rapid prototyping is to capture requirements in code. Greg Young calls this codeas analysis. Again business users will love the fact that you are writing and creating before theireyes. Starting to code will help focus analysis sessions. Starting to implement abstract ideas fromknowledge crunchingwill enable you to validate your design. It also helps to avoid you only thinkingabstractly which can lead to analysis paralysis.

    Coding quickly helps create your powerful questions. Helps find missing use cases. Use the code toidentify and solve the problems. After an hour or so of talking see if you can create a code model ofyour brainstorming. I often find creating code quickly helps to cement domain concepts and speedsup knowledge crunching as the team is deeply engrossed in learning about the domain.

    Remember only create a code model of what is relevant and within the specific context to solve agiven problem; you cant effectively model the entire domain. Think small and model around rulesthen build up. Most importantly remember that you are writing throw away code, dont stop at thefirst useful model, and dont get too attached to your first good idea.

    Look For Existing Models

    Sometimes you dont need to reinvent the wheel. If you are working in a domain that has beenaround for a long time such as a financial institution you can bet that it probably follows a knownmodel. You wont have time to become an expert in your problem domain so seek out informationthat teaches your more about the domain. Analysis Patterns: Reusable Object Models by MartinFowler (Addison-Wesley, 1996) presents many common models in a variety of domains that you canuse as a starting point in discussions.

    Models of the problem domain could already exist in the organisation. Ask for existing processmaps, workflow diagrams to help you understand the domain at a deeper level. Create a knowledgebase like a wiki with terms and definitions to share with the team. Remember you are only as goodas your weakest developer, this applies to domain knowledge as much as technical expertise.

    http://goodenoughsoftware.net/2012/02/29/powerful-questions/http://skillsmatter.com/podcast/open-source-dot-net/mystery-dddhttp://sourcemaking.com/antipatterns/analysis-paralysis

  • Understanding Your Problem Space 16

    ..

    Try, Try And Try AgainYou wont get a useful model on the first attempt; you might not even get one on the secondor third attempts. Dont be afraid of experimentation. Get used to ripping up designs andstarting again. Remember there is not a correct model, only a model that is useful for thecurrent context and set of problems you are facing.

    2.2 Domain Experts: Your Guide To DeeperUnderstanding In Your Problem Domain

    The collaboration between the business customer and the development team is an essential aspect ofDDD and one that is crucial to the success of a product under development. However it is importantto seek out those who are experts in the domain you are working in, and who can offer you deeperinsight into the problem area. DDD refers to these subject matter experts as domain experts. Thedomain experts are the people that deeply understand the business domain from its policiesand workflows, to its nuisances and idiosyncrasies. They are the experts within the businessof the domain, they will rarely, if ever, have the title Domain Expert. Instead look for theproduct owners, users and anyone who has a great grasp and understanding for the domainyou are working in regardless of title.

    ..

    Make The Most Of Your Domain Expert, You Never Know When She Will Be GoneUtilise the time spent with your domain expert, dont just ask them to produce sets ofrequirements or validate ones that you have produced. Actively engage with domainexperts in knowledge distilling sessions, whiteboard with them, experiment and showhow you have a desire to learn more about the domain you are producing software for.A domain experts timewill be precious, meeting them halfway and showing a genuineinterest will display to the domain expert that there is value in sharing knowledge.

    Sit With Your Domain Experts

    To enable the high level of collaboration it is recommended to co-locate the development teamwith domain experts who will be on hand to answer questions and participate during analysis atimpromptu corridor or tea station meetings; something that is lost when the only communicationis restricted to weekly project meetings. The collaboration is such an essential part of DDD that

  • Understanding Your Problem Space 17

    without it a lot of the design breakthroughs would not happen. It is this deeper design insightthat makes the software useful and able to adapt as and when the business processes change.

    If its not possible to sit with your domain expert then join her for lunch. Spend as much time as youcan with her, learn as much as possible. You will never gain an insight into a domain from weeklyproject meetings. You must eat, sleep and breathe it. Read around the subject; immerse yourself init. You will produce better software.

    ..

    Be Careful What Youre Asked ForBe wary of customers asking for enhancements to existing software as they will often giveyou requirements that are based on the constraints of the current systems rather than whatthey really desire. Ask yourself how often you have engaged with a user to really findthe motivation behind a requirement. Have you understood the why behind the what?Once you share and understand the real needs of a customer you can often present a bettersolution. Customers are usually met by surprise when you engage them like this, quicklyfollowed by the classic line: Oh really I didnt know you could do that? Remember, youare the enabler, dont blindly follow the users requirements, business users may not be ableto write effective features and express goals. You must share and understand the underlyingvision and be aware of what the business is trying to achieve in order to offer real businessvalue.

    2.3 Knowledge Distillation : Breaking Down LargeSystems To Find What Is Core

    Much of the essence of building a program is in fact the debugging of thespecification Fred Brooks

    As you are modelling a system you may start to feel its getting a little large. Signs such as theinability to fit a UML diagram on a single six foot wide whiteboard mean you need to break upyour model. When building any large system you wont be able to create a single domain modelthat adequately covers it. Terms will mean different things in different parts of you domain and toolarge of a model will be incomprehensible.

    You need to understand that there will be some parts of the application that are more important thanothers. Some parts will need more attention and investment than others to make the application asuccess. During knowledge crunching with domain experts its important to reduce the noise ofwhats unimportant to enable you to focus on what is important; use distillation to reveal the coreareas of the system. Deeply model what is core and focus on what will make a difference.

  • Understanding Your Problem Space 18

    Subdomains

    Large models can be broken down into subdomains in order to focus on specific areas of the domainto create more focused smaller models. Many of these subdomains will be generic to any enterprisebusiness software such as reporting and notification needs. These subdomains, which do not definethe application are referred to as generic domains. The areas that distinguish your companys uniqueproduct offering from a rivals and defines what gives it a competitive edge in the market are knownas your core domains. The core domains are the reason why you are writing this software yourself.The remainder of the subdomains that make up a large-scale applications are known as supportingdomains.

    ..

    One Model To Rule Them All?It may seem sensible to model the entire problem domain using an enterprise model.However this can be problematic due to the fact that it will need to cater for all the needsof your domain. This will render the model too complex or overly generic and devoid ofany meaningful behaviour. If you have large systems it is far better and more manageableto break down the problem space into smaller more focused models that can be tied to aspecific context.

    Seeing The Wood In-spite Of The Trees

    Take the domain model of an e-commerce application. There are many different components thatmake up the large overall system. Some parts will be found in any e-commerce system, howeversome will be unique to your company. These parts will define the software and will be thefundamental reasons of why you are building rather than buying.

    The figure below shows the large domain model of an e-commerce application.

  • Understanding Your Problem Space 19

    The domain of e-commerce.

    The figure below shows how the domain model of an e-commerce application can be distilled intosubdomains.

  • Understanding Your Problem Space 20

    The domain of e-commerce distilled into subdomains.

    The distillation of knowledge after sessions with domain experts should reveal whats unique andimportant about the application you are about to create. The subdomains can be separated into core,generic and supporting domains as shown in the figure below.

  • Understanding Your Problem Space 21

    The distilled domain of e-commerce sorted into core, generic and supporting domains.

    In order to knowwhere to invest the most effort and quality its crucial to understand where the coredomains are as these are key to making the software successful. This knowledge is distilled fromknowledge crunching sessions working in collaboration with domain experts to understandwhats the most important aspect of the product under development.

    Core Domains

    To understand whats core to the product that your business is asking you to develop you need toask yourself: What are the parts of the product that will make it a success? Why are these parts ofthe system important? And why cant they be bought off the shelf? In other words, what makesyour system worth building?

    The core parts of the system represent the fundamental competitive advantage that yourcompany can gain through the delivery of this software. Whats core is not always obvious.

    If the generic domains should be bought in and have little development, then the core domain is thepolar opposite. The core domains will require your best developers, your commandos if you will.

  • Understanding Your Problem Space 22

    The core domains may not make up the lions share of your companys technology but they willrequire the most investment.

    What is core will certainly change over time. If you are successful competitors will mimic, so thecore domain must evolve in order to set your business apart from the rest and keep it ahead of thegame. Its vital that the development team take this on board and ensure they are in synergy withthe values of the software and the business.

    ..

    The Core Domain of Pottermore.comPottermore.com is the only place on the web were you can buy digital copies of the HarryPotter books. Like any e-commerce site it has the ability to browse products, store products ina basket and checkout. The core domain of the Pottermore site is not what the customer sees,but rather what they do not. Pottermore books arent DRM-locked , they are watermarked.This invisible watermark allows the books that are purchased to be tracked if they shouldbe hosted illegally on the web. The core domain of the Pottermore system is the subdomainthat enables this watermarking technology to deter illegal distribution of a book withoutinfringing on the customer e.g. she can copy the book to any other her devices. This iswhats most important to the business, what sets it apart from other ebook sellers and whatensures the system was built rather than being sold on iTunes or other ebook sellers.

    http://www.futurebook.net/content/pottermore-finally-delivers-harry-potter-e-books-arrive.

    Domain Vision Can Reveal What Is Core

    Before embarking on any product engagement always ask for a project overview. In any largeorganisation the process of project inception starts long before the development team get involved.Often there will be a small paper on why the company wants to build the software for this initiativeover another. This paper often holds the key to the core domain. The paper is a justification on whywriting the software is a good idea, study this and a pick out what is important. Make it explicitby writing the salient points on the whiteboard so all the team understand why they are writingthe software. The Domain vision statement will reveal what is central to the success of thesoftware, what the business goal is and where the value is.

    ..

    Amazons Approach To Product DevelopmentAmazon have a unique approach when it comes to forming a domain vision statement calledworking backwards . For new enhancements a product manager produces an internalpress release announcing the finished product, listing the benefits the feature brings. If theintended customer doesnt feel the benefits are exciting or worthwhile then the product

  • Understanding Your Problem Space 23

    ..

    manager will refactor the press release until the feature offers real value for the customer.At all times Amazon are focused on the customer and ensure that they are clear about theadvantage a new feature can bring before they set out with development.

    http://www.quora.com/What-is-Amazons-approach-to-product-development-and-product-management

    Generic Domains

    A Generic Domain is a subdomain that can be found in many large business systems. An exampleof a generic domain is an email sending service, an accounts package, or report-suite. Thesesubdomains arent core to the business, but the business cant operate without them. As thesesubdomains arent core and wont give you a competitive edge it doesnt make sense to spend alot of effort or investment in building them. Instead look to buy in software for generic domain.Alternatively use junior developers to build these systems, freeing up more experienced resource towork on whats core to your business.

    Note, however, that a business defined by communication and targeted emails on limited time offers,like a Groupon orWowcher, could have its core domain as a sophisticated email/CRM system. Whatis core to one business may well be generic to another.

    Supporting Domains

    The remaining subdomains in the system are defined as the supporting domains. These aresubdomains that, while not defining what your system does, help to support your coredomains. For example, Amazons supporting domains would be the functionality that enables acustomer to browse a catalogue for products. Amazons product browsing functionality doesntdefine it as a company and neither is it that different from any other e-commerce site, but it doessupport the tracking of user journeys in order to feed a recommendations engine.

    As with the generic domains, if possible, you should look to buy off-the-shelf solutions. Failingthat, do not invest heavily in these systems; they need to work but do not require your prolongedattention. Its important to note that you may not always need to implement a techniqual solutionto a supporting domain. Perhaps a manual process could meet the needs of the business whiledevelopers focus on the core domain.

    The Core Domain Doesnt Always Have To Be Perfect First Time

    In an ideal world quality software would always be top of your agenda, however its important to bepragmatic. Sometimes a new systems core domain could be being first to market, or sometimes abusiness may not be able to tell if a particular idea will be successful and become core to its success.

  • Understanding Your Problem Space 24

    In this instance the business want to learn quick and fail fast without putting in a lot of upfronteffort.

    The first version of a product that is not well understood by the business may not be well crafted.This is fine as the business is unsure if it will be invested in over time, and the development teamshould understand why the business want speed of delivery over supple design. However, if theproduct is a success and there is value in a prolonged investment in the software, you will needto refactor in order to support the evolution, otherwise the technical debt racked up in the rush todeliver will start to become an issue.

    Subdomains Exist In The Problem Space

    Understanding the subdomains of your system enables you to break down the problem space.Subdomains are abstract concepts; dont get subdomains confused with the organisational structureof a company. Subdomains represent areas of capability, define business processes and representthe functionality of the business.

    Try not to bring technical concerns into conversation when you are analysing the problem space.Security is a technical concern unless your problem space is security. Audit trails and logging arealso infrastructural concerns. Instead keep focused on the domain first and foremost. Understandyour problem space fully before rushing to implement your solution space.

    2.4 Model In Context

    So now you understand what parts of your system are core to the success of it. You are inline withthe vision of your business and you know where the value lies. Armed with this information youcan focus on models in context. Within each subdomain could live a specific model or two. Youmust apply your knowledge crunching techniques to theses subdomains to reveal a more conciseand focused model of the domain.

    Context is a very important term in Domain-Driven Design. Each model has a context implicitlydefined with a subdomain. When we talk about a product in the context of the fulfilment subdomainwe dont need to call it a fulfil-able product, likewise when talking in the context of shopping its nota saleable product. Its simply a product in a defined context.

    When we communicate with domain experts or other members of the development team we ensurethat everyone is aware of the context that we are talking in. The context defines the scope ofthe model, limiting the boundaries of the problem space, enabling the team to focus withoutdistractions.

  • Understanding Your Problem Space 25

    Multiple Models.

    Without Context We Are Nothing

    In many of the the larger enterprise applications you will work on there could be several of theidentified generic, core and supporting domains coexisting. In each of these subdomains you maywell discover the same terms and concepts being used but different contexts of the business will viewthe same concepts and interpret terminology in very different ways. For example the concept of aproduct in a sales context will be vastly different than a product in a pricing context in the domainof an e-commerce organisation. The sale context is interested in the description of a product alongwith its colour, weight and reviews. In comparison the pricing context needs to understand if theproduct is in a current offer or if it is applicable to discounts that are dependant on the type ofcustomer purchasing the product.

    In the figure below we see the concept of a product existing without an explicitly defined context.It has been distorted in order to satify the needs of many different models.

  • Understanding Your Problem Space 26

    Overlapping terms in subdomains.

    Context Game

    In order to demonstrate the importance of modelling in context and to reveal multiple models withinthe domain you can employe another facilitating game. The Context Game, a game that I learnt froma Greg Young , helps to make it clear where an additional model is require to map the problem spaceeffectively.

    You can introduce the game into knowledge crunching sessions when you think you have anoverloaded or ambiguous term. Split the group into smaller groups of developers and businessexperts. You should split the business experts by department or business responsibility. Give them20 mins to come up with a definition on what the term or concept means to them in their part ofthe business, using the developers to capture the knowledge. Then bring the whole team togetherto present their views on the concept.

    You will find that different parts of the business have different views on the shared terminology.

    http://codebetter.com/gregyoung/2012/02/29/the-context-game-2/

  • Understanding Your Problem Space 27

    Where the business functions have a difference of opinion this is where you need to draw yourcontext lines and create a newmodel. This is shown in the following figure with the product conceptexisitng in many different contexts.

    Putting terms into context and identifying multiple models.

    Multiple Models In A Subdomain

    Within a single subdomain you may find more then one context and therefore more than onemodel. Notice in the diagram below that the fulfilment subdomain has a replenishment model, pickalgorithm model and separate allocation model. The reason for this is that even in the boundariesof the fulfilment subdomain the concept of a product will mean different things to different areasof fulfilment. The replenishment model will only be concerned with the identity of a product andhow often it is purchased rather than a full description of it. The pick algorithm model will treat aproduct as an item that is stored in pickable and bulk storage locations. The allocation model willonly know about the availablity of a product for ordering. Therefore we will create a model in eachof the different contexts each containing its own version of a product concept.

  • Understanding Your Problem Space 28

    Subdomains can contain more than one bounded context

    2.5 Shifting Focus From The Project To The Product

    One of the fundamental shifts in mentality required for writing software for complex core domains,from both the development team and the business, is to focus on the product rather than view itas a standalone project. Often the development of software for a business product may never befinished; instead the product under development will live through periods of feature enhancements.The software is invested in until it is no longer providing value for the business or it cant be enrichedwith further modifications.

    Your product is an evolving succession of feature enhancements and tweaks. Just as developersiterate so to do the business. A good idea becomes better after it is improved upon and fleshed outover time. Understand the value of the product you are working on, what return on investmentwill it bring to the company? Talk to your business sponsors about the future of the product to helpfocus your coding efforts; know what is important to them.

    Less Hast More Speed

    All too often software for the core domain of a business isnt viewed as a product that requires careand attention. Instead business software sacrifices quality and long-term investment for speed tomarket. Too much emphasis is placed on thinking about the project and looming deadlines ratherthan investing in the product for the future. This results in a code base that is hard to maintain andenhance, and falls into the architectural pattern of the Big Ball of Mud, as discussed earlier in thischapter.

    The flip side however, is a prolonged release date which is often non-negotiable if other businessinterests are dependent on the launch date of the software. The solution to this quandary is to lookto de-scope features in order to keep quality high and the deadline on track. To be in a position to

  • Understanding Your Problem Space 29

    do this you must understand and share the vision and ultimate goal that the software is expectedto meet. This Understanding will enable you to include only the most important features of theproduct and ensure it delivers the value expected by the business.

    2.6 The Salient Points

    Knowledge crunching is the art of processing domain information in order to identify therelevant pieces that can be used to build a useful model.

    Knowledge is obtained by developers collaborating with domain experts. Only capture relevant domain knowledge that will help you solve your problem or build

    your product. Value domain knowledge as much as technical knowledge. An analysis model is useful if it stays in synergy with the code model. If you are shaping the analysis or code models you have to be hands on and contribute

    to code. There is a place for architects but they must be coders as well. Domain experts are anyone in the organisation that can offer insight into the domain

    i.e. users, product owners, business analysts, other technical teams. Knowledge is gained around whiteboards, brainstorming and prototyping, in a collabo-

    rative manner with all members of the team. A model of the domain is created to represent the policies, rules and workflows of the

    business in software.

    Distillation is used to break down a large model in order to discover the the core, supportingand generic domains from within the mass of domain knowledge.

    Focus and effort should be invested on the core domain. The core domain is the reason you are writing the software. Outsource, buy in or put juniors on the supporting and generic domains. A domain vision statement will reveal what is core to the success of a product,

    understand this.

  • 3 Speaking The Language Of YourDomainIts amazing how easily people with no technical skills can diagnose complexsoftware problems. @jacksonh

    Understanding what your business considers core to the success of the product is one thing, but youneed to be able to talk about it with domain experts in a language you all understand. The benefitof this is that both developers and domain experts can collaborate to solve problems in the domainspace without having to translate technical concepts. This language should be used throughout theproduct, from class and method names to test scenarios.

    3.1 The Language Of Domain Experts

    I recently went curtain shopping with my wife and I must admit that while at the curtain shop Ihad no idea what the shop assistant was talking about. Pleated, hang length, interlining, these wereall terms that mean something specific in the domain of curtain makers. Employees in the shopcould spend an age describing to each other what they wanted but this could lead to ambiguity inmeaning. Instead using terms in the domain of a curtain shop keep conversations short and conciseand everybody who understands the domain understands their meanings.

    Its the same with carpenters, financial traders, the military and a nearly every domain you canimagine. Each has terms and concepts that mean something very particular to them. Asecret language that enables complex topics to be covered in concise and meaningful dialoguewithout the need for confusing waffle. It is vital for a development team to understand andcollaborate on this language, known as the ubiquitous language (UL). Its terms and concepts need tobe used when communicating with team members including domain experts, as well as being usedto name classes, methods and namespaces in the code base itself.

    When collaborating with domain experts create a glossary of domain terms toavoid confusion and to help make concepts explicit.

    3.2 Collaborating On An Enhanced Language

    It is not only the explicit terms and concepts that the development teammust learn from the business,they must also collaborate with the domain experts to define the assumed or implicit concepts thatmay not have terminology. These concepts must be named by the entire team and included in theshared ubiquitous language. The team may also need to create additional terms for concepts that

    30

  • Speaking The Language Of Your Domain 31

    dont exist in the problem domain but have been discovered and labelled during modelling in thesoftware.

    The teammust communicate with each other using the ubiquitous language. The developmentteam must use it in code, and the domain experts must use it when talking to the team. Thebenefit of a shared language removes the need to translate from business speak into tech andvice versa. It also removes the possibility of ambiguity and misinterpretation as everyoneunderstands the meaning behind the concepts.

    The ubiquitous language should be clean and concise. Technical terms should be removed in ordernot to distract from business concepts. Likewise domain terms not relevant for the software undercreation must also not be allowed to cloud the shared language.

    ..

    Validating The Model Out LoudLinguistic consistency can be used to validate the usefulness of a model. For example listento conversations about the model and focus on concepts in the design that dont fit or whenthe model cant easily satisfy business scenarios.

    Enhancing The Language With Discovered Terms

    As you gain a deeper understanding of the domain you are working in your ubiquitous languagewill evolve. Refactor your code to embrace the evolution by using more intention revealing methodnames. If you find a grouping of complex logic starting to form talk through what the code is doingwith your domain expert and see if you can define a domain concept for it. If one is found separatethe logical grouping of code into a specification or policy class.

    ..

    What Is A Specification?A specifictation represents a business rule that needs to be satisfied by the domain model orpart of it. Specifications can also be utilised for query criteria. For example you can queryfor all objects that satisfy a given specification.

    The ubiquitous language should be visible everywhere, from namespaces toclasses, and from properties to method names, use the language to drive the designof your code.

  • Speaking The Language Of Your Domain 32

    3.3 Working With Concrete Examples

    In order to better understand the domain you are in its a good idea to take specific examples ofdomain behaviour. Concrete examples of real scenarios help to cement process and concepts withinthe domain. However its important to reveal the intention of the business process and not theimplementation. Talk only in business terms, dont get technical.

    In the following dialog a business user is describing the process of customers at an e-commerce siterequesting a replacement for an order that wasnt delivered.

    When a customer doesnt receive their goods, they can request a new order for free. Theywill log into their account and click on the I have not received my items button. If theyhave already been flagged as having received a free order then they cant get anotherone without having spoken to customer services. Otherwise we will send them out a freeorder and update the database to show that this customer has already claimed for a lostitem. We will then contact the courier to see if we can claim back the cost of the lostorder.

    You will notice that in the description above the business user is not focusing on the business processbut rather the implementation concerns. The following sentence is not giving any value or insightinto the domain or business process.

    They will log into their account and click on the I have not received my items button.

    In the next sentence the business user is already second-guessing how you will implement thebusiness policy. Some experts may have some experience with databases and may go as far assuggesting data schemas. Again, this gives the team no deep understanding of the domain.

    If they have already been flagged as having received a free order then they cant getanother one without having spoken to customer services.

    From this set of requirements a team not interested in the domain may simply implement whatthey are told and will end up with a poor model that doesnt reflect the concepts and policies of thedomain. The impact of which could be a misunderstanding of what flagging the customer means,it may mean more than simply a tick in a database column and perhaps the catalyst for a the startof a seperate business workflow. Without understanding the domain and the intent of a feature thedevelopers wont appreciate the repercussions of just implementing what they are told.

  • Speaking The Language Of Your Domain 33

    Teach Your Domain Experts To Focus On The Problem And NotJump To A Solution

    Training and collaboration will help business people focus on the process rather than the implemen-tation; the problem space rather than the solution space. Below the previous requirements statementhas been rewritten using the language of the domain. It focuses on the business and its processes:

    If an order is not received an undelivered order notification can be submitted. Ifthis is the first claim then a replacement order is created. If a claim has been madebefore a claim case is opened and assigned to a customer service representative whowill investigate the claim. In all cases a lost mail compensation case is opened andsent to the courier with details of the consignment that was undelivered.

    In this descriptionwe have discoveredmany important domain concepts that weremissing before. Inthe rewritten prose we have introduced some terms into the ubiquitous language and the terminoloyof the domain has been made crystal clear. In fact the second description doesnt even contain thecustomer concept; Instead it focuses only on terms that are directly related to the process.

    Remember domain experts have no, or limited, understanding of technical terminology. Keep ex-amples focused on the business and if they are trying to help you out by jumping to implementationdetails just gently remind them to focus on the what and why of a system and ask them to leave thehow up to you.

    Using Features And Scenarios To Demonstrate Domain Scenarios

    Even though the second description of the process of a customer requesting a replacement order isfar better than the first it is still a bit wordy. More complex examples could be open to interpretation.To combat this you can utilise features and scenarios to capture requirements and business processin a clean and concise manner.

    A feature describes a behaviour that the gives value to the business. In a feature story a role andbenefit is also included. The clarity of role that relates to the feature enables the development team,along with domain experts to understand who to talk to or who to proxy. The benefit justifies theexistence of the feature, helping to clarify why the business user wants the feature.

    The feature below describes the benefit given to customers at an e-commerce site requesting whohave not received their orders.

    Feature: Enable customers to request replacement ordersIn order to receive goods that have not been deliveredAs a CustomerI would like to be able to notify customer services

  • Speaking The Language Of Your Domain 34

    In order to better understand a feature and its behaviour, scenarios are written to describe the featureunder different use cases. Scenarios start with an initial condition, the Givens. It then contains oneor more events, the Whens, and finally the scenario describes the expected outcomes, the Thens.

    The scenario below shows the behaviour of the feature for a customer who has never claimed foran undelivered order.

    Scenario: Customer making his first claimGiven I have not received my itemsAnd I am a customer that has never notified customer services of an undelivered orderWhen I notify customer servicesThen I should receive a replacement order

    In addition to being a light way of capturing requirements the scenarios provide acceptance criteria,which can be used by developers and testers to determine when a feature is complete and by businessusers to confirm to them that the team understand the feature.

    The next scenario describes the behaviour for a customer that has already made a claim.

    Scenario: Customer making his second claimGiven I have not received my itemsAnd I am a customer that has made a successful claim for a replacement orderWhen I notify customer servicesThen I should be contacted by customer services

    Using this method of capturing requirements removes the ambiguity that traditional requirementsdocumentation can result in whilst also heavily emphasising a focus on the domain language. Thefeatures and scenarios themselves are a product of a collaboration between the development teamand business experts and can help to shape the ubiquitous language.

    3.4 A Language Tied To A Context

    In the same way that we defined the boundary of responsiblity for a subdomain we must also ensurethe ubiquitous language is bound and specific to context within a subdomain. For example termslike customer, order and product will be found in many of the contexts of an e-commerce domain.So its important to be specific in code (using namespaces) and communication about what contextyou are talking about.

    It is also important to be explicit about what context you are using when talking with domainexperts, as terminology can have different meanings in different contexts. As mentioned in theprevious section multiple models will be at play in you domain. It is essential to enforce linguisticboundaries to protect the validity of a domain term.

  • Speaking The Language Of Your Domain 35

    3.5 The Salient Points

    Learn domain terms and concepts, incorporate them into a shared language

    Domains are full of specialist terms and language that describe complex concepts in aclean concise manner

    Implicit ideas in the domain that need to be understood by the team are made explicitand given names that form the shared ubiquitous language

    Care about the conversation Make the implicit explicit Developers should think in domain terns and concepts and not technical terms Avoid the need to translate from business jargon into technical jargon The ubiquitous language should be used in namespaces, class names and methods

    Validate the language

    Domain experts should object to inadequate terms or structure in the language or model Developers should watch for ambiguity or inconsistency Validate assumptions about the ubiquitous language by talking to domain experts Validate out loud and confirm you ubiquitous language with linguistic consistency If a domain expert doesnt say it it shouldnt be in the language

    Capture requirements and language with feature stories and scenarios

    Use domain scenarios to valid the teams understanding of the domain and the sharedlanguage

    If a term in the model no longer makes sense or is not useful then remove it, keep yourlanguage small and focused

    Use the ubiquitous language in specifications, tests and stories

  • 4 Shaping Your Solution SpaceYou have now learnt how to define the subdomains of the problem space. And that many modelsexist in large and complex problem domains. It is vital to protect the integrity of thesemodels andclearly define the boundaries of their responsibility in code. This section of the book introducesthe strategic patterns of Domain-Driven Design that show you how you can protect and integratethe multiple models of an application. Enabling you to take the abstract problem domain and turnit into a concrete technical implementation.

    The diagram below shows the strategic patterns of Domain-Driven Design that will be covered inthis chapter.

    A blueprint of the solution space of Domain-Driven Design.

    4.1 Retaining The Integrity Of Models In Subdomains

    As introduced in the previous sections a model is defined in a context. This should be followedthrough to the implementation in the code otherwise we will find ourselves in a Big Ball of Mud.Take the example of a code model that contains the concept of a product. As discussed this meansmany things to many models in many contexts. If we dont enforce a boundary around the modeland make it specific to a given context we will end up with a mass of sprawling code.

    36

  • Shaping Your Solution Space 37

    It is important when developing the application that you isolate models within subdomains toavoid the blurring of responsibilities which can lead to code that resembles a Big Ball of Mud.

    The Challenges Of Maintaining A Single Model: BlurredResponsibility

    In the following diagram we see the concept of a product implemented within the e-commerceapplication. You can see that there are no explicit boundaries protecting the integrity of theproduct concept within each subdomain. Instead the product concept is being shared betweenall the subdomains and has to contain both the data and behaviour to handle the needs for eachdifferent context. The lack of any defined boundaries will lead the code, and the language, tobecome a mess. The product entity will have many reasons to change as the subdomains evolve,thus breaking the Single Responsibility Principle. In this example the persistence schema will alsobecome unmanageable due to the mess of overlapping concerns.

    A single view of an entity in the domain for all subdomains can quickly become a problem.

  • Shaping Your Solution Space 38

    You can see from the diagram above that the product class looks like it should belong to an enterprisemodel. An enterprise model is typically used to a create a model of the entire problem domain.Enterprise models can quickly become large and unwieldy due to all of the contexts they need toserve, as is shown in the following diagram.

    The product god object.

    This is the manifestation of the Big Ball of Mud pattern as discussed earlier. A change to logic inone of the subdomains will have an undesired knock-on effect to unrelated subdomains dueto the interwoven code and the lack of clearly defined boundaries of responsibility.

    Bounded Contexts: Define A Boundary Of Responsibility AroundA Model

    In order to remove ambiguity we must create explicit boundaries