Domain-Driven Design at ZendCon 2012

1,372 views

Published on

Domain-driven design is a collaborative process involving both domain experts and software practitioners that attempts to address issues of complexity in software. This process is described in the book Domain-Driven Design (Addison-Wesley 2004) written by Eric Evans. Domain-driven design starts with the assertion that (for almost all software) complexity is in the domain, not in the technology. Accordingly, we must let technology play a supporting role. Domain-driven design attempts to focus on and distill the core domain for a given project.

Philosopher and scientist Alfred Korzybski said, "The map is not the territory." As such, a person practicing domain-driven design does not attempt to model reality. Instead, domain experts and software practitioners use a mental model as a tool for solving problems within a given domain. The domain experts and software practitioners collaborate to explore and develop this model. No software of any reasonable scope has just one model. We will look at the concept of a bounded context within which each model can be isolated and explored. Within a bounded context, collaborators must speak a ubiquitous language in order to reason about and discuss the model.

We will also talk about domain-driven design's building block patterns including entities, value objects, aggregates, repositories, services, and domain events. We will look at domain-driven design practices including supple design, strategic design, and distillation of the core. We will see how test-driven development can be used as a means of exploring the model. Examples in PHP will be provided of the building block patterns as well as other techniques including closure of operations, intention revealing interfaces, side-effect free functions, and assertions.

Published in: Technology
0 Comments
4 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,372
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
30
Comments
0
Likes
4
Embeds 0
No embeds

No notes for slide

Domain-Driven Design at ZendCon 2012

  1. 1. Domain-Driven Design A Collaboration Between Domain Experts and Software Practitioners
  2. 2. do·maindōˈmān n.a sphere of knowledge,influence, or activity "domain." Merriam-Webster.com. 2011. http://www.merriam-webster.com/dictionary/domain (17 October 2011).
  3. 3. The Book http://domaindrivendesign.org/books/evans_2003
  4. 4. Training http://www.domainlanguage.com/
  5. 5. Complexity is in the domain,not the technology
  6. 6. Models are tools used tosolve domain problems
  7. 7. The ModelA model is an abstract set of tools that is used tosolve problems within a domainWhile represented in code, do not think of themodel as just codeDon’t try to model reality
  8. 8. from “The Story of Science: Power, Proof and Passion”, a 2010 BBC documentary
  9. 9. Ames RoomUsed in The Lord Of TheRings: The Fellowship ofthe Ring to make thehobbits appear thecorrect size in relationto GandalfWe are always usingmental models tounderstand the worldaround us—we do notperceive an objectivereality By Alex Valavanis (own work) [public domain], via Wikimedia Commons
  10. 10. "Why I prefer Fahrenheit to Celsius [Fixed]." reddit. 2012.http://www.reddit.com/r/funny/comments/wigk1/why_i_prefer_fahrenheit_to_celsius_fixed/ (16 September 2012).
  11. 11. “The map is not the territory.”—Alfred Korzybski
  12. 12. This is not a pipe.Magritte, René. The Treachery of Images (La trahision des images). 1929. Oil on canvas. Los Angeles County Museum of Art, Los Angeles, California.
  13. 13. "Everything simple is false. Everythingwhich is complex is unusable."—Paul Valéry
  14. 14. Collaboratively explore the modelwith both domain experts andsoftware practitioners
  15. 15. Case Study:Three-Dimensional Animation
  16. 16. Software Practioner:Edwin CatmullStudied physics and computer scienceMade many notable computer graphics discoveriesEventually moved from two-dimensional tothree-dimensional animationHired by Lucasfilm to bring his expertise to theentertainment field
  17. 17. Domain Expert:John LasseterStudied animation and taught by veteran animators from DisneyRealized early-on the potential for computer generated imageryWorked at, but eventually fired from, DisneyHired by Edwin Catmull at Lucasfilm as an “Interface Designer”because Catmull’s job didn’t include hiring animators[1] [2] 1. Buckley, A. M. "Chapter 3: Art Meets Science." Pixar: The Company and Its Founders. Edina, MN: ABDO, 2011. 27. Print. 2. BSD Daemon Copyright 1988 by Marshall Kirk McKusick. All Rights Reserved. Drawn by John Lasseter.
  18. 18. “Throughout the process, Lasseterworked side-by-side with the computerscientists. Lasseter’s requests pushedthem to develop new tools, and theirfeedback helped him learn the digitalanimation process.”[1] 1. Buckley, A. M. "Chapter 3: Art Meets Science." Pixar: The Company and Its Founders. Edina, MN: ABDO, 2011. 30. Print.
  19. 19. Identify your core domain
  20. 20. Core DomainIdentify your core domainDistill your core domainFocus your resources on the core domain
  21. 21. Distillation
  22. 22. Types of DomainsA model may represent: • your core domain • a supporting domain • a generic subdomainFocus your modeling efforts on the core domainConsider outsourcing work on supporting domainsConsider off-the-shelf software for generic subdomains
  23. 23. Identifying the Core DomainAsk organizational leaders and domain experts: • What keeps you awake at night? • What makes your system worth writing? • Why not buy it off the shelf? • Why not outsource it?
  24. 24. There are always multiple models
  25. 25. Bounded ContextDelineates the applicability of a particular modelBounded contexts allow each model to be explored in isolationClearly define: • Who is responsible for each bounded context • To which parts of the application is the bounded context applicable • What manifestations the bounded context will take (code, database schemas, etc.)
  26. 26. Ubiquitous LanguageSpeak a ubiquitous language within a bounded contextTerms must be clearly defined, unambiguous, and consistentCritically important when communicating betweendomain experts and software practitionersThe ubiquitous language will (and must) evolve as a progressivelyricher understanding of the domain and the model are achievedIf the ubiquitous language cannot be used to clearly expresscomplex ideas, then you have more work to do!
  27. 27. Strategic Design
  28. 28. Context MapDraw a context map of the current bounded contextsMap what actually exists—not what you wish existed!Identify relationships between contexts
  29. 29. Relationship Patterns customer/ anticorruption partnership supplier layershared kernel big ball of separate ways mud open host conformist published service language
  30. 30. Building Blocks
  31. 31. EntityDefined by a thread of continuity and identityOnly responsibilities should be around identity and life cycleMay be composed of other entities and/or value objects
  32. 32. Value ObjectDefined by its encapsulated attributesTreat value objects as immutableDelegate business logic to value objects
  33. 33. AggregateA group of related entities and value objectsUseful when defining transaction, distribution,and concurrency boundariesA bounded context will have multiple aggregates
  34. 34. Aggregate RootDesignate one entity as the aggregate rootAllow external references to only the aggregate rootPersist the aggregate root, along with its object graph
  35. 35. RepositoryDelegate persistence of an aggregate to a repositoryA repository should behave as if it were an in-memory data storeUse an in-memory strategy for testsIf using an object-relational mapper (ORM):Database -> ORM -> Repository
  36. 36. ServiceA place for operations that aren’t naturally part ofany domain objectLike value objects, services should be treated as immutableOperations on services are stateless
  37. 37. Model Exploration
  38. 38. Ubiquitous Language
  39. 39. Election EventA set of Districts voting on a set of Ballot Items during the samegeneral period of time. Examples of Election Events includeprimaries, general elections, and town meeting days.
  40. 40. Ballot ItemEither an Election or a Referendum as presented on a ballot.
  41. 41. ElectionA formal decision-making process by which a population choosesone or more Candidates to hold public office for a given District.Election results may be tabulated based on Polling Place, Ward,Municipality, or District. The winner or winners of an Election maybe determined by Plurality and/or a Winning Threshold.
  42. 42. DistrictA distinct territorial subdivision for holding separate Elections orReferendums. A District may be a Municipality or a Ward, but thisis not always true. Districts are periodically redistricted, but areimmutable during a given Election Event. Districts can containsub-Districts (i.e. Polling Places, Wards, Municipalities, or otherDistricts). A District’s sub-Districts may be different for differentBallot Items.
  43. 43. MunicipalityA District that can be a city, town, village, or other localgovernment unit.
  44. 44. WardAn electoral District. Some Municipalities are comprised ofmultiple Wards, some are not. In Vermont, only Burlington isbroken down by Ward. Note that for legislative Districts, onlyparts of some Wards vote at a Polling Place. For example, theMunicipality of Burlington’s Ward 2 is broken into two or threelegislative house Districts.
  45. 45. CandidateA person running for elected office. Write-ins areconsidered Candidates.
  46. 46. Winning ThresholdA method of determining the winner of an Election, or the passingof a Referendum, based on a minimum percentage (sometimesplus one) of the total number of votes. This would sometimes becombined with Plurality. For example, if an Election has a WinningThreshold of 40% and two Candidates manage to both exceed40%, then Plurality may be used to decide the winner. Someexamples of where Winning Threshold is used include: • Burlington Mayor: 40% • Revenue Bonds: 50%+1 • GO Bonds: 66%
  47. 47. Scenario
  48. 48. Election for BurlingtonCity CouncilorThe Town Meeting Day 2011 Election Event is under way. Ward 3in the Municipality of Burlington is holding an Election for CityCouncilor. This Election has three Candidates. It is 8:30pm andWard 3 has indicated the following results: • Vince Brennan (P) has 354 votes (60.2%) • Lynn Mesick (D) has 171 votes (29.1%) • Ron Ruloff (I) has 63 votes (10.7%)This Election has a Winning Threshold of 40%, so Candidate VinceBrennan (P) appears to be the winner.
  49. 49. Proposed Model
  50. 50. Warning: This proposed model isintentionally flawed in order todemonstrate opportunities forfurther refinement.
  51. 51. Election Aggregate http://yuml.me/b3094ce6
  52. 52. Election Entity(Aggregate Root)class Election implements BallotItem{ public function __construct($id) { } public function setElectionEvent(ElectionEvent $event) { } public function setDistrict(District $district) { } public function addCandidate(Candidate $candidate) { } /** * @return Candidate[] */ public function getCandidates() { }}
  53. 53. Candidate Entityclass Candidate{ public function __construct($id, Election $election) { } public function setVotes($count) { } public function getFractionOfVotes() { $totalVotes = 0; /* @var $candidate Candidate */ foreach ($this->election->getCandidates() as $candidate) { $totalVotes += $candidate->votes; } return round($this->votes / $totalVotes, 3); }
  54. 54. Winning Policy Value Objectinterface WinningPolicy{ /** * @return Candidate[] */ public function determineWinners();}
  55. 55. Winning ThresholdValue Objectclass WinningThreshold implements WinningPolicy{ public function __construct($minimumPercentage, Election $election) { } /** * @return Candidate[] */ public function determineWinners() { $winners = array(); /* @var $candidate Candidate */ foreach ($this->election->getCandidates() as $candidate) { if ($candidate->getFractionOfVotes() > $this->minimumPercentage) { $winners[] = $candidate; } } return $winners; }
  56. 56. Code Probe
  57. 57. Use concrete scenarios in discussionswith domain experts and in tests
  58. 58. Election Scenarioas Test// The Town Meeting Day 2011 Election Event is under way.$townMeetingDay2011 = new ElectionEvent(Town Meeting Day 2011);// Ward 3 in the Municipality of Burlington…$ward3 = new Ward(Ward 3);$burlington = new Municipality(Burlington);$ward3->setParentDistrict($burlington);// …is holding an Election for City Councilor.$cityCouncilor = new Election(City Councilor);$cityCouncilor->setElectionEvent($townMeetingDay2011);$cityCouncilor->setDistrict($ward3);
  59. 59. Election Scenarioas Test (cont’d)// This Election has three Candidates.$vinceBrennan = new Candidate( Vince Brennan (P), $cityCouncilor);$lynnMesick = new Candidate( Lynn Mesick (D), $cityCouncilor);$ronRuloff = new Candidate( Ron Ruloff (I), $cityCouncilor);
  60. 60. Election Scenarioas Test (cont’d)// It is 8:30pm and Ward 3 has indicated the following results:$vinceBrennan->setVotes(354);$lynnMesick->setVotes(171);$ronRuloff->setVotes(63);$this->assertEquals(.602, $vinceBrennan->getFractionOfVotes());$this->assertEquals(.291, $lynnMesick->getFractionOfVotes());$this->assertEquals(.107, $ronRuloff->getFractionOfVotes());// This Election has a Winning Threshold of 40%…$winningPolicy = new WinningThreshold(.40, $cityCouncilor);// …so Candidate Vince Brennan (P) appears to be the winner.$winners = $winningPolicy->determineWinners();$this->assertContains($vinceBrennan, $winners);$this->assertNotContains($lynnMesick, $winners);$this->assertNotContains($ronRuloff, $winners);
  61. 61. Challenge the Model
  62. 62. Challenge ModelWith More ScenariosQuestions to ask a domain expert: • What if two candidates reach the 40% winning threshold? • What if a candidate participates in two elections? • What about a municipality without wards? • How about an election that is won by plurality? • What’s different about referendums? • What changes when it’s a general election?
  63. 63. Supple Design
  64. 64. Closure of OperationsHave a method on a value object that returns an instanceof the same type of value objectAny method arguments should also be the same type asthe value objectExample: 2 + 3 = 5 • “2” is a value object of type integer • integer has an add method • add method accepts an argument of type integer • add method returns an integer • integers are closed under the operation of addition
  65. 65. Totaling Ballot Item Resultsclass BallotItemResult{ /** * @param BallotItemResult[] $results * @return BallotItemResult */ public function total(array $results) { /* @var $options BallotItemOption[] */ $options = array(); $votes = 0; /* @var $result BallotItemResult */ foreach ($results as $result) { $options[] = $result->option; $votes += $result->votes; } $option = new CompositeBallotItemOption($options); return new BallotItemResult($option, $votes); }}
  66. 66. Other TechniquesIntention-revealing interfaces • Is the method’s intention clear based on its interface?Side-effect free functions • Does the method return a value and modify state? • Does the method interact with other objects and methods?Assertions • What are the method’s preconditions? • What are the method’s postconditions?
  67. 67. Is the intention clear?class BallotItemResult{ /** * Gets the fraction of votes for this Ballot Item Result * relative to the total number of votes for all Ballot * Item Results within the context Ballot Item * * @return float */ public function getFractionOfVotes() { }}
  68. 68. Side-Effect Freeclass WinningThreshold implements WinningPolicy{ /** * @return Candidate[] */ public function determineWinners() { $winners = array(); /* @var $candidate Candidate */ foreach ($this->election->getCandidates() as $candidate) { if ($candidate->getFractionOfVotes() > $this->minimumPercentage) { $winners[] = $candidate; } } return $winners; }}
  69. 69. Assert Preconditionsand Postconditionspublic function determineWinners(){ assert($this->minimumPercentage >= 0); assert($this->minimumPercentage <= 1); $winners = array(); /* @var $candidate Candidate */ foreach ($this->election->getCandidates() as $candidate) { $fraction = $candidate->getFractionOfVotes(); if ($fraction > $this->minimumPercentage) { $winners[] = $candidate; } } assert(count($winners) <= count($this->election->getCandidates())); return $winners;}
  70. 70. Advanced Topics
  71. 71. Event Sourcing[1] 1. http://martinfowler.com/eaaDev/EventSourcing.html
  72. 72. Domain EventSomething important that happens within the domainthat may lead to a state change in a domain objectDomain events can trigger other domain events (e.g.three strikes triggers an out)Domain events are immutable
  73. 73. Event LogCurrent state can be computed by reading the event logCurrent state may be cached, if necessary for performanceCan also serve as an audit log
  74. 74. Command-Query ResponsibilitySegregation (CQRS)
  75. 75. Write Model/Read ModelDefine one model for writing data (commands)Define another model for reading data (queries)Both models operate on the same aggregate
  76. 76. http://oreilly.com/catalog/9781449303129/ http://oreilly.com/catalog/9781449303433/
  77. 77. Thank You @BradleyHolt http://bradley-holt.com https://joind.in/7025Copyright © 2011-2012 Bradley Holt. All rights reserved.

×