Domain Driven Design in Modular Monolith - how would you organize your code based on the given example? - domain-driven-design

I am curious how you would approach it.
Imagine that you operate in the domain of Bikes selling. After workshops with the domain experts, you identified several subdomains (coarse-grained):
At the next workshop (fine-grained) you spotted that there is a further split to the next subdomains (the example is based on offers but it is the same for other coarse-grained subdomains):
So, there is a possibility to subscribe to new offers (or categories of offers) as a customer, there are discounts that can be applied to all offers (e.g. black Friday) or to a specific offer, and publishing of an offer (including approval) that is handled by 2 employees - author and approver.
Now it is time to categorize selected subdomains to:
Core
Supportive
Generic
After categorization, you found out that there is 1 core domain and 2 supportive ones:
Subscriptions - your company is known in the market as the one that has the greatest approach to handling subscriptions to offers. Your algorithm rocks the market and no one is able to do a similar thing. You spotted a Core domain.
Publishing - you were not able to find any existing solution to tackle it and decided to handle it on your own. There is almost no business logic but the data structures are quite complex. You spotted a Supportive domain.
Discounts - same story as with publishing, however here the data structures are simple. You spotted a Supportive domain.
With division in hand, you set about determining bounded contexts. It turns out that all 3 subdomains operate on the same objects, operate close to each other, and use the same (ubiquitous) language. You decide to wrap it to a bounded context called "Offering".
It is time to choose patterns for your subdomains:
Subscriptions - complex business logic, complex data structures. You decided to go with the Domain Model pattern.
Publishing - trivial business logic, complex data structures. You decided to go with the Active Record pattern.
Discounts - trivial/no business logic, simple data structures. You decided to go with the Transaction script pattern.
After all, you decided to go with Modular monolith. The example structure could look like the below:
Solution folder for each bounded context, e.g. Offering
Inside each bounded context, a folder for each subdomain, e.g. Subscriptions, Publishing, Discounts
Inside each subdomain folder, a set of projects (for Subscriptions: Application, Domain, Infrastructure; for Publishing: Presentation, Service, Business logic, Data access; for Discounts: Presentation, Business logic, Data access)
Then it could have been very easy to extract a subdomain (in case it is really needed) to a microservice. I omitted things like integration events etc. to distill the core of the problem.
How would you structure your solution based on the above assumptions?

Related

how to identify domains, subdomains and bounded contexts in an online retailer integration scenario?

The problem I'm facing is the design of an integration platform.
The company has different tools used for selling online financial services and wants to unify the selling process by creating a common integration platform.
Existing tools range from simply designing a tailor-made offer, to managing all the phases of listing to selling and supporting. The integration platform should orchestrate all the tools.
So I do approach this problem from a DDD point of view?
Domain: selling online services
subdomains: service catalog, request offers, sending offers, buying service, support customer.
bounded context? maybe integration with other company systems like identities and invoices?
My trouble with this is that some existing applications encompass several subdomains, others don't. Also, some applications working in the same subdomain have completely different languages, for example, service vs product, vs project...
How does an integration platform fit in this picture and how would you approach it from a DDD point of view? (or maybe it's a completely wrong approach and should I leave DDD inside each tool and treat them as bounded context?)
I recommend extracting the common bits of meaning (ignoring their names) from the various applications into common domains/bounded contexts. Each bounded context has anti-corruption layers that essentially adapt the language used in one or more existing applications to the one used in the common domain (and vice versa). Then you can cut over the existing applications piece-by-piece to use the respective ACLs to take advantage of the common domain implementation.
Eventually, you might even be able to dispense with the ACLs, as the language becomes more ubiquitous, but it's also perfectly okay to keep them around forever: the ACLs introduce some indirection (and possibly complexity, e.g. if they're deployed as their own microservices) but that's the price you pay for limiting coupling to the ACL.
(It's not clear from the question how experienced you are with DDD).

How to slice down a monolith where my domain depends heavily from other domains?

I'm currently learning about Microservices because in the company where I work, we will split down our giant monolith into microservices.
We have a lot of business logic in our application, but this rules basically validate data from many different domains and act accordingly the status of this data.
Our domain has it's own data, of course, but I even dare to say we depend something like 60 ~ 70% of data from different domains, which makes our domain kind of an aggregator.
I created a little diagram to illustrate it:
So like I said before, my domain (Domain A) has a lot of business logic to validate data and status from all those different domains. And then after this validation, take the appropriate actions and save the result of it in the DB.
I feel like I hit a dead end, cause I have read a few articles how to break down a monolith, but I haven't got any good example where it explains this situation.
So I ask you guys, do you have any suggestions to tell me? :)
Thanks!
In DDD speak a bounded context approximates a microservice. The different domains in your diagram are probably going to be bounded contexts.
You most certainly do not want concepts from various BCs polluting each other as you are going to end up with quite a mess.
There is one place, however, where you may run into this and that is on integration/orchestration. Here you should approach this concern almost as a separate BC that relates to the orchestration or integration.
For instance, let's assume that you have an Assets domain and an Accounting domain. The two should know nothing about each other. However, when you decommission an asset (say some huge machine that grinds down rocks into stones) you perhaps need to have the accounting domain register some write-off value if the asset has not reached the end of its useful life. In this layer you would integrate the various bits of your process and manage the state using a process manager. Although the process manager, and related state, may belong to the Assets BC the AssetsOrchestration BC may make use of objects from both the Assets as well as the Accounting BCs. Typically you would attempt to limit that interaction to, say, messages using some messaging infrastructure but YMMV.
A good starting point may be Sam Newman's Microservice Decomposition Patterns.
About 18 minutes into the talk, Newman offers this pattern:
Within your monolith, identify the coarse modules of functionality.
Draw the dependency graph
OK, your dependency graph has cycles in it. That's no good, you want an acyclic graph. So iterate on the graph until you are able to eliminate the cycles. DO NOT PASS GO until you have this done
Identify candidate modules that have no inbound dependencies - you want the bits that nothing else depends on.
Pick one, and see if you can redesign your system to allow you to deploy that module independently of the monolith.

Reasoning/modeling business logic with the approach of Domain Driven Design

What I'm trying to achieve is to develop an application implementing the DDD approach.
The story might sound silly but it's an actual, real life problem. Believe me.
The business looks as follows:
Let's say a company specializes in manufacturing sweets which are distributed to its own shops for sale.
The craftsman makes different types of candy depending on what is - and what is not - currently at the display at one of the company's shop.
When a basket of one flavour 'disappears' the seller replaces this type of sweet with a different kind from the shops storage cabinet.
Duplicates of flavours at the display shouldn't exist and the display should be populated with as much as the capacity allows or how much the manafacturer can handle to produce.
The sweets are distributed from the manufacturer's lab's storage to the shop's one depending on the demand.
Let's assume each worker has public view access to the display and the storage cabinet. Each worker (user) decides on it's own what to provide. The shops display view will be publicly accessible through the application to a potential client as an information what is currently on sale.
So far I have split the business logic into three separate (sub?)domains which are:
Production
Distribution
Sale
And of course each entity like Sweets, Storage, Craftsman, it's Repository etc. are placed respectively in their domain.
The concerns I approach are:
Is it appropriate that an entity (Sweet) is being passed from one domain to another?
Should a Provider be able to reach the StorageCabinet of one domain and pass it's content to another?
Is my reasoning proper? Correct me if I'm wrong or violating any DDD rules.
Thanks in advance.
The story might sound silly but it's an actual, real life problem.
This is great, actually. In his recent retrospective, one of the things that Greg Young called out is that "shopping cart" models are a really lousy as a teaching tool. He points out briefly that the interesting questions are in the supply chain.
Is it appropriate that an entity (Sweet) is being passed from one domain to another?
No, but a message (DTO) describing an entity's state might be passed from one domain to another.
You want to keep the flexibility to define the entities differently in each domain; that's part of the point of identifying bounded contexts.
Should a Provider be able to reach the StorageCabinet of one domain and pass it's content to another?
Probably not: your domain model isn't the book of record for the storage cabinet. Listen very carefully to Greg's comments on one way commands.

What is the best practice about sharing the model for different projects when use domain driven design?

So we may apply the domain driven design for multiple projects but there could be intersection of the same piece of domain model.
In this case, how to apply the domain driven design (use ORM, model first, generating database schema)? Create multiple databases with a lot of same tables? Or how to share data? Use synonyms? What is the possible strategy to resolve the sharing model (including data)?
Any suggestion is welcome. Thanks in advance!
In my previous project we had a lot of discussions regarding having redundant info in several models that have some shared parts.
What we found interesting is that we thought that several projects (not C# proj, but real large development projects) or call it systems very rarely share the exact same perspective on how using the model. We thought that in a larger domain that spans over several application/systems/projects you could spot several core's where you don't want the cores to be duplicated in each application.
It all ended up with a domain that where distributed on several machines. And we had GUID keys to bind them together in database. But since we did this "model first", sub domains looked at each other like infrastructure related services that where reached through Domain events.
Complicated? Not really. Here's an example:
Domain one (Salary review system) - We have a Salary Review statistic system which conduct evaluation on employees salary and how they related to their experience, age and performance. The Core is questionnaire form, work evaluation, questionnaire answers, rating. salary modification advices etc.
Domain two (Employee system) - Here you manage your employee, register new employees, handle rehab, maybe personal development, salary, employee contract, employee benefits etc.
Domain three (Performance management) - Here you handle history of employee experience, goals, achievements, and agreements between boss and employees about personal development, rating and grade of performance.
As you notice the Core of each domain is different but they share some concerns. Depending on deployment, infrastructure and requirement on how tight they should relate/respond to each other - the tech how to solve this could differ.
I Prefer to do this tech independent. We used NServiceBus for synchronizing domain through Domain Events (Udi Dahn's Domain Event Pattern).
For instance, Once we have completed a salary review for an employee and boss should be informed that Joe should get a chance of salary increase with 200 - 500 $ this year.
The method ApplySalaryReview on entity aggregate root Employee do not only save the review result, it also trigger domain event NotifySalaryReviewSubscribers which trigger an eventhandler HandleNotifySalaryReviewSubscribersEvent in Application layer that takes a infrastructure service in ctor. That service puts result in a message queue that all systems that need this info can subscribe on this message.
In our case, it is Domain two (Employee system). The employee system import result and notify employee's boss that he got new info for the upcoming salary talk with this particular employee.
I hope I may have shread some light on one way of doing it. There are so many other ways as well...
You might want to (re-)read the strategic design patterns in the blue book.

What is Domain Driven Design?

Can somebody please explain (in succinct terms) what exactly is domain driven design? I see the term quite a lot but really don't understand what it is or what it looks like. How does it differ from non-domain driven design?
Also, can somebody explain what a Domain Object is? How does domain differ from normal objects?
EDIT:
As this seem to be a top result on Google and my answer below is not, please refer to this much better answer:
https://stackoverflow.com/a/1222488/1240557
OLD ANSWER (not so complete :))
In order to create good software, you have to know what that software
is all about. You cannot create a banking software system unless you
have a good understanding of what banking is all about, one must
understand the domain of banking.
From: Domain Driven Design by Eric Evans.
This book does a pretty good job of describing DDD.
Register to download a summary of the book.
Domain Driven Design is a methodology and process prescription for the development of complex systems whose focus is mapping activities, tasks, events, and data within a problem domain into the technology artifacts of a solution domain.
The emphasis of Domain Driven Design is to understand the problem domain in order to create an abstract model of the problem domain which can then be implemented in a particular set of technologies. Domain Driven Design as a methodology provides guidelines for how this model development and technology development can result in a system that meets the needs of the people using it while also being robust in the face of change in the problem domain.
The process side of Domain Driven Design involves the collaboration between domain experts, people who know the problem domain, and the design/architecture experts, people who know the solution domain. The idea is to have a shared model with shared language so that as people from these two different domains with their two different perspectives discuss the solution they are actually discussing a shared knowledge base with shared concepts.
The lack of a shared problem domain understanding between the people who need a particular system and the people who are designing and implementing the system seems to be a core impediment to successful projects. Domain Driven Design is a methodology to address this impediment.
It is more than having an object model. The focus is really about the shared communication and improving collaboration so that the actual needs within the problem domain can be discovered and an appropriate solution created to meet those needs.
Domain-Driven Design: The Good and The Challenging provides a brief overview with this comment:
DDD helps discover the top-level architecture and inform about the
mechanics and dynamics of the domain that the software needs to
replicate. Concretely, it means that a well done DDD analysis
minimizes misunderstandings between domain experts and software
architects, and it reduces the subsequent number of expensive requests
for change. By splitting the domain complexity in smaller contexts,
DDD avoids forcing project architects to design a bloated object
model, which is where a lot of time is lost in working out
implementation details — in part because the number of entities to
deal with often grows beyond the size of conference-room white boards.
Also see this article Domain Driven Design for Services Architecture which provides a short example. The article provides the following thumbnail description of Domain Driven Design.
Domain Driven Design advocates modeling based on the reality of
business as relevant to our use cases. As it is now getting older and
hype level decreasing, many of us forget that the DDD approach really
helps in understanding the problem at hand and design software towards
the common understanding of the solution. When building applications,
DDD talks about problems as domains and subdomains. It describes
independent steps/areas of problems as bounded contexts, emphasizes a
common language to talk about these problems, and adds many technical
concepts, like entities, value objects and aggregate root rules to
support the implementation.
Martin Fowler has written a number of articles in which Domain Driven Design as a methodology is mentioned. For instance this article, BoundedContext, provides an overview of the bounded context concept from Domain Driven Development.
In those younger days we were advised to build a unified model of the
entire business, but DDD recognizes that we've learned that "total
unification of the domain model for a large system will not be
feasible or cost-effective" 1. So instead DDD divides up a large
system into Bounded Contexts, each of which can have a unified model -
essentially a way of structuring MultipleCanonicalModels.
You CAN ONLY understand Domain driven design by first comprehending what the following are:
What is a domain?
The field for which a system is built. Airport management, insurance sales, coffee shops, orbital flight, you name it.
It's not unusual for an application to span several different domains. For example, an online retail system might be working in the domains of shipping (picking appropriate ways to deliver, depending on items and destination), pricing (including promotions and user-specific pricing by, say, location), and recommendations (calculating related products by purchase history).
What is a model?
"A useful approximation to the problem at hand." -- Gerry Sussman
An Employee class is not a real employee. It models a real employee. We know that the model does not capture everything about real employees, and that's not the point of it. It's only meant to capture what we are interested in for the current context.
Different domains may be interested in different ways to model the same thing. For example, the salary department and the human resources department may model employees in different ways.
What is a domain model?
A model for a domain.
What is Domain-Driven Design (DDD)?
It is a development approach that deeply values the domain model and connects it to the implementation. DDD was coined and initially developed by Eric Evans.
Culled from here
Here is another good article that you may check out on Domain Driven Design. if your application is anything serious than college assignment. The basic premise is structure everything around your entities and have a strong domain model. Differentiate between services that provide infrastructure related things (like sending email, persisting data) and services that actually do things that are your core business requirments.
Hope that helps.
As in TDD & BDD you/ team focus the most on test and behavior of the system than code implementation.
Similar way when system analyst, product owner, development team and ofcourse the code - entities/ classes, variables, functions, user interfaces processes communicate using the same language, its called Domain Driven Design
DDD is a thought process. When modeling a design of software you need to keep business domain/process in the center of attention rather than data structures, data flows, technology, internal and external dependencies.
There are many approaches to model systerm using DDD
event sourcing (using events as a single source of truth)
relational databases
graph databases
using functional languages
Domain object:
In very naive words, an object which
has name based on business process/flow
has complete control on its internal state i.e exposes methods to manipulate state.
always fulfill all business invariants/business rules in context of its use.
follows single responsibility principle
DDD(domain driven design) is a useful concept for analyse of requirements of a project and handling the complexity of these requirements.Before that people were analysing these requirements with considering the relationships between classes and tables and in fact their design were based on database tables relationships it is not old but it has some problems:
In big projects with complex requirements it is not useful although this is a great way of design for small projects.
when you are dealing with none technical persons that they don,t have technical concept, this conflict may cause some huge problems in our project.
So DDD handle the first problem with considering the main project as a Domain and splitting each part of this project to small pieces which we are famous to Bounded Context and each of them do not have any influence on other pieces.
And the second problem has been solved with a ubiquitous language which is a common language between technical team members and Product owners which are not technical but have enough knowledge about their requirements
Generally the simple definition for Domain is the main project that makes money for the owners and other teams.
I do not want to repeat others' answers, so, in short I explain some common misunderstanding
Practical resource: PATTERNS, PRINCIPLES, AND PRACTICES OF DOMAIN-DRIVEN DESIGN by Scott Millett
It is a methodology for complicated business systems. It takes all the technical matters out when communicating with business experts
It provides an extensive understanding of (simplified and distilled model of) business across the whole dev team.
it keeps business model in sync with code model by using ubiquitous language (the language understood by the whole dev team, business experts, business analysts, ...), which is used for communication within the dev team or dev with other teams
It has nothing to do with Project Management. Although it can be perfectly used in project management methods like Agile.
You should avoid using it all across your project
DDD stresses the need to focus the most effort on the core subdomain. The core subdomain is the
area of your product that will be the difference between it being a success and it being a failure. It’s
the product’s unique selling point, the reason it is being built rather than bought.
Basically, it is because it takes too much time and effort. So, it is suggested to break down the whole domain into subdomain and just apply it in those with high business value. (ex not in generic subdomain like email, ...)
It is not object oriented programming. It is mostly problem solving approach and (sometimes) you do not need to use OO patterns (such as Gang of Four) in your domain models. Simply because it can not be understood by Business Experts (they do not know much about Factory, Decorator, ...). There are even some patterns in DDD (such as The Transaction Script, Table Module) which are not 100% in line with OO concepts.
I believe the following pdf will give you the bigger picture. Domain Driven Design by Eric Evans
NOTE: Think of a project you can work on, apply the little things you understood and see best practices. It will help you to grow your ability to the micro service architecture design approach too.
Get an organization wide understanding of the problem domain by
developing a ubiquitous language (a common mental model) per sub-problem-domain.
Use that language as close as possible in solution domains (code).
Only then choose technologies.
Don't be technology driven but problem domain or business driven.

Resources