Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

Like this presentation? Why not share!

Domain-Driven Design



Domain-Driven Design

Domain-Driven Design



Total Views
Views on SlideShare
Embed Views



4 Embeds 134

http://dotnetug-lviv.blogspot.com 119
http://www.linkedin.com 10
http://dotnetug-lviv.blogspot.co.uk 4
https://www.linkedin.com 1



Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
Post Comment
Edit your comment
  • “Domain-Driven Design Quickly”:“Consider car manufacturing as a metaphor. The workersinvolved in auto manufacturing may specialize in producingparts of the car, but in doing so they often have a limited view ofthe entire car manufacturing process. They start viewing the caras a huge collection of parts which need to fit together, but a caris much more than that. A good car starts with a vision. It startswith carefully written specifications. And it continues withdesign. Lots and lots of design. Months, maybe years of timespent on design, changing and refining it until it reachesperfection, until it reflects the original vision. The processingdesign is not all on paper. Much of it includes doing models ofthe car, and testing them under certain conditions to see if theywork. The design is modified based on the testing results. Thecar is sent to production eventually, and the parts are created andassembled together.Software development is similar. We can’t just sit down andtype code. We can do that, and it works well for trivial cases .But we cannot create complex software like that.”Mention about the Waterfall and the Agile methodologies and how DDD can illuminate weak areas of XP.
  • Problem is: - you want to develop application and you dive into complexity - core problem of the whole is the Domain - For example "Banking" - Developers doesn't like to learn much about the bussiness... Maybe to give programming tools to the bank people? Developer stand with bussines guy near whiteboard.How this process looks like? What is the solution? Where to start?
  • Domain-driven design (DDD) is an approach to the design of software, based on the two premises [1]:that complex domain designs should be based on a model, andthat for most software projects, the primary focus should be on the domain and domain logic (as opposed to the particular technology used to implement the system).Model in the Domain Driven DesignModel and the design shape each otherModel is language for team membersModel is knowledgeIngredients of Effective ModelingBinding the model and implementationCultivating a language based on the modelDeveloping a knowledge-rich modelDistilling the modelBrainstorming and experimenting
  • Talk about need for some common language.Mention about the jargon of experts and develpers and that misunderstanding leads to project failure.A core principle of domain-driven design is to use a language based on the model.
  • A 110% rule.
  • A 110% rule.
  • A 110% rule.
  • “Remember, one of the consequences of this pattern is that you can't migrate to another design approach except by replacing entire applications.”The bottom line is this: If the architecture isolates the domain-related code in a way that allows a cohesive domain design loosely coupled to the rest of the system, then that architecture can probably support domain-driven design.
  • User Interface(PresentationLayer)Responsible for presenting information to the user andinterpreting user commands.ApplicationLayerThis is a thin layer which coordinates the applicationactivity. It does not contain business logic. It does nothold the state of the business objects, but it can holdthe state of an application task progress.Domain Layer This layer contains information about the domain. Thisis the heart of the business software. The state ofbusiness objects is held here. Persistence of thebusiness objects and possibly their state is delegated tothe infrastructure layer.InfrastructureLayerThis layer acts as a supporting library for all the otherlayers. It provides communication between layers,implements persistence for business objects, containssupporting libraries for the user interface layer, etc.For example, a typical, the interaction of the application, domainand infrastructure could look like this. The user wants to book aflights route, and asks an application service in the applicationlayer to do so. The application tier fetches the relevant domainobjects from the infrastructure and invokes relevant methods onthem, e g to check security margins to other already bookedflights. Once the domain objects have made all checks andupdated their status to “decided”, the application service persiststhe objects to the infrastructure.
  • Talk about the diagram and a bit about the relations… Mention about each of the blocks:AssociationsEntitiesValue ObjectsServicesModulesAggregatesFactoriesRepositories
  • EntitiesIdentityCreation of unique identityIf we were to implement the concept of a Person using asoftware program, we would probably create a Person class witha series of attributes: name, date of birth, place of birth, etc.It is important for two objects with different identities to be to beeasily distinguished by the system, and two objects with thesame identity to be considered the same by the system.
  • For fun:“Let’s consider a drawing application. The user is presented acanvas and he can draw any points and lines of any thickness,style and color. It is useful to create a class of object namedPoint, and the program could create an instance of this class foreach point on the canvas. Such a point would contain twoattributes associated to screen or canvas coordinates. Is itnecessary to consider each point as having an identity? Does ithave continuity? It seems that the only thing that matters forsuch an object is its coordinates.”An object that is used to describe certain aspects of a domain, and which does not have identity, is named Value Object.It is highly recommended that value objects be immutable.Immutability. Example is flight code.One golden rule is: if Value Objects are shareable, they shouldbe immutable.
  • Is "Address" a VALUE OBJECT? Who's Asking?In software for a mail-order company, an address is needed to confirm the credit card,and to address the parcel. But if a roommate also orders from the same company, it isnot important to realize they are in the same location. Address is a VALUE OBJECT.In software for the postal service, intended to organize delivery routes, the countrycould be formed into a hierarchy of regions, cities, postal zones, and blocks, terminatingin individual addresses. These address objects would derive their zip code from theirparent in the hierarchy, and if the postal service decided to reassign postal zones, allthe addresses within would go along for the ride. Here, Address is an ENTITY.In software for an electric utility company, an address corresponds to a destination forthe company's lines and service. If roommates each called to order electrical service,the company would need to realize it. Address is an ENTITY. Alternatively, the modelcould associate utility service with a "dwelling," an ENTITY with an attribute of address.Then Address would be a VALUE OBJECT.
  • Such an object does nothave an internal state, and its purpose is to simply providefunctionality for the domain. The assistance provided by aService can be a significant one, and a Service can group relatedfunctionality which serves the Entities and the Value Objects. Itis much better to declare the Service explicitly, because it createsa clear distinction in the domain, it encapsulates a concept. Itcreates confusion to incorporate such functionality in an Entityor Value Object because it won’t be clear what those objectsstand for.When a significant process or transformation in the domain is not a natural responsibility of an ENTITY or VALUE OBJECT, add an operation to the model as a standalone interface declared as a SERVICE. Define the interface in terms of the language of the model and make sure the operation name is part of the UBIQUITOUS LANGUAGE. Make the SERVICE stateless.
  • For a large and complex application, the model tends to growbigger and bigger. The model reaches a point where it is hard totalk about as a whole, and understanding the relationships andinteractions between different parts becomes difficult. For thatreason, it is necessary to organize the model into modules.Modules are used as a method of organizing related conceptsand tasks in order to reduce complexity.It iswidely accepted that software code should have a high level ofcohesion and a low level of coupling. While cohesion starts atthe class and method level, it can be applied at module level.
  • Domain objects go through a set of states during theirlife time. They are created, placed in memory and used incomputations, and they are destroyed. In some cases they aresaved in permanent locations, like a database, where they can beretrieved from some time later, or they can be archived.Aggregate is a domainpattern used to define object ownership and boundaries.Factories and Repositories are two design patterns which help usdeal with object creation and storage.Therefore, use Aggregates. An Aggregate is a group ofassociated objects which are considered as one unit with regardto data changes. The Aggregate is demarcated by a boundarywhich separates the objects inside from those outside. EachAggregate has one root. The root is an Entity, and it is the onlyobject accessible from outside. The root can hold references toany of the aggregate objects, and the other objects can holdreferences to each other, but an outside object can holdreferences only to the root object. If there are other Entitiesinside the boundary, the identity of those entities is local,making sense only inside the aggregate.If objects of an Aggregate are stored in a database, only the rootshould be obtainable through queries. The other objects shouldbe obtained through traversal associations.Objects inside an Aggregate should be allowed to holdreferences to roots of other Aggregates.The root Entity has global identity, and is responsible formaintaining the invariants. Internal Entities have local identity.
  • Creation of an object can be a major operation in itself, but complex assemblyoperations do not fit the responsibility of the created objects. Combining suchresponsibilities can produce ungainly designs that are hard to understand. Making theclient direct construction muddies the design of the client, breaches encapsulation ofthe assembled object or AGGREGATE, and overly couples the client to the implementationof the created object.Shift the responsibility for creating instances of complex objects and AGGREGATES to aseparate object, which may itself have no responsibility in the domain model but is stillpart of the domain design. Provide an interface that encapsulates all complex assemblyand that does not require the client to reference the concrete classes of the objectsbeing instantiated. Create entire AGGREGATES as a piece, enforcing their invariants.There are many ways to design FACTORIES. Several special-purpose creation patterns— FACTORYMETHOD, ABSTRACT FACTORY, and BUILDER—were thoroughly treated in Gamma et al. 1995.The two basic requirements for any good FACTORY are:1. Each creation method is atomic and enforces all invariants of the created object orAGGREGATE. A FACTORY should only be able to produce an object in a consistent state. For anENTITY, this means the creation of the entire AGGREGATE, with all invariants satisfied, butprobably with optional elements still to be added. For an immutable VALUE OBJECT, this meansthat all attributes are initialized to their correct final state. If the interface makes it possibleto request an object that can't be created correctly, then an exception should be raised orsome other mechanism should be invoked that will ensure that no improper return value ispossible.2. The FACTORY should be abstracted to the type desired, rather than the concrete class(es)created. The sophisticated FACTORY patterns in Gamma et al. 1995 help with this.Reconstituting Stored ObjectsAn ENTITY FACTORY used for reconstitution does not assign a new tracking ID.A FACTORY reconstituting an object will handle violation of an invariant differently.
  • To do anything with an object, you have to hold a reference to it. How do you get that reference?Creating and/or traversing is not the best way – you need Repository!Adding traversing code to your infrastructure kills model.Important: Any object internal to an AGGREGATE is prohibited from access except by traversal from the root.Problem: “” A subset of persistent objects must be globally accessible through a search based onobject attributes. Such access is needed for the roots of AGGREGATES that are notconvenient to reach by traversal. They are usually ENTITIES, sometimes VALUE OBJECTSwith complex internal structure, and sometimes enumerated VALUES. Providing accessto other objects muddies important distinctions. Free database queries can actuallybreach the encapsulation of domain objects and AGGREGATES. Exposure of technicalinfrastructure and database access mechanisms complicates the client and obscuresthe MODEL-DRIVEN DESIGN.For each type of object that needs global access, create an object that can provide theillusion of an in-memory collection of all objects of that type. Set up access through awell-known global interface. Provide methods to add and remove objects, which willencapsulate the actual insertion or removal of data in the data store. Provide methodsthat select objects based on some criteria and return fully instantiated objects orcollections of objects whose attribute values meet the criteria, thereby encapsulatingthe actual storage and query technology. Provide REPOSITORIES only for AGGREGATE rootsthat actually need direct access. Keep the client focused on the model, delegating allobject storage and access to the REPOSITORIES.REPOSITORIES have many advantages, including the following:* They present clients with a simple model for obtaining persistent objects and managing theirlife cycle.* They decouple application and domain design from persistence technology, multiple databasestrategies, or even multiple data sources.* They communicate design decisions about object access.* They allow easy substitution of a dummy implementation, for use in testing (typically usingan in-memory collection).The REPOSITORY encapsulates the underlying data store.
  • Relationship with FactoriesRepository uses Factory to reconsistuteUser Uses Repostitory to save new one, but factory creates that objectRepository and Relational database
  • “Refactoring is the process of redesigning the codeto make it better without changing application behavior.Refactoring is usually done in small, controllable steps, withgreat care so we don’t break functionality or introduce somebugs. After all, the purpose of refactoring is to make the codebetter not worse. Automated tests are of great help to ensure thatwe haven’t broken anything.”Refactoring toward deeper insight is not the same kind as technical refactoring. We could not have patterns of doing it.“One of the first things we are taught about modeling is to readthe business specifications and look for nouns and verbs. Thenouns are converted to classes, while the verbs become methods.This is a simplification, and will lead to a shallow model.”“Sophisticated domain models are seldom developed exceptthrough an iterative process of refactoring, including closeinvolvement of the domain experts with developers interested inlearning about the domain.”Bring Key Concepts Into Light“Refactoring is done in small steps. The result is also a series ofsmall improvements. There are times when lots of small changesadd very little value to the design, and there are times when fewchanges make a lot of difference. It’s a Breakthrough.”
  • ConstraintFor example of Constraint talk about Placing the Constraint into a separate method has the advantage of making it explicit.Process“Processes are usually expressed in code with procedures. Wewon’t use a procedural approach, since we are using an objectorientedlanguage, so we need to choose an object for theprocess, and add a behavior to it. The best way to implementprocesses is to use a Service. If there are different ways to carryout the process, then we can encapsulate the algorithm in anobject and use a Strategy. Not all processes should be madeexplicit. If the Ubiquitous Language specifically mentions therespective process, then it is time for an explicit implementation.”Specification (Rules by Jimmy Nilsson)“Simply said, a Specification is used to test an object to see if it satisfies a certain criteria.”Talk about Rules…..“The Specification is used to test objects to see if they fulfillsome need, or if they are ready for some purpose. It can also beused to select a certain object from a collection, or as a conditionduring the creation of an object.”
  • Talk about the enterprise projects and contribution of many teams work into it and intersection with domain.Created module by one team and change to it by developer from other breaks the model.“The first requirement of a model is to be consistent, with invariable terms and no contradictions.”
  • “Each model has a context. When we deal with a single model,the context is implicit. We do not need to define it. When wecreate an application which is supposed to interact with othersoftware, for example a legacy application, it is clear that thenew application has its own model and context, and they areseparated from the legacy model and its context. They cannot becombined, mixed, or confused. But when we work on a largeenterprise application, we need to define the context for eachmodel we create.”A model should be small enough to be assigned to one team.Continuous IntegrationContinuous Integration is based on integration of concepts in themodel, then finding its way into the implementation where it istested. Any inconsistency of the model can be spotted in theimplementation. Continuous Integration applies to a BoundedContext, it is not used to deal with relationships betweenneighboring Contexts.Context MapA Context Map is a document which outlines thedifferent Bounded Contexts and the relationships between them.A Context Map can be a diagram like the one below, or it can beany written document. The level of detail may vary. What it isimportant is that everyone working on the project shares andunderstands it.
  • Shared KernelThe purpose of the Shared Kernel is to reduce duplication, but still keep two separate contexts.Designate some subset of the domain model that thetwo teams agree to share. Of course this includes, along with thissubset of the model, the subset of code or of the database designassociated with that part of the model. This explicitly sharedstuff has special status, and shouldn’t be changed withoutconsultation with the other team.Customer-Supplier (for example reporting to some functionality and the functionality itself)There are times when two subsystems have a specialrelationship: one depends a lot on the other. The contexts inwhich those two subsystems exist are different, and theprocessing result of one system is fed into the other. They do nothave a Shared Kernel, because it may not be conceptuallycorrect to have one, or it may not even be technically possiblefor the two subsystems to share common code. The twosubsystems are in a Customer-Supplier relationship.Addition to example:“The reporting team should play the customer role, while the eshopping team should play the supplier role.”ConformistThis is much like the Shared Kernel, but there is animportant difference. The customer team cannot make changesto the kernel. They can only use it as part of their model, andthey can build on the existing code provided.Anticorruption LayerThis deals with legacy systems.Almost about the Homecare Link project: “Another method of interaction is the database. Theexternal system works with data stored in a database. The clientsystem is supposed to access the same database. In both caseswe are dealing with primitive data being transferred between thesystems. While this seems to be fairly simple, the truth is thatprimitive data does not contain any information about themodels. We cannot take data from a database and treat it all asprimitive data. There is a lot of semantics hidden behind thedata. A relational database contains primitive data related toother primitive data creating a web of relationships. The datasemantics is very important, and needs to be considered. Theclient application can’t access the database and write to itwithout understanding the meaning of the data used. We see thatparts of the external model are reflected in the database, andmake their way into our model.”We should build an Anticorruption Layer which stands between our client model and the external one.This layer works as a two way translator between two domains and languages.Separate WayCould be used when the CI makes too much difficalties.The Separate Ways pattern addresses the case when anenterprise application can be made up of several smallerapplications which have little or nothing in common from amodeling perspective. There is a single set of requirements, andfrom the user’s perspective this is one application, but from amodeling and design point of view it may done using separatemodels with distinct implementations.Open Host ServiceThe solution is to see the external subsystem as a provider ofservices. If we can wrap a set of Services around it, then all theother subsystems will access these Services, and we won’t needany translation layer. The difficulty is that each subsystem mayneed to interact in a specific way with the external subsystem,and to create a coherent set of Services may be problematic.
  • Invisibility of saving – key concept for Infrastructure
  • Where to save: Memory, File system, Object db, Relational dbData mapper or ORMORM Classification:InheritanceStarting pointQuering languageGood support for Database operations: aggregate, ordering, grouping, etcOther Classification:Differend RDMSCachingTransactionsOpen code?ORMIdentity MapUnit Of WorkLazy load
  • NHibernate provides all the features required to quickly build an advanced persistence layer in code.v
  • Advantages for designMore client controlMore Interfaces and FabricsMore concreteLow couplingOther advantagesAnother version of APILong term supportDocumentationLike smart compilerDisadvantagesUI & Database testingYou feel too much safePossilitity to lose whole visibilityMore code to maintainFake, Stub, Mock – mention about these also!SOA (Service-oriented architecture)Generally speaking, SOA is a flexible set of design principles used during the phases of systems development and integration.AOP (Aspect-oriented programming)In computing, aspect-oriented programming (AOP) is a programming paradigm in which secondary or supporting functions are isolated from the main program's business logic. It aims to increase modularity by allowing the separation of cross-cutting concerns, forming a basis for aspect-oriented software development.
  • Very recently, web development platforms have begun to matureenough to make web development productive enough for DDD,and there are a number of positive trends. For example, SOA,when it is used well, provides us a very useful way of isolatingthe domain.

Domain-Driven Design Domain-Driven Design Presentation Transcript

  • Domain-Driven Design
  • Yeah… I’ve read them all…
  • Where is a car on the left or on the right?
    We cannot just type the code… we need to have a vision…
  • What is DDD?
    Ubiquitous Language
    New architecture
    Building blocks of Domain-Driven Design
    Refactoring Toward Deeper Insight
    Preserving Model Integrity
    Patterns and practices with Domain-Driven Design
  • Domain-Driven Design
    DDD is an approach to the design
    Model is the heart of the DDD
    Model and the design shape each other
    Model is language for team members
    Model is knowledge
    Your Focus is on heart
    Need for some common language
    Language and model
    How does it look?
    Speech (a common)
    Writing (not long documents)
    UML (not cumbersome)
  • Voyage Cargo
  • Voyage Cargo
  • Voyage Cargo
  • New Architecture
    How will you build your architecture with DDD?
  • Advantages
    Bottom line
    The Smart UI “Anti-Pattern”
  • Layered architecture
  • Building blocks of DDD
  • Entities
  • Almost like a Entity but without Identity
    Value Objects
  • Address for Patient could be Value Object
    …because it doesn’t play huge role in his treating
    Address in postal service is Entity
    …because it is critical to know where to deliver correspondence
    Value Object or Entity? Who is asking?
  • Three characteristics for a good Service:
    Operation not natural to an Entity or Value Object
    Defined interface
    Operation is stateless
  • When you place some classes together in a Module, you are telling the next developer who looks at your design to think about them together.
  • Aggregate
    Car is Aggregate to Tire
    Root Entity
  • Responsibility of Factory
    Requirements to Factory
    Abstracted to the type desired
    Reconstituting Stored Objects
  • Repositories
    Querying a Repository
    Implementation of Repository
    Abstract the type.
    Take advantage of the decoupling from the client.
    Leave transaction control to the client.
  • Factories and Repositories
  • Refactoring Toward Deeper Insight
    Continuous Refactoring
    Refactoring toward deeper insight is not the same kind as technical refactoring. We could not have patterns of doing it.
    Bring Key Concepts into Light
    There are times when lots of small changes add very little value to the design, and here are times when few changes make a lot of difference.
  • Constraint
    Bring Concepts Into Light
    Customer customer = customerRepository.findCustomer(customerIdentiy);
    Specification customerEligibleForRefund = newSpecification(
            newCustomerHasNoOutstandingBalances() );
    if (customerEligibleForRefund.isSatisfiedBy(customer))
  • Preserving Model Integrity
  • Each model has a context
    When we deal with legacy we create new model and new context
    A model should be small enough to be assigned to one team
    Continuous Integration
    Context Map (document)
    Bounded Context
  • Interaction between different contexts
    Shared Kernel
    Anticorruption Layer
    Separate Ways
    Open Host Service
  • Prepare your Infrastructure
    Persistence Ignorance
  • How do we classify ORMs?
    How do they resolve issues?
    Requirements to them
    Identity Map
    Unit Of Work
    Lazy load
    Infrastructure: ORM
  • NHibernate provides all the features required to quickly build an advanced persistence layer in code.
    You work only with objects, so you understand Business model.
  • Patterns and practices with Domain-Driven Design
    Agile techniques are good for DDD
    …such as TDD…
    New way of proecting
    …such as SOA, AOP, IoC…
  • My article on DDD:
    DDD community:
    DDD books:
    Domain-Driven Design: Tackling Complexity in the Heart of Software
    Applying Domain-Driven Design and Patterns
    Domain-Driven Design Quickly
  • Read blog! Follow me! Visit Lviv UG!