Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
Upcoming SlideShare
What to Upload to SlideShare
What to Upload to SlideShare
Loading in …3
×
1 of 64

Introducing domain driven design - dogfood con 2018

8

Share

Download to read offline

DDD provides a set of patterns and practices for tackling complex business problems with software models. Learn the basics of DDD in this session, including several principles and patterns you can start using immediately even if your project hasn't otherwise embraced DDD. Examples will primarily use C#/.NET.

Related Books

Free with a 30 day trial from Scribd

See all

Related Audiobooks

Free with a 30 day trial from Scribd

See all

Introducing domain driven design - dogfood con 2018

  1. 1. No Content Here (Reserved for Watermark) Introducing Domain- Driven Design (DDD) @ardalis Ardalis.com Steve Smith
  2. 2. No Content Here (Reserved for Watermark) Tweet Away! • Live Tweeting and Photos are encouraged • Questions and Feedback are welcome • Use #DDDesign • Mention @ardalis
  3. 3. No Content Here (Reserved for Watermark) Online Training See me after for: • 1-month free Pluralsight pass • 20% off any DevIQ course
  4. 4. No Content Here (Reserved for Watermark) https://ardalis.com/architecture-ebook http://microsoft.com/net/learn/architecture Sample: https://github.com/dotnet-architecture/eShopOnWeb Covers ASP.NET Core 2.1 monolithic app development along with several DDD principles and patterns. Free Microsoft eBook
  5. 5. No Content Here (Reserved for Watermark) Weekly Dev Tips WeeklyDevTips.com 5-10 minute long episodes Focus on tips, tools, gotchas, patterns Prefer email? ardalis.com/tips newsletter Grab a sticker!
  6. 6. Starting down the path…
  7. 7. No Content Here (Reserved for Watermark) What is Domain-Driven Design? Focus on the problem domain Not the database, or even the code implementation Tools for better communication and knowledge discovery Patterns for modeling solutions Without tight coupling to infrastructure concerns
  8. 8. No Content Here (Reserved for Watermark) Some new thing? Domain-Driven Design published in 2004
  9. 9. No Content Here (Reserved for Watermark) Why You Should Care about DDD History of success with complex projects Principles & patterns to solve difficult problems Clear, testable code that represents the domain Aligns with practices from experts’ experience
  10. 10. No Content Here (Reserved for Watermark) Flexible Customer’s vision/perspective of the problem Path through a very complex problem Well-organized and easily tested code Business logic lives in one place. Many great patterns to leverage Benefits of Domain Driven Design
  11. 11. No Content Here (Reserved for Watermark) While Domain-Driven Design provides many technical benefits, such as maintainability, it should be applied only to complex domains where the model and the linguistic processes provide clear benefits in the communication of complex information, and in the formulation of a common understanding of the domain. —Eric Evans Domain-Driven Design
  12. 12. No Content Here (Reserved for Watermark) Time and Effort Learning curve (why you’re here) Only makes sense when there is complexity in the problem Team or Company Buy-In to DDD Drawbacks of DDD
  13. 13. No Content Here (Reserved for Watermark) DDD Concepts
  14. 14. No Content Here (Reserved for Watermark) The Domain
  15. 15. No Content Here (Reserved for Watermark) Core Domain Your company (or product/division)’s primary space in which they solve customers’ problems Key differentiator Problem Domain The overall domain of the specific problem your application will address / solve Generic Subdomains Separate applications or features your application must interact with. Not necessarily core to your app. What are “domains”
  16. 16. No Content Here (Reserved for Watermark) Domains refer to problem spaces. Domain Models and Bounded Contexts are parts of a solution.
  17. 17. No Content Here (Reserved for Watermark) Bounded Contexts Domain-Driven Design
  18. 18. No Content Here (Reserved for Watermark) Appointment Scheduling Bounded Context Billing
  19. 19. No Content Here (Reserved for Watermark) Explicitly define the context within which a model applies… Keep the model strictly consistent within these bounds, but don’t be distracted or confused by issues outside. —Eric Evans
  20. 20. No Content Here (Reserved for Watermark) Bounded Context Appointment Scheduling Billing
  21. 21. No Content Here (Reserved for Watermark) What’s important to one bounded context may not be (as) important in another.
  22. 22. No Content Here (Reserved for Watermark)
  23. 23. No Content Here (Reserved for Watermark)
  24. 24. No Content Here (Reserved for Watermark) Relates to the Solution you are building The domain represents the problem your solution is solving Core Domain – the business’s primary focus/industry Sub-Domain – a particular area within a larger domain. Maps to a software solution and bounded context. Bounded Context
  25. 25. No Content Here (Reserved for Watermark) Context Maps Client Patient Appointment Notification Exam Room Client Procedure Invoice Notification One DB To Rule Them All Appointment Scheduler Billing vet-managr The Dev Team
  26. 26. No Content Here (Reserved for Watermark) Context Maps Client Patient Appointment Notification Exam Room Client Procedure Invoice Notification Appointment Scheduler Billing DB DBAuthentication User Shared Kernel vet-appt-sched Team Awesome vet-billing Team Ultimate
  27. 27. No Content Here (Reserved for Watermark) Ubiquitous Language http://upload.wikimedia.org/wikipedia/commons/2/23/Rosetta_Stone.JPG
  28. 28. No Content Here (Reserved for Watermark) A project faces serious problems when its language is fractured. —Eric Evans
  29. 29. No Content Here (Reserved for Watermark) Ubiquitous Language For a single Bounded Context Used throughout that context, from conversations to code Bounded Contexts should also have names, to aid in disambiguation.
  30. 30. No Content Here (Reserved for Watermark) The Domain Model Domain-Driven Design
  31. 31. No Content Here (Reserved for Watermark)
  32. 32. The Domain Model
  33. 33. No Content Here (Reserved for Watermark) BehaviorsSchedule an appointment for a checkup Note a pet’s weight Request lab work Notify pet owner of vaccinations due Accept a new patient Book a room Not AttributesAppointment.Time Pet.Name Owner.Telephone Room.Number FOCUS ON
  34. 34. No Content Here (Reserved for Watermark) Rich Domain ModelsAnemic Domain Models
  35. 35. No Content Here (Reserved for Watermark) “The basic symptom of an Anemic Domain Model is that at first blush it looks like the real thing. There are objects, many named after the nouns in the domain space, and these objects are connected with the rich relationships and structure that true domain models have. The catch comes when you look at the behavior, and you realize that there is hardly any behavior on these objects, making them little more than bags of getters and setters.” —Martin Fowler http://martinfowler.com/bliki/AnemicDomainModel.html
  36. 36. No Content Here (Reserved for Watermark) Push behavior into the model objects (entities, value objects) Tell the stateful model objects what operation to perform Don’t Ask them for their state, operate on them, and then update their state Only resort to services when you can’t put logic with its state Access dependencies via domain events Tell, Don’t Ask
  37. 37. No Content Here (Reserved for Watermark) Many objects are not fundamentally defined by their attributes, but rather by a thread of continuity and identity. —Eric Evans Domain-Driven Design
  38. 38. No Content Here (Reserved for Watermark) Entities Have Identity & Are Mutable Jan 12 10:00 am Check-Up Snickerdoodle Appointment ID=358 & Vaccinations ID=172 XXXX 9:30 am
  39. 39. No Content Here (Reserved for Watermark) ENTITIES Entities in the Navigation Map Evans, Domain-Driven Design, p. 65
  40. 40. No Content Here (Reserved for Watermark) Entities should minimize direct access to their state (e.g. public property setters) Encapsulate changes by exposing well-defined methods Entities should be responsible for their own behavior Be especially wary of collection properties! EF Core 1.1+ supports encapsulation of properties (exposing IEnumerable or ReadOnlyCollection) Encapsulation
  41. 41. No Content Here (Reserved for Watermark) Dependencies and Entities Don’t inject dependencies into entity constructors And of course don’t new up or call static infrastructure dependencies This often leads to moving interesting behavior out of entities and into services Consider raising domain events Behavior requiring dependencies shifts to domain event handlers
  42. 42. No Content Here (Reserved for Watermark) VALUE OBJECTS
  43. 43. No Content Here (Reserved for Watermark) Value Object Measures, quantifies, or describes a thing in the domain. Identity is based on composition of values Immutable Compared using all values No side effects
  44. 44. No Content Here (Reserved for Watermark) Value Object Example Company Worth: $50,000,000 $ 50,000,000 Worth (Value Object) Monetary Unit (string) “U.S. Dollar” Amount (decimal): 50000000 Company (Entity) ID (guid): 9F63CE8D-9F1E-45E0-85AB-C098CC15F8E6 Worth Unit (string): “US Dollar” Worth Amount (decimal): 50000000 Company (Entity) ID (guid): 9F63CE8D-9F1E-45E0-85AB-C098CC15F8E6 Worth { Source:http://fit.c2.com/wiki.cgi?WholeValue (Ward Cunningham)
  45. 45. No Content Here (Reserved for Watermark) DateTimeRange public class DateTimeRange { public DateTimeRange(DateTime start, DateTime end) { Start=start; End=end; } public DateTime Start { get; private set; } public DateTime End { get; private set; } … } Patient Appointment 10:00 am Jan 4, 2014 – 11:00 am Jan 4, 2014 Staff Meeting 2:00 pm Feb 1, 2014 – 3:15 pm Feb 1, 2014
  46. 46. No Content Here (Reserved for Watermark) It may surprise you to learn that we should strive to model using Value Objects instead of Entities wherever possible. Even when a domain concept must be modeled as an Entity, the Entity’s design should be biased toward serving as a value container rather than a child Entity container. —Vaughn Vernon Implementing Domain Driven Design
  47. 47. Patterns
  48. 48. No Content Here (Reserved for Watermark) Aggregates
  49. 49. No Content Here (Reserved for Watermark) Aggregates
  50. 50. No Content Here (Reserved for Watermark) Aggregates Customer Address Customer Aggregate Product Component Product Aggregate 1 N N 1 Aggregate Root Aggregate Root
  51. 51. No Content Here (Reserved for Watermark) Aggregates Product Component Product Aggregate N 1
  52. 52. No Content Here (Reserved for Watermark) An aggregate is a cluster of associated objects that we treat as a unit for the purpose of data changes. —Eric Evans Domain-Driven Design
  53. 53. No Content Here (Reserved for Watermark) Important operations that don’t belong to a particular Entity or Value Object Good Domain Services: Not a natural part of an Entity or Value Object Have an interface defined in terms of other domain model elements Are stateless (but may have side effects) Live in the Core of the application Domain Services Result Value Object Entity 2 Entity 1 Service
  54. 54. No Content Here (Reserved for Watermark) Examples of Services in Different Layers UI Layer & Application Layer InfrastructureDomain (“Application Core”) Message Sending Message Processing XML Parsing UI Services Transfer Between Accounts Process Order Send Email Log to a File
  55. 55. No Content Here (Reserved for Watermark) Repository Palaeoclimate archives: Core repository of AWI Hannes Grobe/AWI Creative Commons Attribution 3.0
  56. 56. No Content Here (Reserved for Watermark) A repository represents all objects of a certain type as a conceptual set…like a collection with more elaborate querying capability. —Eric Evans Domain-Driven Design
  57. 57. No Content Here (Reserved for Watermark) Repository Benefits Provides common abstraction for persistence Promotes Separation of Concerns Communicates Design Decisions Enables Testability Improved Maintainability
  58. 58. No Content Here (Reserved for Watermark) Client code can be ignorant of repository implementation …but developers cannot N+1 Query Errors Inappropriate use of eager or lazy loading Fetching more data than required Common Repository Blunders
  59. 59. No Content Here (Reserved for Watermark) Enforce proper Aggregate usage by only creating Repositories for Aggregates Use Marker Interfaces to identity Aggregate Roots Constrain generic repository implementations to work with Aggregate Root types only Repositories and Aggregates
  60. 60. No Content Here (Reserved for Watermark) Avoid returning IQueryable results Initially, use separate methods for specialized queries and commands Address method explosion, SRP violation, and too much Repository complexity with the Specification pattern Repository Method Tips
  61. 61. No Content Here (Reserved for Watermark) Domain Events (one of my favorites) Specification Learn more about these from my Pluralsight courses: • DDD Fundamentals • Design Patterns Library - Specification More Patterns (we don’t have time for)
  62. 62. No Content Here (Reserved for Watermark) Or tweet me @ardalis and I’ll answer later. Let me know if I can help your team get up to speed with DDD, Clean Architecture, and/or .NET Core. Questions?
  63. 63. No Content Here (Reserved for Watermark) No Content Here (Reserved for Watermark) No Content Here (Reserved for Course Previews) Thanks! Follow us: /DevIQPage DevIQ.com/updates @deviq • full-length courses • samples • member-only events Enroll in DevIQ for access to: DevIQ.com/enroll Ardalis.com @ardalis | steve@deviq.com Steve Smith

Editor's Notes

  • Abstract
    This is a hands-on workshop. You must bring your own laptop. Writing SOLID, testable ASP.NET Core applications has never been easier, but it may require a change in the way you typically structure your projects and their dependencies. In this hands-on workshop, you'll build a working ASP.NET Core application, complete with unit and integration tests. Along the way you'll learn the basics of Domain-Driven Development, and how to apply them to ASP.NET Core application development. The principles and patterns will apply to developers working with previous versions of ASP.NET MVC, as well.
  • https://twitter.com/hashtag/Codemash
    https://twitter.com/hashtag/DDDesign

  • “Majestic Monolith”
  • DDD provides principles and patterns to help us tackle difficult software problems and even business problems

    These are patterns that are being used successfully to solve very complex problems

    The more I learned about DDD, the more I found these ideas align with the approaches I’ve learned from my years of experience. I’ve read white papers describing how these approaches have worked for others, and I’ve applied DDD to many of my clients’ projects. DDD has a solid track record of success when applied appropriately.

    DDD provides us with a clean representation of the problem in code that I can readily understand and verify through tests

  • Domain Driven Design can a big commitment. While we have both chosen to leverage pieces of DDD as we learn more about the wider scope, one thing we are both confident about is that it is providing a lot of benefits to our work.

    Because DDD guides us to focus on small, individual, nearly autonomous pieces of our domain,, our process and the resulting software is more flexible. We can easily move or modify the small parts with little or no side effects. It even lets us be more flexible with our project resources as we build the software.

    S:
    The resulting software is More closely mapped to the customer’s understanding of the problem
    DDD gives you a clear and manageable path through a very complex problem
    When you look at the code, you can see that it’s well-organized and easily tested, and the business logic lives in one place.
    Even if you don’t use full DDD for a project, there are patterns and practices that you can use by themselves to benefit your application … so keep watching even if you don’t think you’ll need it all  )
  • DDD is not a path for every project. Its real benefit is for complex domains.

    Even Eric Evans explicitly states that DDD isn’t suitable for problems where there is substantial technical complexity but little business domain complexity.
  • DDD offers great benefits, but There’s No Such Thing As A Free Lunch.

    You’ll spend a lot of time talking about the domain and the problems that need to be solved.
    And you’ll spend plenty of time sorting out what is truly domain logic and what is just infrastructure…the easy example there is data persistence, but also concerns external services or file or network access.

    You’ll have a big learning curve as you learn new principles, patterns and processes. There is no question about that. DDD is a big topic and gaining expertise from end-to-end is a big commitment.

    It’s worth restating, that DDD is not always the correct path for your apps. And it’s helpful to keep in mind some of the scenarios where DDD is just going to be overkill.

    If you’re really just trying to provide users with a way to edit data in tables, and there are very few business rules, DDD is probably a waste of effort.


    And be clear about the difference between complexity in your business domain and technical complexity. DDD is designed to help with complex domains. If your domain is simple == even if you have a lot of technical challenges to overcome, DDD still may not the right path. For example, If you were writing a tic-tac-toe game for a touchscreen with a new complex API, the complexity lies in the touch interactions of the two players on the screen. The domain itself is well-known and just comes down to Xs and Os.

    Getting others to agree to follow the DDD approach can also be a drawback. There may be some politics involved in this decision – it depends on your team. We hope that another takeaway from this course will be to help you understand the concrete benefits of DDD which you can show to your coworkers to help convince them.

  • Let’s start with the Core Domain, and talk about how it relates to the bounded contexts and the language used to describe the project.

    We’ll also mention Context Mapping and Shared Kernels.
  • S: As you develop your model, remember to identify its bounded context. That is, where is this model valid? If you don’t put boundaries around your model, eventually pieces of it will be used where they don’t fit. Concepts that make sense in one part of the application won’t make sense in another, even if they have the same name, and sometimes even if they literally refer to the same thing.

    J: For example, as we built out the appointment scheduling portion of this system, we needed to know some very basic information about clients. But in the context of appointment scheduling, these are very simple concepts with little behavior beyond their names. However, in the billing context, we’ll want to include contact and payment information for clients. But that’s information we don’t care about in the appointment scheduling context. If we try to reuse the same model in multiple places, it’s likely to cause inconsistent behavior in our system.

    S: That’s right. For instance, we might decide to include some form of validation on clients, to ensure we have enough information to bill them. If we’re not careful, that validation might inadvertently prevent us from being able to schedule the client for appointments, which certainly isn’t the desired behavior. Maybe the billing system requires that clients have a valid credit card in order to save changes for them, but it wouldn’t make sense for a lack of a credit card to prevent us from saving an appointment for a client in the appointment scheduling system. In this example, we have two contexts, but the boundaries between them are blurred and overlapping.

  • S: Eric Evans notes that models are only valid within specific contexts. Therefore, it’s best to explicitly define the context within which a model applies. We should be able to avoid compromising the model within this context, keeping it strictly consistent within these bounds, and avoiding distractions or confusion from outside issues.
  • J: Once we explicitly define our bounded contexts, we can easily see whether or not we have elements of our model that are trying to span multiple contexts. In this example, we would want to keep a simple view of a Client in the appointment scheduling application, and a richer version of the Client, with contact and billing information, in the Billing context. These two views of a Client are defined in two separate classes. They will most likely live in separate applications. In fact, Evans recommends that bounded contexts maintain their separation by giving each context its own team, codebase, and database schema.

    S: This is ideal, but of course in many real-world systems, we need to work on systems where this level of separation is not present, usually due to resource constraints or for political reasons within the organization. Remember, though, if you have multiple contexts, you will want to keep them bounded, and one way to maintain this separation is to keep their data, code, and team members distinct from one another.
  • You know how sometimes you’ll have a shared database and it’ll be organized for a certain purpose, but you need this one thing from it and it’s got like 50 things you don’t care about? It can make it much more difficult to reason about the problem and your model for it. It’s providing a lot of information that isn’t the thing that’s most important to you for your current need.
  • Like, in this case, as you’re driving down the road at 50 MPH, you don’t really care how sharp the sign is, but you do care that the bridge is out ahead.
  • A good first step for an existing application is to create a map that shows how things *are*. Remember that the name of your contexts are also important, as you’ll refer to them frequently when discussing different parts of the application. It may be that things are not as separate as they should be; that’s worth noting. If you have separate teams responsible for different contexts that share resources, it’s important that each team understands which aspects of the application they can change on their own, and which are shared dependencies they’ll need to coordinate with the other team to void breaking things. If we look at these two sets of concepts, we can see some obvious overlap. For one thing, Client (click) appears in both contexts, but we know that for appointment scheduler we only really care about the client’s name, whereas in the billing system they’ll want additional information like address and payment details. However, although the details involved vary, we know that Mr. Jones the client on the left is the same actual person as Mr. Jones the client on the right. However, we also have a concept of notifications on both sides, and in this case they’re referring to different things. On the left, we’re talking about sending a notification when an appointment is booked, as a reminder, and on the right we’re talking about notifying the client that their payment was received, or perhaps that it’s past due.

    S: Especially in smaller organizations, it’s common to have one team responsible for several contexts of the same overall application.(click)
    In such cases, it’s also common for the team to use a single codebase for the bounded contexts they’re working with, (click)
    As well as a shared database.(click). As we’ve already noted this is not ideal, since it makes it much more difficult to maintain the boundaries between the separate contexts.

    J: Part of creating a context map involves explicitly identifying its boundaries. If we try to draw the boundaries around these two bounded contexts, we can see there are now several resources that belong to each bounded context. This isn’t ideal if these two contexts really are meant to be kept separate.


    NOTE:
    Evans notes that within each bounded context you will have a coherent dialect of the ubiquitous language. The names of the bounded contexts will themselves enter the language so that you can speak unambiguously about the model of any part of the design by making your context clear.

    It’s OK to have the same name in separate contexts – you can always disambiguate by being specific about the context in which you’re using the term. However, this assumes that you are in fact separating your contexts, so you have different teams, codebases, and databases. In that case, all day long each team can refer to for instance Notification and everybody on that team knows what is being referenced. However, if the teams, codebase, and/or database are shared, then it may make sense to adjust the language so everyone understands which term is being referenced.

    NOTE: Sometimes concepts can be readonly within one bounded context, to keep things consistent. For instance the appointment scheduler may not care about editing clients or patients at all, so its model might have read-only versions of these concepts. However, that doesn’t mean the user of the application can’t make updates to clients or patients while scheduling an appointment, it just means they may do it from another part of the application (from the perspective of the system – the user may view it as all part of the same interface) that uses a different bounded context from what the appointment scheduler uses.

    Identify ddd bounded contexts, anti=corruption layers, what’s just crud, what can be totally external (a la quickbooks, notifications to clients etc)
  • S: In the ideal case, for a large complex system, we would have bounded contexts like these, with their own teams, codebases, and databases. In this was, both teams are free change their model without worrying about breaking anything outside of the boundaries for team and context. This can greatly increase team velocity and reduce integration bugs.

    J: Of course, you’re probably wondering how the two systems will interoperate. There are a number of patterns that can be applied to enable such integration. We won’t be covering all of them in this course. One question that frequently comes up is, how to share cross-cutting concerns, like authentication? (click)

    For this scenario, a common approach is to designate these shared concepts or resources as a Shared Kernel. The two teams agree to share this subset of the domain model. (click) Since they’re sharing it, they also agree not to change it without coordinating with the other team first. Frequently, the shared kernel will either be a part of the customer’s core domain, or some set of generic subdomains, or both, though it can be any part of the model that both teams require. Using a shared kernel is a tradeoff between code reuse and consistency and the overhead of involved in integrating changes to the shared kernel across multiple teams and bounded contexts. It works best when the shared model is relatively stable.
  • We’ve mentioned already that an important aspect of DDD is an emphasis on effective communication among the stakeholders in the project. And remember, if you’re a programmer, count yourself as one of the stakeholders in whatever you’re working on, since you certainly have a stake in its success! The language we use to describe the problem and how we choose to model it is key to the shared understanding we want to have with our domain experts in order to be successful. Having a single, shared, ubiquitous language helps avoid unnecessary confusion and translation within the team building the software, and is one of the fundamental practices of domain-driven design.
  • S: Let’s look at a couple of excerpts from the DDD book on ubiquitous language. Evans cautions that “A project faces serious problems with its language is fractured.”

    When domain experts use their jargon while technical team members have their own language tuned for discussing the domain terms in the design, translation errors will manifest as software bugs. Neither the customer’s nor the developers’ language is sufficient for all parties to discuss the application effectively. What is needed is a shared, common, language that incorporates and uses terms defined in the domain model. The use of this language must be ubiquitous, and the more the language is used, the more it will force deficiencies in the model into the open.

    J: And by ubiquitous, we mean it must be used everywhere. The vocabulary of the language includes the names of model classes and prominent operations. The team should use these common terms in code, in diagrams, on whiteboard, in design documents, and especially when discussing the system.
  • You can use Bounded Context names similar to how you use namespaces in C#/.NET.
  • Apply Model-Driven (NOT Data-Driven) design to create a domain model, that models the behavior of the problem domain.
  • S: In a typical database driven app, we are used to focusing on properties, or attributes of classes. Our apps sometimes become all about editing property values and the state of our objects.
    However, when we are modeling a domain, we focus on the behaviors of that domain, not just on changing the state of objects. Think about the actions a user can take, not the values they can change. What side effects or additional behaviors are triggered by the user’s actions?
  • An anemic domain model is a domain model that is focused on the state of it’s objects which is the antithesis of domain driven design. While the term is very negative – indicating a deficiency, you don’t need to perceive it that way. There’s nothing wrong with anemic classes when all you need is to do some CRUD logic. But you if you are creating a domain model, you have already made the decision that your domain is too complex for crud. So anemia in a domain model is an anti-pattern.

    What we aim for are rich, not anemic, domain models, when we are modeling our domain. Rich domain models will represent the behaviors and business logic of your domain. Classes that simply affect state are considered an anti-pattern in a domain model and therefore get the nasty label of “anemic” even though they are perfectly fine in a CRUD model. While Martin Fowler and other DDDers have strong words to say about anemic domain models, we’d like to share a gentler message which is to strive for rich domain models and have an awareness of the strengths and weaknesses of those that are not so rich.
  • Indeed often these models come with design rules that say that you are not to put any domain logic in the the domain objects. Instead there are a set of service objects which capture all the domain logic. These services live on top of the domain model and use the domain model for data.
  • Even though a DDD app is driven by behavior, we still need objects. DDD expresses two types of objects: those which are defined by an identity and those which are defined by their values. We’ll focus first on the objects that are defined by their identity .. These objects are called entities.
  • S: An entity is something we need to be able to track, locate, retrieve and store, [click for animation]
    and we do that with an identity key. [click for animation]

    Its properties may change so we can’t use its properties to identify the object. If you’ve done any type of data persistence in software, you are probably pretty familiar with entities and their keys. When we are modeling a problem, we can talk about entities without having to think about how they are implemented in the resulting software. But when it is time to start coding, there are patterns to follow to ensure that these objects have the technical attributes of entities.

  • J: As you can see from this section of the DDD navigation or mind-map, entities are pretty integral to our software. So before we can learn about these other elements — domain events, repositories, factories and more — you should have a good understanding of an entity. Fortunately, you’re probably already familiar with working with objects that use an ID for persistence.
  • J: When introducing entities, we talked about objects that were defined by a thread of continuity and an identity, not defined by their values. So what about objects that are defined by their values? These are called Value Object and play an equally important role in a domain model as entity objects.
  • A Value Object has very specific characteristics. It is an object that is used to measure, quantify or describe something in your domain. Rather than having an identity key, its identity is based on the composition of the values of all of its properties. Because the property values define a value object, it is immutable. In other words, you can’t change any of the properties. Instead you would create another instance with the new values. If you need to compare two value objects to determine if they are equal, you need to do so using all of its values. Value objects may have methods and behavior, but they should not have side effects. Any methods on the value object should only compute things, they shouldn’t change the state of the value object (since it’s immutable) or the system. If a new value is needed, a new value object should be returned.

    See: Strings and DateTimes in .NET
  • Ward Cunningham provides us with a helpful example: a company’s worth.

    If a company is worth 50 million dollars, that means something : fifty million dollars. It’s a very specific measurement. 50 million, on its own is not a measurement. It has no meaning without the unit – dollars. In fact, dollars doesn’t help …is it Canadian dollars? Australia dollars? Ahh U.S. Dollars. But U.S. dollars alone doesn’t describe worth either. It only makes sense when you put the two together as 50million u.s. dollars.

    S: So we could still just have the two properties in this company class. But by creating a value object, you also protect and constrain the measurement. Nobody can set unit without setting the amount. More importantly, nobody can just randomly change the unit. 50million rupees is a totally different value than 50 million dollars. The value is represented by the object as a whole. It’s not immutable. If the company’s worth changes, then we can just set the worth property to a new worth value object.

    (http://fit.c2.com/wiki.cgi?WholeValue)
  • A value object is not always for a measurement. It can be another type of description. I’ve used this one often and it was perfect for the vet appointment scheduling app. We usually set a start and end time together and can’t set one without the other. Also, we often need to pass the two values, start and end time, around from one method to another. So we’ve encapsulated them in a value object. The properties have private setters so the object is immutable. We aren’t showing the full logic of the class here, but when we look at the value objects in our app, you’ll see more of how we implement a value object in our software to ensure that it meets all of the attributes. Not just immutability but how we handle equality comparison and other logic.
  • In his book Implementing Domain Driven Design, Vaughn Vernon recommends that we should try to use value objects instead of entities wherever possible. Essentially you can decorate one or more value objects with an ID property to form an entity. Some DDD proponents will even go so far as to make individual IDs themselves value objects, which does have the benefit of ensuring via the type system that you never accidentally use an OrderID where you meant to use a CustomerID, for instance.
  • Imagine this represents all of the entities and concepts in your domain. Most of these will likely have some corresponding structure in your data model. Each brick represents a different class, perhaps a different table in the database. When you need to work with a composite element in your model, something that’s represented by multiple objects and their relationships, and which is responsible for its own integrity, do you want to have to deal with individual bricks?
  • Aggregates let you identify complete, larger-grained structures in your model, and work at this higher level of abstraction.
  • Aggregates consist of one or more entities and value objects that change together. We need to treat them as a unit for data changes, and we must consider the entire aggregate’s consistency before applying such changes. In the examples shown here, the address is part of the Customer; the Component is quite literally a part of the Product. We can treat a set of changes to a customer and their address as a single transaction. (click) Every aggregate must have an aggregate root, which is the parent object of all members of the aggregate. It is possible to have an aggregate that consists of just one object, in which case that object would be the aggregate root.
  • S: In some cases, the aggregate may have rules that enforce data consistency that apply across multiple objects. For instance, maybe our product consists of a collection of components, but in order to be in a valid state it needs to have a specific set of such components. (click) For instance, if the product is a Lego Minifig, the collection of parts won’t be a valid product unless it includes a head, an upper torso, a lower torso, 2 arms, 2 hands, and 2 legs. If we allowed the collection of components to be modified independently of the product it was associated with (click), we could easily end up with consistency problems. If we want to modify the composition of a product in this example, we should do so as a transaction, so that we start and end with a valid product.

    J: Data changes to the aggregate should follow ACID. That is, they should be atomic, consistent, isolated, and durable. It is also the responsibility of the aggregate root to maintain its invariants, such as the number and type of components it requires in this example. An invariant is a condition that should always be true for the system to be in a consistent state. When considering whether a particular object should be treated as an aggregate root, think about whether deleting it should cascade, deleting the other objects in its aggregate hierarchy. If so, it’s likely the object in question should be considered an aggregate root.

    [is the below bit too long? Should we put it on another slide along with a Part object to make it more clear? J: - if you want to leave it, I can do it when I edit]
    S: Another way to think about whether it makes sense to have an object as an aggregate root is to ask, does it make sense to have just this object, detached from its parent? In the example shown here, each component represents a specific piece of the product. Part of the definition for the component might be a standard part number, but it also includes product specific information, like perhaps whether it’s the left or right hand of the figure. While it may make sense somewhere in the application to refer to a ‘yellow hand’ part on its own, referring to the left hand of a particular product that happens to use the yellow hand part is not likely to be referenced separately from the product object. Thus, we wouldn’t provide persistence options for retrieving a single component separately from its product – we would retrieve and save whole products along with their components.
  • S: Read the slide.

    This slide is supposed to have quotes on it, I think. Not sure where those ended up. I may have the wrong slide template.
  • JULIE
    When an operation is important to the model, but doesn’t necessarily belong on any one entity or value object, a service is often appropriate. Don’t be too quick to give up on finding a natural home for the operation on an existing entity or value object, though, or you may end up with a very procedural, anemic model. Frequently, domain services serve as orchestrators for operations that require several different collaborating entities and or value objects.

    Evans notes that good domain services must first and foremost not be a natural part of an existing entity or value object. Again, we don’t want to shift all of our rich behavior from our entities and value objects to our services. Services also should have a defined interface that is comprised of domain model elements. Lastly, domain services should be stateless, though they may have side effects. What this means is, we should always be able to simply create a new instance of a service to perform an operation, rather than having to rely on any previous history that may have occurred within a particular service instance. But of course, the result of calling a method on a service may result in changes to the state of the system itself.

    Finally, these rules apply specifically to Domain Services, which belong in the core of our application. Your software will likely also use services to perform work related to infrastructure, or as part of the front end of the application.

  • STEVE
    Here are some examples of the kinds of services we might find in different layers of a DDD application. The UI layer represents the front end of the system, and should have as little business logic as possible. It is frequently combined with the Application Layer, which should be concerned with behavior necessary for the application, but unrelated to the customer’s problem domain. For example, the application may need to work with file formats or parse XML, and might have services for these purposes, but these are unrelated to the domain.

    In the core of the application, which is our core domain, we will define any domain services for operations that don’t belong somewhere else. These services will frequently involve operations on multiple domain elements, or will be responsible for orchestrating some kind of a workflow. For instance, processing an order might involve a series of steps and multiple domain elements as the system checks inventory, verifies customer information, charges a credit card, and sends messages to ship the order, notify the customer, and reduce inventory.

    Finally, there are infrastructure level services. These will usually implement interfaces defined in the core of the domain, such as ISendEmail, but since they require access to external dependencies like file systems, databases, or network resources, they live in the infrastructure layer of the system. With respect to our domain, you may find infrastructure not very interesting, though I’m sure the folks creating the internal workings of those services think they are quite fascinating.
  • S: If this were an in-person class, I’d definitely ask for a show of hands, “who has heard of the Repository design pattern?”. I would expect most hands to go up.

    J: Yes, I think the Repository pattern is by far the most popular element of DDD to be practiced outside of domain-driven design today. They can be valuable in many applications as a way to simplify data access and enforce separation of concerns. When I began learning about repositories and implementing them in my own software design, it had a huge impact on my application architecture. Along with automated testing practices, it really forced me to consider separation of concerns with each method and behavior I added to my software. It really made me stop and think: “where does this really belong?”

    S: Personally, I love the pattern and find it makes it much easier for me to write good, testable code. We’re going to talk about using repositories within a DDD application, but you can learn more about the pattern itself in the Design Patterns library, and I know Julie discusses using them with Entity Framework in her “entity Framework in the Enterprise” course. (show a screenshot of these two course titles from the website).
  • S: In Domain-Driven Design, Eric Evans sums up repositories simply: (read)


  • S: Repositories provide a number of benefits to our application.

    S: Provides a common abstraction for persistence concerns
    Clients can simply obtain model objects and manage their life cycle

    S: Promotes Separation of Concerns
    Domain logic and user interface can vary independently from the data source used by the application

    J: Communicate Design Decisions
    Only certain objects should be accessed directly; Repositories provide and control this access

    J: Enables Testability
    Tight coupling to external resources, like databases, make unit testing difficult

    Note that having repositories separate from client code and domain logic means that we can easily make improvements to optimize data access for the application. Tuning for performance, adding caching behavior, etc. is all much easier and safer when the code for data access is all encapsulated in one or more well-known classes.

  • (all Julie)

    J: Developers must understand how the underlying technology of their repositories work in order to avoid performance issues and other design problems
  • ×