How to Organise a Domain Driven Design Project? - domain-driven-design

I've started learning about DDD and wanted to know how others have organised their projects.
I've started off by organising around my AggregateRoots:
MyApp.Domain (namespace for domain model)
MyApp.Domain.Product
- Product
- IProductService
- IProductRepository
- etc
MyApp.Domain.Comment
- Comment
- ICommentService
- ICommentRepository
- etc
MyApp.Infrastructure
- ...
MyApp.Repositories
- ProductRepository : IProductRepository
- etc
The problem i've bumped into with this is that i have to reference my domain product as MyApp.Domain.Product.Product or Product.Product. I also get a conflict with my linq data model for product....I have to use ugly lines of code to distiguish between the two such as MyApp.Domain.Product.Product and MyApp.Respoitories.Product.
I am really interested to see how others have organised their solutions for DDD...
I am using Visual Studio as my IDE.
Thanks alot.

I try to keep things very simple whenever I can, so usually something like this works for me:
Myapp.Domain - All domain specific classes share this namespace
Myapp.Data - Thin layer that abstracts the database from the domain.
Myapp.Application - All "support code", logging, shared utility code, service consumers etc
Myapp.Web - The web UI
So classes will be for example:
Myapp.Domain.Sales.Order
Myapp.Domain.Sales.Customer
Myapp.Domain.Pricelist
Myapp.Data.OrderManager
Myapp.Data.CustomerManager
Myapp.Application.Utils
Myapp.Application.CacheTools
Etc.
The idea I try to keep in mind as I go along is that the "domain" namespace is what captures the actual logic of the application. So what goes there is what you can talk to the "domain experts" (The dudes who will be using the application) about.
If I am coding something because of something that they have mentioned, it should be in the domain namespace, and whenever I code something that they have not mentioned (like logging, tracing errors etc) it should NOT be in the domain namespace.
Because of this I am also wary about making too complicated object hierarchies. Ideally a somewhat simplified drawing of the domain model should be intuitively understandable by non-coders.
To this end I don't normally start out by thinking about patterns in much detail. I try to model the domain as simple as I can get away with, following just standard object-oriented design guidelines. What needs to be an object? How are they related?
DDD in my mind is about handling complex software, but if your software is not itself very complex to begin with you could easily end up in a situation where the DDD way of doing things adds complexity rather than removes it.
Once you have a certain level of complexity in your model you will start to see how certain things should be organised, and then you will know which patterns to use, which classes are aggregates etc.
In my example, Myapp.Domain.Sales.Order would be an aggregate root in the sense that when it is instanced it will likely contain other objects, such as a customer object and collection of order lines, and you would only access the order lines for that particular order through the order object.
However, in order to keep things simple, I would not have a "master" object that only contains everything else and has no other purpose, so the order class will itself have values and properties that are useful in the application.
So I will reference things like:
Myapp.Domain.Sales.Order.TotalCost
Myapp.Domain.Sales.Order.OrderDate
Myapp.Domain.Sales.Order.Customer.PreferredInvoiceMethod
Myapp.Domain.Sales.Order.Customer.Address.Zip
etc.

I like having the domain in the root namespace of the application, in its own assembly:
Acme.Core.dll [root namespace: Acme]
This neatly represents the fact that the domain is in scope of all other portions of the application. (For more, see The Onion Architecture by Jeffrey Palermo).
Next, I have a data assembly (usually with NHibernate) that maps the domain objects to the database. This layer implements repository and service interfaces:
Acme.Data.dll [root namespace: Acme.Data]
Then, I have a presentation assembly declaring elements of my UI-pattern-of-choice:
Acme.Presentation.dll [root namespace: Acme.Presentation]
Finally, there is the UI project (assuming a web app here). This is where the composition of the elements in preceding layers takes place:
Acme.Web [root namespace: Acme.Web]

Although you're also a .Net developer, the Java implementation reference of the cargo app from DDD by Eric Evans and Citerus is a good resource.
In the doc'd code, you can see the DDD-organization into bounded contexts and aggregates in action, right in the Java packages.
Additionally, you might consider Billy McCafferty's Sharp Architecture. It's an ASP.Net MVC, NHibernate/Fluent NHibernate implementation that is built with DDD in mind.
Admittedly, you will still need to apply a folder/namespace solution to provide the contexts. But, couple the Evans approach with #Arch and you should be well on your way.
Let us know what you are going with. I am on the same path as well, and not far from you!
Happy coding,
Kurt Johnson

Your domain probably have a
name, so you should use this
name as namespace.
I usally put repository
implementation and data access
details in a namespace called
Persistance under the domain
namespace.
The application use its own name
as namespace.

I'd check out codecampserver since the setup there is quite common.
They have a core project in which they include both the application and domain layers. I.e. the insides of the onion (http://jeffreypalermo.com/blog/the-onion-architecture-part-1/).
I actually like to break the core apart into separate projects to control the direction of dependency. So typically I have:
MyNamespace.SomethingWeb <-- multiple UIs
MyNamespace.ExtranetWeb <-- multiple UIs
MyNamespace.Application <-- Evans' application layer with classes like CustomerService
MyNamespace.Domain
MyNamespace.Domain.Model <-- entities
MyNamespace.Domain.Services <-- doman services
MyNamespace.Domain.Repositories
MyNamespace.Infrastructure <-- repo implementation etc.
MyNamespace.Common <-- A project which all other projects have a dependency to which has things like a Logger, Util classes, etc.

Related

Can I say Axon Commands and Events are considered as anemic models?

My question here is quite straight as mentioned in the subject.
However, please allow me to give some brief explanation here about my innocent thoughts.
I've been using Axon for approximately 10 months now. I used to design my project structure based on the Hexagonal architecture with two top level packages respectively for domain and infrastructure.
Furthermore, domain package will contain different domain objects (as explained in the DDD concept) such as follow:
Aggregate (this will be an Axon aggregate class).
Repository (in my case, this will be a Spring Data Repository interface).
Entity (in my case, this contains any lookup entity that i used for set-based consistency validation as written here).
Service Port (collection of Input and Ouput port interfaces).
Commands (representing Axon Command object).
As for Events, I used to put them on a different module that I compiled as a jar file, so I can share it to other developers whom going to use the same event in their project.
I've noticed recently that all of my commands and events were basically anemic models (an anti pattern that we should avoid).
Is there any good practice on this ? Or, Is it something that intentionally used by design ?
I've been thinking to put my Command classes within my Aggregate class (as an inner classes). At least by using this approach I won't end-up with having so many anemic models scattered outside. Any thoughts ?
Commands are designed to be behavior and input structures mirroring the external world. They don't necessarily mirror an aggregate's structure.
They are not even connected clearly to one single aggregate, at times. Enclosing them within aggregates can be a code smell because you are then thinking in terms of resources and UI organization, instead of transaction boundaries and entity groups.
You are also violating the open-closed principle. Changes in volatile layers like user interface and request structures will make you edit the Aggregate class, and that is not good design.
On a more general note...
At times, this debate of anemic vs. non-anemic (or dry vs. non-dry) can push you in the direction of premature - and incorrect - optimization. Try avoiding this trap because you will end up optimising at the code level, but your domain will suffer.
DDD and CQRS guidelines align with principles that help you keep complexity at bay over the long term. Things kept distinct and separate help you achieve this.
First of all, in DDD, your domain had to be free of any frameworks, just use pure language library.
Then, mixing Commands and Aggregates cannot be a good solution. I think Commands belongs to Port while Aggregates belongs to the Hexagone.
Finally, DDD highlights the discovery of the domain thanks to the experts. Did you do that ? If not, if you're only using the Tacticts pattern, you'll miss one of the most important part of DDD.

DDD : can I start from UI designs to design my domain?

I'm new to Domain Driven Design, and I'm reading a lot about it. I started a first implementation of what I consider to respect DDD principles.
But now, I'm wondering something : to define the sub domains and contexts, I started from well defined UI designs. They describe well every steps that take when you want to interact with the app.
Do you think it is a good start point (of course, I also got close from the domain experts) ? I mean, UI's define the Use Cases no ?
An example :
You have an administration panel, and from this panel, you can manage companies. So, I conclued that my sub-domain is Administration/ and one of its context is Company/.
So I end up with something like this :
src/
Administration/
Company/
Domain/
Command/
Ports
Is it poor designed Domain ?
I'd really like to have your opinions about this please.
Have a nice day.
------- edit ------
As #Luca Masera said, My example was a little bit too tiny.
So to give more example, I would have ended up with something like :
src/
Administration/
Company/
Domain/
Company.model
Employees.collection
Commands/
AddEmployeeToCompany.command
GetAllEmployeesForACompany.query
[...]
Employees/
Domain/
Commands/
[...]
FrontEnd/ <--- didn't really think about the naming yet
Contracts/
Domain/
Contract.model
CompanyId.id
Employee.model
Commands/
ChangeContractForEmployee.command
Actually I don't really understand, because you've made only a single sample, if you end up splitting the same domain on each ui area. What I know is that the ui defines the use cases, but how they are implemented should not define the design of the domain.
If you have an Administration and, for example, a Frontend, and you split the Company domain between the two, then the answer is no, it's not ok. The Company domain should have all its logic enclosed in a single package, not scattered around several context.
For example, in my last application I've to manage the user Absences. There're several types of them: holidays, maladies, exemptions and some others. I've also another concept, the Prospects: they cone from a sub-system and give general information for each type of Absence.
When the users starts the application, the first entry point is in the Prospects domain. The ui loads the page and then, with the help of Javascript and Ajax it asks a section of the page to each other domain. Every further interaction with the domain is managed by the ui (implemented in the infrastructure layer) of that domain.
--- After the editing ---
I would not do something like this. As I wrote before, in this way you end up splitting the domain logic in each macro area. Hence you loose all the advantages of the DDD.
I elaborate a bit more: what would you do when, later, in the Administration you need something about the Contracts?
Whatever architecture you use, you'll have:
src/
contracts/
infrastructure/
*** My way to manage the UI interactions ***
ui/
frontendA/ (it could be *hr_team*)
frontendB/ (it could be *managers*)
frontendC/ (it could be *employers)
application/
domain/
companies/
infrastructure/
*** My way to manage the UI interactions ***
ui/
frontendA/ (it could be *hr_team*)
frontendB/ (it could be *managers*)
*** no employers actions are planned ***
application/
domain/
Into the infrastructure you'll implement the Controllers that allow to interact with the Domain using the code inside the application layer. There're some overlapping here and there with the roles (some employers could be managers, some other part of the hr_team) but not with the functionalities.
In this way you still keep the logic of the domain (contracts) all together, but you end up with a nice splitting of the functionalities for each role.

DDD domain services: what should a service class contain?

In Domain Driven Design, domain services should contain operations that do not naturally belong inside an entity.
I've had the habit to create one service per entity and group some methods inside it (Organization entity and OrganizationService service).
But the more I think about it: OrganizationService doesn't mean anything, "Organization" is not a service, it's a thing.
So right now I have to add a Organization deep copy functionality that will duplicate a whole Organization aggregate, so I want to put it in a service.
Should I do: OrganizationService::copyOrganization(o)?
Or should I do: OrganizationCopyService::copyOrganization(o)?
More generally: is a "service" an abstract concept containing several operations, or is a service a concrete operation?
Edit: more examples given the first one wasn't that good:
StrategyService::apply()/cancel() or StrategyApplicationService::apply()/cancel()? ("Application" here is not related to the application layer ;)
CarService::wash() or CarWashingService::wash()?
In all these examples the most specific service name seems the most appropriate. After all, in real life, "car washing service" is something that makes sense. But I may end up with a lot of services...
*Note: this is not a question about opinions! This is a precise, answerable question about the Domain Driven Design methodology. I'm always weary of close votes when asking "should I", but there is a DDD way of doing things.*
I think it's good if a domain service has only one method. But I don't think it is a rule like you must not have more than one method on a domain service or something. If the interface abstracts only one thing or one behaviour, it's certainly easy to maitain but the granularity of the domain service totally depends on your bounded context. Sometimes we focus on low coupling too much and neglect high cohesive.
This is a bit opinion based I wanted to add it as a comment but ran out space.
I believe that in this case it will make sense to group the methods into one a separate OrganizationFactory-service with different construction method.
interface OrganizationFactory{
Organization createOrganization();
Organization createOrganizationCopy(Organization organization);
}
I suppose it will be in accordance with information expert pattern and DRY principle - one class has all the information about specific object creation and I don't see any reason to repeat this logic in different places.
Nevertheless, an interesting thing is that in ddd definition of factory pattern
Shift the responsibility for creating instances of complex objects and
AGGREGATES to a separate object, which may itself have no
responsibility in the domain model but is still part of the domain
design. Provide an interface that encapsulates all complex assembly
and that does not require the client to reference the concrete classes
of the objects being instantiated.
the word "object" is in a generic sense doesn't even have to be a separate class but can also be a factory method(I mean both the method of a class and the pattern factory method) - later Evans gives an example of the factory method of Brokerage Account that creates instances of Trade Order.
The book references to the family of GoF factory patterns and I do not think that there's a special DDD way of factory decomposition - the main points are that the object created is not half-baked and that the factory method should add as few dependecies as possible.
update DDD is not attached to any particular programming paradigm, while the question is about object-oriented decomposition, so again I don't think that DDD can provide any special recommendations on the number of methods per object.
Some folks use strange rules of thumb, but I believe that you can just go with High Cohesion principle and put methods with highly related responsibilities together. As this is a DDD question, so I suppose it's about domain services(i.e. not infrastructure services). I suppose that the services should be divided according to their responsibilities in the domain.
update 2 Anyway CarService can do CarService::wash()/ CarService::repaint() / CarService::diagnoseAirConditioningProblems() but it will be strange that CarWashingService will do CarWashingService::diagnoseAirConditioningProblems() it's like in Chomsky's generative grammar - some statements(sentences) in the language make sense, some don't. But if your sentence contains too much subjects(more than say 5-7) it also will be difficult to understand, even if it is valid sentence in language.

Naming of domain objects that act like ddd building blocks such as repositories

When comming accross concepts within a Domain Model where there exists something that has a name and sounds like an object but overlaps with the responsiblility of one of the 5 main DDD building blocks what is the best practice for naming this object and or dealing with design which may or may not include that name or phrase in the actual implementation?
To give a more concrete example lets say that we are designing a time tracking application in the spirit of DDD and encounter something that the domain experts refer to as a "time log" which is supposed to be the log which holds punch-in and corresponding punch-out times for all employees.
With this information my initial thought is that if there were a class written called TimeLog which allowed for querying existing time entries and also for persisting new or amended time log entries that such a class is really playing the role of a DDD repository. For simplicity sake, lets assume that after various discussions and refactoring that we come to a conclusion that each time log entry is essentially it's own aggregate root and thus has the need for a corresponding repository.
Now we are left with the option of either naming our repository as TimeLog which seems more in line with the DDD concept of ubiquitous language or we could call it TimeLogEntryRepository which seems to fit the more general convention for naming Repositories after the Aggregate root that they query/persist. I'm leaning more towards the the idea of using TimeLog since it is more descriptive of the actual role that it plays in the domain model which should in turn help in communicating design to domain experts. The choice of using TimeLogEntryRepository on the other hand follows existing DDD conventions and thus would make the design easier to follow for developers. A compromise could also be to go with the TimeLog naming but to have all repositories implement an IRepository interface or inherit from a common Repository base class to help developers locate and distinguish repository classes from others that make up the domain model. The main concern I have with using a base class is that it may encourage the use of marker interfaces or a weak unnecessary base class just for the purpose of organization and not due to behavioral factors.
What is the best practice in cases like this? I can see the same type of issue perhaps happening for services as they are another piece of the typical DDD building blocks that developers typically name using a "Service" suffix such as in SomeComplexActivityService but for Entities and Value Objects this is really a non-issue. I'm especially interested to see what others may have to say that have more DDD experience under their belt.
I personally prefer TimeLog.
It's actually amazing how much easier it becomes once you switch focus to business instead of technology. Proper naming is main weapon to keep that focus sharp.
The same goes for services - instead of ApplicationRegistrationService, I use ApplicationRegistrator.
Here's quite nice article about repositories.
I second #Arnis L. suggestion. I would also add that in respect to DDD your domain should reflect the actual UL (Ubiquitous Language) which you share with business analysist and other people that are often non technical people. So I think that you will talk with them about TimeLog and not TimeLogEntryRepository. Repository is just a pattern and it's name should not be in the naming conventions.

DDD what all terms mean for Joe the plumber who can't afford to read books few times?

I am on a tight schedule with my project so don't have time to read books to understand it.
Just like anything else we can put it in few lines after reading books for few times. So here i need some description about each terms in DDD practices guideline so I can apply them bit at a piece to my project.
I already know terms in general but can't put it in terms with C# Project.
Below are the terms i have so far known out of reading some brief description in relation with C# project. Like What is the purpose of it in C# project.
Services
Factories
Repository
Aggregates
DomainObjects
Infrastructure
I am really confused about Infrastructure, Repository and Services
When to use Services and when to use Repository?
Please let me know if anyway i can make this question more clear
I recommend that you read through the Domain-Driven Design Quickly book from infoq, it is short, free in pdf form that you can download right away and does its' best to summarize the concepts presented in Eric Evan's Blue Bible
You didn't specify which language/framework the project you are currently working on is in, if it is a .NET project then take a look at the source code for CodeCampServer for a good example.
There is also a fairly more complicated example named Fohjin.DDD that you can look at (it has a focus on CQRS concepts that may be more than you are looking for)
Steve Bohlen has also given a presentation to an alt.net crowd on DDD, you can find the videos from links off of his blog post
I've just posted a blog post which lists these and some other resources as well.
Hopefully some of these resources will help you get started quickly.
This is my understanding and I did NOT read any DDD book, even the holy bible of it.
Services - stateless classes that usually operate on different layer objects, thus helping to decouple them; also to avoid code duplication
Factories - classes that knows how to create objects, thus decouple invoking code from knowing implementation details, making it easier to switch implementations; many factories also help to auto-resolve object dependencies (IoC containers); factories are infrastructure
Repository - interfaces (and corresponding implementations) that narrows data access to the bare minimum that clients should know about
Aggregates - classes that unifies access to several related entities via single interfaces (e.g. order and line items)
Domain Objects - classes that operate purely on domain/business logic, and do not care about persistence, presentation, or other concerns
Infrastructure - classes/layers that glue different objects or layers together; contains the actual implementation details that are not important to real application/user at all (e.g. how data is written to database, how HTTP form is mapped to view models).
Repository provides access to a very specific, usually single, kind of domain object. They emulate collection of objects, to some extent. Services usually operate on very different types of objects, usually accessed via static methods (do not have state), and can perform any operation (e.g. send email, prepare report), while repositories concentrate on CRUD methods.
DDD what all terms mean for Joe the plumber who can’t afford to read books few times?
I would say - not much. Not enough for sure.
I think you're being quite ambitious in trying to apply a new technique to a project that's under such tight deadlines that you can't take the time to study the technique in detail.
At a high level DDD is about decomposing your solution into layers and allocating responsibilities cleanly. If you attempt just to do that in your application you're likely to get some benefit. Later, when you have more time to study, you may discover that you didn't quite follow all the details of the DDD approach - I don't see that as a problem, you proabably already got some benefit of thoughtful structure even if you deviated from some of the DDD guidance.
To specifically answer your question in detail would just mean reiterating material that's already out there: Seems to me that this document nicely summarises the terms you're asking about.
They say about Services:
Some concepts from the domain aren’t
natural to model as objects. Forcing
the required domain functionality to
be the responsibility of an ENTITY or
VALUE either distorts the definition
of a model-based object or adds
meaningless artificial objects.
Therefore: When a significant process
or transformation in the domain is not
a natural responsibility of an ENTITY
or VALUE OBJECT, add an operation to
the model as a standalone interface
declared as a SERVICE.
Now the thing about this kind of wisdom is that to apply it you need to be able to spot when you are "distorting the definition". And I suspect that only with experience (or guidance from someone who is experienced) do you gain the insight to spot such things.
You must expect to experiment with ideas, get it a bit wrong sometimes, then reflect on why your decisions hurt or work. Your goal should not be to do DDD for its own sake, but to produce good software. When you find it cumbersome to implement something, or difficult to maintain something think about why this is, then examine what you did in the light of DDD advice. At that point you may say "Oh, if I had made that a Service, the Model would be so nmuch cleaner", or whatever.
You may find it helpful to read an example.:

Resources