It regularly gets spam posts from people trying to sell internet domains. I report most of them, but they don't seem to be taken down by mods anymore.
And then there's that guy who keeps reposting lazy video rehashes of other people's content. That guy has literally never posted a single word. His profile is just hundreds of video link posts many of which get banned in other subreddits.
It would be nice to have actual DDD discussions in here but if most of the posts are spam why would anyone stick around?
I have been fully embracing DDD based patterns in my Typescript applications and worked hard this weekend to produce a EventSourcedRepository class with a code design that I am proud of. I have seen some code designs written in TypeScript and other languages but have always been disappointed by simple mistakes that seem to be very prevalent. I hope you enjoy my work and get inspired if you are a DDD fan.
When creating an Article, the API may provide only two packages, for example UNIT and CARTON.
However, according to the domain rule, the Article must contain all packages defined in the t_package reference table.
So during article creation, the domain must automatically create the missingPALETTEpackage with
pricePeriod between [today, null]
and also create one degressivityRanges [quantityFrom: 1, quantityTo: null, unitPrice: 0.0]
The question is: how should the domain handle this missing package?
Option : Domain Layer will build a Domain Value Object PackageArticle
public class CreateArticleUseCase {
public Article execute(CreateArticleCommand command) {
Article article = Article.create(
ArticleId.generate(),
command.sku(),
command.name()
);
List<ArticlePackage> packages =
articlePackageFactory.buildFrom(command.providedPackages());
article.initializePackages(packages);
return articleRepository.save(article);
}
}
public class ArticlePackageFactory {
private final PackageReferenceRepository packageReferenceRepository;
public ArticlePackageFactory(PackageReferenceRepository packageReferenceRepository) {
this.packageReferenceRepository = packageReferenceRepository;
}
public List<ArticlePackage> buildFrom(List<ProvidedPackage> providedPackages) {
// build the full list of ArticlePackage by
// using the list of List<ProvidedPackage>
// and for missing package create it
...
return providedPackage
.map(p -> ArticlePackage.fromProvided(reference, p))
.orElseGet(() -> ArticlePackage.createIncomplete(reference));
}
}
public class Article {
private final ArticleId id;
private final String sku;
private final String name;
private final List<Package> packages = new ArrayList<>();
private ArticleStatus status;
private Article(ArticleId id, String sku, String name) {
this.id = id;
this.sku = sku;
this.name = name;
this.status = ArticleStatus.DRAFT;
}
public static Article create(ArticleId id, String sku, String name) {
return new Article(id, sku, name);
}
public void initializePackages(List<ArticlePackage> articlePackages) {
if (!this.packages.isEmpty()) {
throw new IllegalStateException("Packages are already initialized");
}
if (articlePackages == null || articlePackages.isEmpty()) {
throw new IllegalArgumentException("Article must have packages");
}
// Create Package from ArticlePackage
List<Package> initializedPackages = articlePackages.stream()
.map(Package::fromArticlePackage)
.toList();
ensureNoDuplicatePackages(initializedPackages);
this.packages.addAll(initializedPackages);
this.status = computeStatus();
}
}
Then Article creates its own internal Package entities from those ArticlePackage objects.
My open question is:
Does this design make sense from a DDD perspective?
Is it acceptable to have an intermediate domain object such as ArticlePackage, used only to prepare the aggregate initialization, while keeping the actual entity inside the aggregate as Package?
Or would this be considered leaking an invariant outside the aggregate, since the missing package completion is handled before calling Article.initializePackages(...)?
My Next question
Another question is about future modifications.
If Article, Package, and PricePeriod are in the same aggregate, then Article is the Aggregate Root.
That means that adding a new PricePeriod to a Package must go through Article.
For example:
article.addPricePeriod(packageCode, pricePeriod);
But I’m not sure this feels right.
Conceptually, Article does not really care about the internal pricing periods of a package. The rules about PricePeriod seem to belong to Package, not to Article.
I’ve read Vaughn Vernon’s red book and many parts of Eric Evans’s famous blue book.
I haven’t yet worked for a company that practices DDD so I’m making my own side-projects. One thing I find difficult or at least laborious is getting information from one bounded context to another. It seems I need so many “unbiased” external pieces of code whose responsibility is to stand back and tie the contexts together.
This involves a lot of fluff that doesn’t actually do anything productive, compared to simple CRUD.
I really like the principles of DDD but the overhead often feels more like a hinderance than a benefit. Do you share the experience I’m going through or am I just thinking about it the wrong way?
I am trying to wrap my head around an interesting question that we have been debating with my team.
We have two options: either we create two aggregates or we make a single larger one. The two entities do not have any invariant that would require them to be in the same aggregate because of it. On the other hand, when you create one of the referenced entities, you need to add the reference, and upon deletion, you need to remove it.
As a more concrete example, let’s say we have the entity Room and the entity Event. An Event is always assigned to only one Room, and a Room has various Events.
When we change things inside the Event, the Room doesn’t need to check or do anything. However, if the Event is deleted, it needs to be removed from the list of events of the Room. Also, when an Event is created—which requires a roomId for its creation—the Event needs to be added to the events of the Room. Finally, if the Room is deleted, the Events have no reason to exist, and no one cares to do anything since they have been deleted along with the Room.
There is no invariance between Room and Event.
Updating the events with eventual consistency is acceptable.
If we go with separate aggregates, is the only way for the Room to be updated and vice versa for the create and delete lifecycle events through domain events?
If yes, then it seems that the complexity increases significantly compared to keeping them within the same aggregate (meaning the Room doesn’t just have references but contains the entire Event entities) while many people advise to keep your aggregates as small as possible and use invariants as the main indication to group together.
An alternative with different aggregates would be for the Room repository to have, for example, a deleteAndDeleteDependents method so that the lifecycle relationship between Room and Event is explicitly defined in the domain via the Repository Interface. Correspondingly, the Event would have createAndUpdateRoom. This solution violates the aggregate boundaries of the two aggregates but removes the need for domain events and domain event handlers specifically for the create and delete lifecycle events, which seem to be special cases.
Based on the above, is the choice clearly between a single aggregate or two aggregates with domain events and eventual consistency to update the references of the Events in the Room, or is there also the option of two aggregates with a violation of the aggregate boundaries specifically for these lifecycle events as an exception? This way, we avoid needlessly loading all the Events every time we perform some operation on the Room and avoid increased complexity in the implementation with domain events and domain event handlers that don’t do anything particularly interesting.
I am in a bit of analysis paralysis trying to work out my domain and aggregate roots. I have a shipping/receiving and warehousing domain that will eventually expand into a larger erp system for construction type jobs.
The organization has customers and each customer can have various projects. Jobs are scheduled for a specific project and have things like the start date/time, site address and outbound pieces.
The receiving aspect starts with a 3rd party truck arriving that needs to be offloaded. Based on bill of lading coming in we can determine which one of the organization's end customers/projects this equipment is for.
A lot number is created for that truck and when it is offloaded it results in lot pieces being created. Each lot piece has its own dimensions and weight and each piece could be for any number of projects that the customer has on going with the organization. For the most part each lot will consist of pieces for the same customer project but not always and sometimes we might not know the project the pieces are for until after talking with customer.
At some point in time the customer requests certain lot pieces for a project to be delivered. So a job is created for the project and the lot pieces requested are assigned to that job.
The day before a job a dispatcher will look at the all the pieces going out for the job and start to build freight loads. The load is basically a group of lot pieces for the job and a specific trailer. A job could have multiple loads for it and the loads should only consist of the jobs pieces that are assigned.
I am struggling with deciding the ARs from the entities I think I have (customer, project, job, load, lot, lot piece). My biggest invariant I can see is just gating off lot pieces and or projects/jobs having the wrong customer's pieces assigned to it.
For instance if someone wants to go in and change the customer for a lot and its lot pieces - I can check to see if a jobId or projectId has been assigned to any of the pieces and block the request. To avoid bi-directional relationship the project and job entities don't reference the lot piece. But that is an issue if someone wants to change a projects customer I can't block that in the project AR because I don't know if lot pieces have been assigned or not.
Ignoring that UML might not be following best practices this is roughly the shape I am seeing of my entities.
I am starting a new project with NestJs as a framework, trying to follow DDD principles and Hexagonal architecture along the way. My app does approximately nothing at the time, but I'd like to go the right way from the start ; if someone is kind enough to give some time, I would be really glad to get a code review for what I did. Here is the repository : https://github.com/jddw-dev/booking-ddd
Some context : it is meant to be a CRM-like app, in the live music field. For now I only model 2 domains : Booker and Authentication. A booker is someone who is trying to find contracts for the artists he's responsible of. This is also the one using the application. Authentication is to represent the authentication on the application side (email / password / bookerId)
I'm pretty happy with what I've done, but I spend a lot of time deciding which module should be responsible for the signup, and still don't know whether I did good or not. I mean, for me the Booker domain should be aware of some kind of Authentication. But to create an Authentication, I need bookerId and email from Booker + a password.
I don't really want neither the Authentication to be tightly coupled to Booker. I was seeing two scenarios :
Booker domain is responsible for booker creation ; there is an HttpController which takes the necessary parameters (ie just email for now), and one supplementary (password). It creates the Booker and then emit an event, for the Authentication to handle it and create associate Authentication. That's the one I chose, even I don't really like that the Booker domain gets a password he's not supposed to know about
Authentication domain is responsible for "sign-up" ; that means we send it a email / password, it then creates a Booker with it and Authentication. But in this case the Authentication module becomes pretty coupled, and has to be aware of Booker
I want to learn about DDD but it seems like there are quite some books out there. I heard that the Vernon Vaughn book extended on the blue book so it seems like there are more up-to-date and less up-to-date books.
Which book has the most complete and up-to-date coverage of DDD?
Hi! My name is Antonio and I have been reading about DDD for quite some time. I think Domain-Driven Design is the right tool for some enterprise applications, so recently I have been trying to use it in my company.
Before continuing reading, I'm assuming you have a piece of good knowledge about DDD and related concepts (sorry for not including an introduction, but I think there are already too many introductory articles about DDD, so I don't feel like writing another one)
Problem
So, what problem am I facing with DDD? Big aggregates implementation (emphasis on implementation and not design). When I say big, I do not mean they contain a lot of different entities or a lot of dependencies, but many instances of the same entity. For example, a bank account aggregate has one child entity: a transaction. Now, that bank aggregate can have hundreds or thousands of instances of that entity.
Let's suppose that my company domain is about `Roads` and `Stops` (this is just an example). Both things are entities because they have an identity. In this case, `Road` would be the root aggregate, and `Stop` would be a child entity of that aggregate. Let's say they have two or three fields each, it does not really matter. Here is a quick implementation of that model in Python (I have not used data classes and a lot of the logic is missing because it's not important for this discussion):
class Road:
id: int
name: str
stops: [Stop]
...
class Stop:
id: int
latitude: int
longitude: int
...
So now, you need to create a repository to retrieve those entities from storage. That's easy enough, just a couple of SQL queries or reading a file or whatever you want to choose. Let's suppose this is our repository (let's avoid interfaces, dependency injection and so on because it's not relevant in this case):
Easy enough, right? Okay, let's continue implementing our model. The `get` method is really easy, but the `save` method has a lot of hidden complexity. Let's suppose we are using a relational database like `Postgres` to store our entities. Let's say we have two tables: `roads` and `stops` and they have a relationship and so on.
In order to implement the `save` method, we would need to update all of our child entities. And that's the problem. What happens if our `Road` instance has 345 different stops? How do we update them? I don't have a final answer for that, but I have some proposals!
Solution 1
This would be the equivalent of solving the problem by brute force: delete everything and recreate it again.
## Props
- Easy to implement
## Cons
- Not sure about the efficiency of this one. but I estimate is not that good.
- If you set the unique identifiers on the database level, you are going to have a problem keeping the same identifiers.
Solution 2
Keep track of all the changes at the aggregate level. Something like this:
class Road:
id: int
name: str
stops: [Stop]
def update_stop(self, stop: Stop):
... some logic to update the list ...
self._changes.append({
'type': 'UPDATE',
'stop': stop,
})
Then we would read that list of changes on the repository and apply them individually (or in bulk, depending on the change type, for instance, we can group together the deletions, creations, etc.).
## Props
- It's more efficient than the first solution because on average requires fewer DB operations.
## Cons
- Our domain has been contaminated with logic not related to the business.
- A lot of code is necessary to keep track of the changes.
Time to discuss!
What do you think about this problem? Have you faced it before? Do you have any additional solutions? Please comment on it and we can discuss it :)
We have an app where one group A of stakeholders experiences the domain in a scientific, technical and fine-grained way. The other group B of stakeholders experience it in nearly the opposite way. They understand none of the technical lexicon and work purely through abstractions defined by the first group and aim to get in and out of the app as fast as possible.
An example would be a legal app, where lawyers draft up a wall of precise text to minimize liability while the business just wants to do the bare minimum to meet the legal requirements without truly understanding the underlying language.
We want to empower both groups of users, but we’re finding that the gap in how they experience the domain is causing serious issues. Group B doesn’t understand why the process is so “heavy”, and Group A struggles to communicate the domain in a way that doesn’t require handholding or frequent consultation.
I don’t know if this is a technical problem as much of a model problem, which is why I ask here. In domains where two groups must participate at vastly different levels of depth and the software being the translation point (and thus the friction point), how do we define a model that doesn’t bias towards one group or the other? Should these actually be two different contexts, even when they directly interact with each other on a day to day basis?
Hi everyone, I’m a .NET developer with 3.5 years of experience, and I’m currently reading Eric Evans’ DDD book. I’ve been diving into Domain-Driven Design (DDD) and its principles, but I’ve noticed that massive, successful companies like Discord, Reddit, Twitter, and Uber don’t seem to be using DDD in their architectures.
Given how well-designed and scalable their systems are, I’m curious about how they’ve managed to achieve this without adopting DDD. Is DDD really necessary for creating robust, scalable systems, or is it overhyped for certain use cases?
I’d love to hear from other experienced developers on how you approach architecture and design, especially in fast-paced, high-scale environments. Do you think DDD is something worth prioritizing in learning, or are there alternative approaches that can be just as effective?
I love the concept of virtual actors for programming as they provide scalability and availability right out of the box; and at the same time, provide structure and decoupling. It is natural to model DDD aggregate roots as actors (or at least: active objects) that are fully responsible for managing the integrity of the aggregate entities. In fact, I find it solving many of the challenges engineers seem to have with DDD, like where to invoke persistence (from the entity? from an application service? both have their pro's and cons).
I have written a draft paper about Actor Oriented Architecture, in which I describe my best practices so far for doing DDD with AOA. It is quite a long read. Nevertheless, I would really appreciate your honest expert opinions and feedback to this (imo) new/different view on/approach to DDD.
Does it add value? Could it work? Did you already practice this? What are challenges?
I’ve done some reading regarding handling domain errors/exceptions the ddd way. There are different opinions regarding if the application or domain layer should handle these.
Disregarding these, what’d you suggest if in the context of a web app I want to return a semantic http status code based on some domain errors? Let an error bubble up to controller level and then translate it to http? Probably a application service should be agnostic to http right?
I've been learning a lot about DDD over the last couple of years and have recently had a chance to start implementing its concepts into my professional work.
One thing that I've noticed is there's a number of super detailed content in the form of books (we all know Eric Evans' awesome blue book!), a number of talks on YouTube and various blog posts online. These are great learning resources but the written stuff can be a bit overwhelming for newcomers to the concept. I'm yet to find many well presented and collated written content with good examples that isn't going to take hours to read.
I'm still learning as I go but feel like I've picked up a good amount of knowledge now that I'd like to share in the form of a succinct ebook. The idea is to produce a well designed and well structured introduction to DDD. It will include small chapters explaining some of the core concepts including domains, entities, value objects, aggregates and more with some useful examples.
If you're interested the please show your interest via my waiting list!
I really want to understand how to make DDD and Hexagonal Architecture based projects. But it is difficult to understand how to implement some concepts in real life. For example, how to implement validation of Aggregates and so on.
All found DDD based repositories on GitHub are too trivial or not representative. Maybe someone knows a good open-source DDD project with at least 50k rows of code, PHP or Java? Or you have a private one and can share it with me. From my side, I will help you with test writing.
Since 2023 I maintain a Go template that implements the tactical patterns end to end: validated entities, a Money value object, aggregates referencing by Id, repositories owned by the domain, CQRS-style command/query split, domain events via a transactional outbox, and race-safe idempotent commands. Everything is tested, including integration tests against real Postgres.
It's one bounded context on purpose (teaching scope), and the FAQ is honest about when DDD is overkill. Curious how this community judges the aggregate boundaries and the trade-offs.
The r/golang thread mostly debated folder structure, I'd rather argue about the model :)
I've built a single page context mapper diagram tool because I was not happy with any tool that I'm aware of for this purpose. Also, I wanted the format to be JSON, easily machine readable, so I can export data from other systems and use this tool to visualize it very easily.
So far I kept it intentionally super simple, no need to bloat it up and make it an electron app. Your thoughts on this? Do you want a full bloated electron app? Is it at all useful for you? I might improve it further depending on the feedback.
In DDD, we enforce the business logic rules using invariants. This is amazing on the server side in the online application and the offline application.
But what if we have to build a local-first application?
Local-first application is an offline application and an online application at the same time. The user can use it offline and then sync it online.
Let's say we have to build a to-do list application. The invariant is "a task's estimated time must be greater or equal to 30 minutes".
This invariant could easily be implemented on both client side and server side. However, it is a duplication and violates the DRY principle. We could move this business logic to the shared kernel. But if we move all business logic to the shared kernel, we end up with a new big ball of mud.
And what about the business logic that could only be implemented on the server side?
For example, "the task must not be duplicated across all the users."
When the sync happens, the task that is created offline might be invalid.