logo资料库

Domain-Driven Design领域驱动设计.pdf

第1页 / 共320页
第2页 / 共320页
第3页 / 共320页
第4页 / 共320页
第5页 / 共320页
第6页 / 共320页
第7页 / 共320页
第8页 / 共320页
资料共320页,剩余部分请下载后查看
Domain-Driven Design Tackling Complexity in the Heart of Software Eric Evans eric@domainlanguage.com (415) 902-7873 (Draft December 23, 2002) For current draft and other information, see www.domainlanguage.com Copyright © 2002, Eric Evans. All rights reserved.
Table of Contents Preface........................................................................................................................................................5 The Challenge of Complexity...........................................................................................................5 Design vs. Development Process ......................................................................................................6 What Is in This Book ........................................................................................................................7 Who Should Read This Book............................................................................................................8 Crunching Knowledge ..................................................................................................................13 Communication and the Use of Language ..................................................................................22 UBIQUITOUS LANGUAGE............................................................................................................23 Communication Through Diagrams..........................................................................................29 Path to Implementation................................................................................................................31 MODEL-DRIVEN DESIGN............................................................................................................32 HANDS-ON MODELERS ..............................................................................................................41 OBJECT MODEL..........................................................................................................................43 Non-objects in an Object World .....................................................................................................45 Map of High-Level Patterns............................................................................................................48 Isolating the Domain.....................................................................................................................52 LAYERED ARCHITECTURE..........................................................................................................53 SMART UI ANTI-PATTERN .........................................................................................................58 Expressing the Model....................................................................................................................61 ENTITIES (AKA REFERENCE OBJECTS)........................................................................................62 VALUE OBJECTS.........................................................................................................................70 SERVICES ...................................................................................................................................74 Expressive Objects Throughout Their Lifecycle........................................................................78 AGGREGATES.............................................................................................................................79 Designing Objects for Relational Databases .............................................................................86 FACTORIES.................................................................................................................................88 REPOSITORIES ............................................................................................................................96 Chunking the Model ...................................................................................................................104 MODULES (AKA PACKAGES) ....................................................................................................105 Using the Language in an Example: A Cargo Shipping System.............................................108 1. 2. 3. 4. 5. 6. 7. 8. 9. Deep Modeling.............................................................................................................................125 10. Making Implicit Concepts Explicit............................................................................................133 Listening..................................................................................................................................133 Scrutinizing Awkwardness......................................................................................................136 Read the Book.........................................................................................................................140 Try, Try Again ........................................................................................................................141 Expressing Less Obvious Categories of Concepts........................................................................142 Explicit Constraints.................................................................................................................142 Domain Processes ...................................................................................................................144 SPECIFICATION.........................................................................................................................146 11. Supple Design ..............................................................................................................................161 INTENTION REVEALING INTERFACES .......................................................................................163 SIDE-EFFECT-FREE FUNCTIONS ...............................................................................................164 CONCEPTUALLY COHERENT ASSERTIONS ................................................................................168 CONCEPT-CONTOURING GRANULARITY ..................................................................................171 (Draft December 23, 2002) © Eric Evans, 2002 2
CLOSURE OF OPERATIONS........................................................................................................174 Declarative Design ..................................................................................................................177 Where Do You Start......................................................................................................................178 Example Integrating the Patterns: Shares Math ............................................................................178 12. Applying Analysis Patterns........................................................................................................185 13. Relating Design Patterns to the Model......................................................................................186 STRATEGY AKA POLICY ...........................................................................................................187 COMPOSITE ..............................................................................................................................191 Why Not FLYWEIGHT?..................................................................................................................196 14. Designing on an Agile Project....................................................................................................197 Refactoring Toward Deeper Insight..............................................................................................200 15. Maintaining Model Integrity......................................................................................................203 BOUNDED CONTEXT ................................................................................................................206 CONTINUOUS INTEGRATION.....................................................................................................210 CONTEXT MAP.........................................................................................................................212 Relationships Between BOUNDED CONTEXTS...............................................................................218 SHARED KERNEL......................................................................................................................219 CUSTOMER/SUPPLIER DEVELOPMENT TEAMS............................................................................220 CONFORMIST............................................................................................................................223 ANTICORRUPTION LAYER ........................................................................................................225 SEPARATE WAYS .....................................................................................................................229 OPEN HOST SERVICE................................................................................................................231 PUBLISHED LANGUAGE............................................................................................................232 Unifying an Elephant ....................................................................................................................234 Choosing Your Model Context Strategy.......................................................................................236 Transformations ............................................................................................................................240 SHARED KERNEL) .................................................242 Merging CONTEXTS (SEPARATE WAYS CONTINUOUS INTEGRATION).................................244 Merging CONTEXTS (SHARED KERNEL Phasing Out a Legacy System.................................................................................................245 PUBLISHED LANGUAGE .....................................................................246 OPEN HOST SERVICE 16. Distillation....................................................................................................................................247 CORE DOMAIN .........................................................................................................................249 GENERIC SUBDOMAINS ............................................................................................................252 DOMAIN VISION STATEMENT...................................................................................................257 HIGHLIGHTED CORE.................................................................................................................259 COHESIVE MECHANISMS..........................................................................................................262 Distilling to a Declarative Style ..............................................................................................264 SEGREGATED CORE..................................................................................................................265 ABSTRACT CORE......................................................................................................................272 Deep Models Distill ......................................................................................................................273 Choosing Refactoring Targets.......................................................................................................273 17. Large-Scale Structure.................................................................................................................274 EVOLVING ORDER....................................................................................................................277 SYSTEM METAPHOR.................................................................................................................279 RESPONSIBILITY LAYERS .........................................................................................................281 KNOWLEDGE LEVEL ................................................................................................................294 PLUGGABLE COMPONENT FRAMEWORK ..................................................................................299 How Restrictive Should a Structure Be?.......................................................................................302 Refactoring Toward a Fitting Structure ........................................................................................303 18. Game Plans: Putting the Pieces Together.................................................................................305 Bringing Together Large-Scale Structures and BOUNDED CONTEXTS ..........................................305 (Draft December 23, 2002) © Eric Evans, 2002 3
Bringing Together Large-Scale Structures and Distillation ..........................................................308 Assessment First ...........................................................................................................................309 Who Sets the Strategy...................................................................................................................310 Looking Back.........................................................................................................................................315 Looking Forward...................................................................................................................................316 Glossary..................................................................................................................................................318 References ..............................................................................................................................................319 Acknowledgements................................................................................................................................320 (Draft December 23, 2002) © Eric Evans, 2002 4
Preface The Challenge of Complexity Ambitious software projects often fail to meet expectations. Progress bogs down in complexity. The team becomes mired in maintaining and understanding its own analysis and early code when the job is scarcely underway. The common vision is lost, efforts splintered. Eventually, software gets written that seems to meet requirements but doesn’t quite satisfy users. It is seldom recognized that many of these problems stem from a lack of attention to the domain model, or an inadequate connection between the model and implementation. The fate of three actual projects indicates the potential impact of effective use of the domain model. One project started with lofty aspirations to build a global enterprise system. The team did a lot of things right. They had sharp people, good tools, the patience to learn and build quality, and a good understanding of their business. But as months rolled by, they became mired in complexity and lost their cohesive vision of the system. After years of effort, they produced a bloated, slow system with hardly any integration. Another project got out of the gate fast with a useful, simple application, developers flying by the seat of their pants. Expectations for the second version were sky-high, but lacking a domain model, or a shared language of any kind, and saddled with a completely unstructured, disorganized design, they found themselves bogged down and unable to deliver a second version. In contrast, a project no less complex than those two followed up a modest initial success, delivering a simple application, with successive accelerations of development. With each iteration, exciting new options opened for integration and elaboration of functionality. This upward trajectory was directly attributable to a powerful domain model, iteratively improved and expressed in code. As the domain model deepened, the quality of communication improved among developers and between developers and user experts. The design, far from imposing an ever-heavier maintenance burden, became easier to modify and extend. I have participated in several projects like that last one. One of their common features was a rich domain model, evolved through iterations of design, that became a part of the fabric of the project. The purpose of this book is to share techniques and principles that help projects repeat those successes. What Is a “Domain Model”? In software development, a “domain” is really just a topic, the subject matter relevant to the users of a computer program. The program will be designed to manage information in that domain or help a user carry out some task related to that domain. A domain may be part of the real world. The real world activity of placing people on air flights is the domain of an airline reservation system. A domain may be quite abstract. Cash flows are part of the domain of accounting software. A domain usually has nothing to do with software technology, although programming itself is the domain of the integrated development environments programmers use. The domain is what the software is about. To create valuable software, we have to bring to bear a body of knowledge about the domain we’re working in. The “domain model” is a team’s agreed-upon way of structuring that knowledge. The domain model serves to capture knowledge, enhance communication, and provide a direct path to implementation and maintenance of functional software. This is the potential of the domain model, but that potential goes unfulfilled on most projects because team members do not recognize the importance of the domain, or because they do not know how to get the most out of a model. To realize that potential requires sophisticated design skills that are not technology- centered. Most software developers are naturally drawn to technology and other tidy design problems. As a (Draft December 23, 2002) © Eric Evans, 2002 5
result, the very heart of the software goes neglected. We lack even an effective technical language with which to organize and communicate domain design decisions. I have spent the past ten years working on complex systems in several business domains. Some of these projects were very successful; others failed. I’ve tried best practices in design and development process as they have emerged from the leaders in the object-oriented development community, and through my triumphs and mistakes I’ve accumulated insights of my own. This book is a synthesis of those insights and experiences into a coherent set of concepts and practical techniques that make domain design effective in overcoming the problems that confront complex software projects. Through this book, I advocate an approach to software development that puts the domain model at the dynamic center of project activity. I show how to use it to give leverage to application development, increase communication on a development team, and focus attention on the most important parts of the project. With the right practices and skills, you can turn your domain model into a strategic asset, the glue to hold together complex systems, the leverage to produce rich functionality. Domain-driven development is a difficult technical challenge that can pay off big, opening opportunities just at the stage when most software projects begin to ossify into legacy. Beyond that, my hope is that domain-driven design will make software projects more interesting for developers and users alike. Design vs. Development Process Design books. Process books. They seldom even reference each other. Each is a complex topic in its own right. This is a design book. But I believe that these two issues are inextricable if design concepts are to be put into successful practice and not dry up into an academic discussion. When people learn design techniques, they often feel excited by the possibilities, but then the messy realities of a real project descend on them. They don’t see how to fit the new design ideas with the technology they must use. Or they don’t know when to worry about a particular design aspect and when to let go in the interest of time. It is possible to talk with other team members about the application of a design principle in the abstract, but it is more natural to talk about the things we do together. So, while this is a design book, I’m going to barge right across that artificial boundary when I need to. This will help place design in the context of a development process. This book is not specific to a particular methodology, but it is oriented toward the new family of “Agile Development Processes”. In recent years there has been a rebellion in the development process world. A number of “lightweight” or “agile” processes have been put forward in reaction to processes that burden projects with useless, static documents and obsessive upfront planning and design. Instead, the Agile Processes emphasize the ability to cope with change and uncertainty. Extreme Programming (XP), conceived by Kent Beck, Ward Cunningham and others [Beck2000], is the most prominent of the agile processes and the one I have worked with most. To make the discussion concrete, I will use XP throughout the book as the basis for discussion of the interaction of design and process. The principles illustrated should be easily adapted to other Agile Processes. XP is minimalist in artifacts and up-front design, but puts an admirable effort into increasing communication, and increasing the project’s ability to change course rapidly. XP recognizes the importance of design decisions, but strongly resists upfront design. Instead, the idea is to use the “simplest thing that could work” at any stage of a project and then continuously refactor, making many small design improvements, ultimately arriving at a design that fits the customer’s true needs. Extreme Programming is a powerful new approach to organizing development work. It has been a much- needed antidote to some of the excesses of design enthusiasts. Projects have bogged down due to cumbersome, complicated documents that provided little value. They have suffered “analysis paralysis”, so afraid of an imperfect design that they made no progress at all. Something had to change. (Draft December 23, 2002) © Eric Evans, 2002 6
Unfortunately, some of these new process ideas can be easily misinterpreted. Each person has a different definition of “simplest”. I’ve seen continuous refactoring become continuous hacking, when practiced by people without design principles to guide these small redesigns. They end up with a code base hard to understand or change – anathema to XP with its emphasis on agility. While fear of unanticipated requirements often leads to over-engineering, the attempt to avoid over- engineering can develop into another fear: The fear of any deep design thinking at all. In fact, XP works best for developers with a sharp design sense. The XP process assumes that you can improve a design by refactoring, and that you will do this often and rapidly. But design choices make refactoring itself easier or harder. The XP process attempts to increase team communication. But model and design choices clarify or confuse communication. What is needed is an approach to domain modeling and design that pulls its weight. So, while this is primarily a design book, it does not consider “pure” design in a vacuum. Instead, it intertwines design and development practice and illustrates how domain-driven design and agile development reinforce each other. A sophisticated approach to domain modeling within the context of an agile development process will accelerate development. The interrelationship of process with domain development makes this approach more practical than any treatment of design in isolation. While a good process might allow a team with poor design skills to get something done, and while a team with design skill may be wasted and accomplish nothing with a poor process, both will be left in the dust by a team employing a good process and skilled in design. What Is in This Book Although leading software designers have recognized domain modeling and design as critical topics for at least twenty years, little has been written about what needs to be done or how to do it. This book consolidates the best practices of the last decades along with a few thoughts of my own. It organizes these practices and the principles underlying them into a mental framework for making domain-driven design decisions. And it provides a coherent technical vocabulary for discussing domain design. The domain-driven development style has evolved in a small subculture of the object community, and, as a result, many have not been exposed to it. For them, I will describe and justify domain-driven design. There are others who have attempted to use a domain model prominently on a project and were disappointed with the results. Effective use of a domain model is not easy to pull off. Many attempts have failed for lack of a key principle or even some detail of technique. For this group I provide a set of patterns to follow in modeling and design that can get designers through a lot of sticking points. The book is divided into four major sections: Part I: The Role of the Domain Model presents the basic goals of domain-driven development that motivate the practices in later sections. Since there are so many approaches to software development, Part I defines terms, and gives an overview of the implications of placing the domain model in the role of driving communication and design. Part II: The Language of Model-driven Design condenses a core of best practices in object-oriented domain modeling into a set of basic building blocks. The focus of this section is on bridging the gap between models and practical, running software. Using these standard building blocks to assemble a domain model provides a clear path to writing an implementation that expresses the model clearly while providing valuable functionality to the application. Sharing these standard patterns brings order to the design and makes it easy for team members to understand each other’s work. Using standard patterns also establishes a common language, which all team members can use to discuss model and design decisions. Part III: Refactoring Toward Deeper Insight goes beyond the building blocks to the challenge of assembling them into practical models that provide the payoff. Rather than jumping directly into esoteric design principles, this section emphasizes the discovery process. Valuable models do not emerge immediately. They require a deep understanding of the domain. That understanding comes from diving in, implementing an initial design based on a probably naïve model, and then transforming it again and again. (Draft December 23, 2002) © Eric Evans, 2002 7
Each time the team gains insight, the model is transformed to reveal that richer knowledge, and the code is refactored to reflect the deeper model and make it’s potential available to the application. Then, once in a while, this onion pealing leads to an opportunity to break through to a “deep model”, with a rush of profound design changes. Exploration is inherently open-ended, but it does not have to be random. Part III delves into modeling principles that can guide choices along the way, and techniques that help direct the search. Part IV: Strategic Design deals with situations that arise in complex systems, larger organizations, interactions with external systems and legacy systems -- in short, most projects. This section explores a triad of principles that apply to the system as a whole: Bounded Context, Distillation, and Large-Scale Structure. Strategic design decision are made by teams, or even between teams. Strategic design enables the goals of Part I to be realized on a larger scale. Throughout the book, discussions are illustrated with realistic examples, mostly drawn from actual projects, rather than oversimplified “toy” problems. Who Should Read This Book This book is primarily written for intermediate to advanced developers of object-oriented software. Most members of a software project team can benefit from some parts of it. For an intermediate software developer, a reader who already knows something of object-oriented design and may have read one or two software design books, this book will fill in gaps and provide perspective on how object modeling fits into real life on a software project. It can help an intermediate developer jump to a higher level of effectiveness in applying design skill to practical problems of complex domains. An advanced or expert software developer should be interested in the comprehensive framework for dealing with the domain. The systematic approach to design may help them in leading teams down this path. The consistent terminology may help them communicate with peers. In addition to this core readership, the book will be of interest to some analysts and to relatively technical project managers. The connections drawn between model and implementation can point to ways for analysts to make more effective design contributions in the context of an “agile” project. Analysts may also use some of the principles of Strategic Design to better focus and organize their work. Project managers should be interested in the emphasis on making a team more effective and more focused on designing software meaningful to business experts and users. While individual developer who understands domain-driven design will gain valuable design techniques and perspective, the biggest gains should come when a team joins to apply a domain-driven design approach. The team members will share a language that can enrich their communication. They will share a roadmap for moving the domain model to the center of discourse. Such a team will be equipped to develop software that better serves the user, is more natural to understand, and is easier to change and maintain. It should also make business software development work far more interesting, making it easier to attract and retain talented developers. A solid knowledge of object-oriented modeling is necessary to benefit from this book. The examples include UML diagrams and Java code, so the ability to read those languages at a basic level is important, but it is unnecessary to have mastered the details of either UML or Java. Knowledge of Extreme Programming will add perspective to the discussions of development process, but the discussion should be understandable without background knowledge. Readers of various backgrounds may take different paths through the book, shifting emphasis to different points. I recommend all readers to start with the introduction. This book is a narrative, and can be read beginning to end, or from the beginning of any chapter. A skimmer who has some grasp of a topic should be able to pick up the main points by reading headings and bolded text. For reference, all the patterns are summarized in tables in Appendix ##. <> (Draft December 23, 2002) © Eric Evans, 2002 8
分享到:
收藏