420 likes | 749 Views
Domain Driven Design. Ryan Riley Catapult Systems, Inc. Domain Driven Design. When you remember that DDD is really just “OO software done right”, it becomes more obvious that strong OO experience will also stand you in good stead when approaching DDD.
E N D
Domain Driven Design Ryan Riley Catapult Systems, Inc.
Domain Driven Design When you remember that DDD is really just “OO software done right”, it becomes more obvious that strong OO experience will also stand you in good stead when approaching DDD. - Jak Charlton, Domain Driven Design Step-by-Step
Domain Driven Design Agenda • Patterns • Entities • Value Objects • Aggregate Roots • Object Creation Patterns • Repository • Specification • Domain Services • Modules • Domain Events • State Machines • Conceptual • Ubiquitous Language • Bounded Contexts • Persistence Ignorance • Refactoring • Command Query Separation • When to use DDD
Domain Driven Design Conceptual Elements (or what it means)
Domain Driven Design Domain Driven Design • Domain First • Focus on the Object Model • Focus on Object-Oriented Design • Works well with other *DD methods to: • Reduce Complexity • Increase Maintainability
Domain Driven Design Ubiquitous Language • Model the language used by your domain experts • Nouns == Classes • Verbs == methods, services, etc. • Example: A Hiring Specialist may post Jobs to the Job Board. • Classes = Job, JobBoard • Actions = JobBoard.PostJob(Job)
Domain Driven Design Bounded Contexts • One of many integration patterns • Continuous Integration • Shared Kernel • Customer / Supplier • Conformist • Anticorruption Layer • Separate Ways • More than One Ubiquitous Language • Applicant terminology • Hiring Specialist terminology • Department terminology
Domain Driven Design Persistence Ignorance • Why is this important? • Model-driven, not data-driven • Focus on the domain, not the data structure • Quickly swap out repositories for testing, POC, etc. • How? • Plain Old CLR Objects (POCO) • Repository pattern (abstract the data access) • Aggregate Roots • More on this in a minute
Domain Driven Design Persistence Ignorance UI Application /Service Domain Data Access Infrastructure
Domain Driven Design Refactoring • “Refactor to deeper insights” • Include your domain experts in your refactoring • Refactor your ubiquitous language 1st, your code 2nd • This doesn’t mean refactor for greater reusability • Example: benefit disbursements • Initially used Retro disbursements for final partial-month payments • Realized that these required different actions • Symptom: confusion around the name Retro when talking about Final Partial Payments
Domain Driven Design Command Query Separation User Interface Commands Query / Reporting Service Commands Domain Events Events Infrastructure Event Store
Domain Driven Design Command Query Separation • Origins – Eiffel language • Use for Distributed architectures • Move from class method level to the architectural level • Separate Bounded Contexts for reading and writing • Write == Commands == Change state and return nothing • Read == Queries == Pure functions that do not change state • Optimize each side differently • Focus on: • Event-Driven Architecture with Domain Events • State Machines • Allows easy transitions to: • Messaging services • Asynchronous processing • Massive scalability
Domain Driven Design When to use DDD • Now! (Not really) • Fits approximately 5% of development project needs • DDD is a software methodology suited to a particular kind of application – one where there is • significant complexity, and there is a significant focus on a well defined business model. • - Jak Charlton, Domain Driven Design Step-by-Step
Domain Driven Design Patterns (or how it works)
Domain Driven Design Entities • A behavioral approach mandates the assignment of responsibilities first. Only when you are satisfied with the distribution of responsibilities among your objects are you ready to make a decision about what they need to know…. Behavior is the only criterion we use to differentiate among objects. • Dr. David West, Object Thinking • When data is the center piece of your object, you assign data to objects before saying what they do. Descriptions of data don’t tell you squat about your objects. • - Rocky Lhotka, http://www.theserverside.net/tt/articles/showarticle.tss?id=BusinessObjects
Domain Driven Design Entities, cont. • The Domain Model pattern: • Structure • Behavior • No persistence behavior (i.e. Active Record) • Uniquely identified and tracked • Associated with other objects • Simplify • Remove unnecessary associations
Domain Driven Design Value Objects • Nothing special (no identity) • Don’t confuse with value type • Immutable • One instance can be used for in multiple entities • Examples: • Money • Address (usually) • Codes
Domain Driven Design Aggregate Roots • A complete and meaningful representation • Based on a single root (Entity) • Some entities or value objects don’t mean much alone • Maintains state for a collection of objects • Serves as a boundary between the objects inside and those outside • Simplifies access to the associated objects • The root has global identity and maintains invariants • Aggregates may be nested • Don’t go too deep! • Examples: • Job Board (Job) • Job (Skill, Applicant) • Applicant (Applicant Skill)
Domain Driven Design Object Creation Patterns • Aid in object creation • Entities and Value Objects should ALWAYS be valid! • Constructors • Factory • Simple Factory (Factory Method moved up to its own class) • Factory Method (static method) • Abstract Factory (composes from parts via inheritance) • Builder • Fluent Interfaces • Example: String Builder • Other Gang of Four patterns
Domain Driven Design Repository • Abstraction over data access • Acts as a collection of Aggregate Roots • Various approaches: • Repository per Aggregate (very explicit) • Generic Repository • Repository per aggregate built upon Generic Repository Strategy • Generic Repository with Specifications • Used for querying and adding/removing • Some implementations also add an Update • Generally used along with a Unit of Work (e.g. DataContext)
Domain Driven Design Repository per Aggregate • Explicit query methods: • GetById(int id) • GetByName(string name) • GetByCityAndState(City city, State state) • AddApplicant(Applicant person) • Pros: • Very explicit and intentional interface so it reads better • Restrict data access to what you want to allow developers • Can more easily optimize each query • Cons: • Very manual process to create • Cannot reuse methods for other purposes • Extension requires editing the class
Domain Driven Design Generic Repository • Generic, open query methods: • GetByKey<TKey>(TKey key) • Query<T>(Expression<Func<T>> query) • Insert<T>(T entity) • Delete<T>(T entity) • Update<T>(T entity) ? • Pros: • Very re-usable; write once, use everywhere • Easy to code-gen for extension using partial classes • More directly mimics database operations against a table • Cons: • Not intentional (Expressions?!) • Little control over what happens on insert, delete, etc. • Exposes methods you may not want exposed
Domain Driven Design Repository per Aggregate w/ Generic Strategy • Mix the best of both worlds: • GetById(int id) : Query<Person>(p => p.Id == id) • GetByName(string name) : Query<Person>(p => p.Name == name) • Add(Person person) : Insert<Person>(person) • Pros: • Very explicit and intentional interface so it reads better • Restrict data access to what you want to allow developers • Can more easily optimize each query • Standardize data access mechanics • Simplify query construction in the repository • Easier to swap out persistence technology (database / in-memory) • Composition over Inheritance • Cons: • More code than Generic Repository • More moving pieces
Domain Driven Design Generic Repository with Specifications • Generic functionality with explicit query functionality: • Query<T>(ISpecification<T> specification) • Add<T>(T entity) • Pros: • Extremely intention revealing • Same reusability as Generic Repository • Extend by creating new specifications • Specifications can be used for more than querying (e.g. rules, etc.) • Cons: • Add, Remove, etc. may still be limited(but you probably shouldn’t do much else there anyway) • May be difficult to tie into your ORM(ExpressionVisitorreq’d for L2S or EF) • What is a Specification?!
Domain Driven Design Specification • Simple interface for defining criteria: • IsSatisfiedBy(T entity) • Similar to the Query Object pattern • Very intention revealing • Very easy to test • Easy to chain together for more complex queries: • CompoiteSpecification: And, Or, Not • LINQPad uses PredicateBuilder for a similar effect • http://www.lostechies.com/blogs/chrismissal/archive/2009/09/10/using-the-specification-pattern-for-querying.aspx
Domain Driven Design Domain Services • Do not confuse with Application Services • Defining characteristics: • Actions that do not fit within an entity or aggregate • Stateless • Examples: • Transfers • Calculators
Domain Driven Design Modules • Break up your domain to reduce complexity • Becomes part of the ubiquitous language • Helps with decoupling • Aids in extensibility
Domain Driven Design Domain Events (CQS) • These are not delegate events • POCO messages • IPublish<TEvent> and IHandle<TEvent> • Domain Models (Aggregates) publish events instead of saving to the database • Eventual consistency (just like every other model)
Domain Driven Design State Machines (CQS) • In CQS, you don’t change state, you publish changes • State Machines: transition from one state to another • Domain Model (Aggregate) defines transitions • Examples: • HTTP • Stateless
Domain Driven Design Summary • Useful for very difficult and complex domains • Can help identify requirements • Focus on the language • Feel free to use patterns in other styles • Add Command Query Separation for distributed systems
Domain Driven Design Questions?
Domain Driven Design Resources • Books • Domain Driven Design: Tackling Complexity in the Heart of Software • Applying Domain Driven Design and Patterns • Domain Driven Design Quickly (abbr. version of above) • Domain Driven Design Step-by-Step • ASP.NET MVC in Action • Blogs • Eric Evans • Jimmy Nilsson • Casey Charlton • Greg Young (Distributed DDD/CQS)