I read Fowlers description of Anemic Domain and I believe I have those symptoms. I have several objects doing nothing but passing data around in different packages. I also have several Services that pretty much handle all the behavior (executive functioning). I am starting to lose track of why and what i did and where to find certain tasks.
The application does what I want, but i wonder if i just have a procedural program in oo disguise. Perhaps I can never shake my procedural programming past? should I?
In MVC, Should I eliminate my services and spread that responsibility to my Controllers and Model Objects?
I appreciate analogies between MVC concepts and DDD conepts...
I think controllers should be relatively thin. Their job is mainly being taking the request, delegating it to the appropriate application services and determining the correct action result.
If you're feeling that your domain entities are overly anemic I would suggest going over your Services and determine whether that functionality belongs on an Entity instead. I found this was my biggest problem starting with DDD was that I would push all behavior to Services rather than critically thinking about whether this was something more appropriate on the Entity.
Why don't you try the Evans book as suggested in one of your previous questions?
Related
I watched some videos, read some blogs about it. SO has many questions and answers on that subject but I can not find anywhere exact answer for my question.
Almost every question and answer has a lack of usage context.
I have one middle sized, asp.net-mvc, monolith application which is running in one process on IIS. I want to (refactor and) go all the way with DDD (and CQRS without separated storage for reads and writes for now) but for me it looks like impossible mission without breaking some rules/guides/etc.
Bounded Context
For example I have more than one BCs. Each should not cross their boundaries which means should not share their storage. Right?
It is not possible if you use the whole known (everywhere scattered over the web) solution to work with NHibernate session and UoW.
Aggregate Root
Only one AR should be modified in one transaction. When others ARs are involved should introduce eventual consistency (if I remember those are Eric Evans words).
I try to do it but it is not easy in app like that. Pub/Sub not working as desired because if event is published then all subscribers are take their action within one transaction (NSB/MT does that way).
If event handlers wants to modify others ARs they should be executed in separated transactions, right?
Is it possible to deal with it in monolith application (application where whole code works in one process)?
It is not possible if you use the whole known (everywhere scattered
over the web) solution
[...]
if event is published then all subscribers are take their action
within one transaction
I think you're setting yourself useless and harmful constraints by trying to stick to some "state of the art".
Migrating an entire application to DDD + CQRS is a massive undertaking. Some areas of it don't have well-documented beaten paths yet and you'll probably have a fair bit of exploration to do. My best advice would be to stay at a reasonable distance from "the way people do things". Both in traditional ASP.Net web apps because mainstream practices often don't match the way DDD+CQRS works, and in CQRS itself because the case studies out there are few and far between and most probably very domain specific, with a tendency to advocate the use of heavy tools which may not make sense in your context.
You may need to think out of the box, adopt things incrementally and refrain from goldplating everything. You'll be better off starting with very simple implementations that suit your needs exactly than throwing a ton of tools and frameworks at your codebase.
For instance, do you really need a service bus or could a simple Observer pattern suffice ?
Regarding NHibernate, most implementations out there use a (single) Session Per Request approach, but just because it's the most popular doesn't mean it's the only one. Have you tried using multiple ISessions (one for each BC) available at a more programmable level, such as per-action, or managed entirely manually ? Conversely, have you considered sharing a database between Bounded Contexts at first and see for yourself if that's bad or not ?
I'm specifically referring to this question:
DDD - How to implement factories
The selected answer has stated:
"factories should not be tied with dependency injection because domain objects shouldn't have dependencies injected into them."
My question is: what is the reasoning of not being able to inject dependencies in to your entities? Or am I just misunderstanding the statement? Can someone please clarify?
Kind of old, but I really want to address this because I've been running into this a lot, and express my opinion on it:
I often hear that Domain Objects should not "depend" on things. And this is true. I often see people extrapolate this to mean we should not inject things into domain object.
That's the opposite of what dependency means. The domain shouldn't depend on other projects, this is true. But, the domain can define its own interfaces which other projects may then implement, which can then be injected back into the domain. As we all know, that's what is called Dependency Inversion (DI).
That is literally the opposite of having a dependency. Not allowing DI into the domain completely hamstrings your ability to accurately model the domain, forces odd SRP violations, and pretty much kills the usability of domain services.
I really feel like I must be the crazy one here, because I feel like everyone reads "the Domain must not have any dependencies" then thinks "being injected with something means you are dependant on it" and comes to the conclusion "therefore we can't inject dependencies into the domain.
That leaves us with the wonderful logic:
Dependency Inversion == Dependency
Domain Objects aren't Factories, Repos, etc. They are only Entities, Value Objects, Domain Services and Aggregate Roots. That is, they must be classes which encapsulates the data your business domain uses, the relationships between them, and the behaviour(read modifications) that the domain can do on that data.
Repository is a pattern to abstract away the persistence infrastructure you are using. It's in DDD because it makes your app decoupled from your database, but not all DDD app need or even should use repository.
Factory is a pattern to isolate the construction logic of objects. It's also just a good practice that DDD recommends, but not really needed in all scenarios.
Domain Objects shouldn't depend on anything else, because they are the core of your app. Everything will depend on them. So keeping them free of other dependency makes a clear one way dependency chain, and reduces the dependency graph. They are the invariants, the model, the foundation. Change them, and you probably need to change a lot of stuff. So changing other things shouldn't force them to change.
Domain objects should not have many dependencies.
By Fowler's Tell-Don't-Ask principle (https://martinfowler.com/bliki/TellDontAsk.html), you would want the domain objects to do as much as possible. Including having dependencies. But in Clean Code (Uncle Bob) Chapter 6, it mentions it can be a good design to have data structures operated on by procedure/function classes (services). As long as you don't have hybrid objects which combine simple getters/setters as well as more complex tell-don't-ask operations.
Fowler disagreed with thin models and called it an antipattern - AnemicDomainModel. https://www.martinfowler.com/bliki/AnemicDomainModel.html
I disagree with Fowler. I strongly agree with the following quote from another article about this Fat-Models problem: "Following this logic basically every behaviour would end up in the model classes. This is something that we know (by experience) is a bad idea. Hundreds or thousands of lines of code crammed into a single class is a recipe for disaster. Service Objects grew out of this frustration." - https://tmichel.github.io/2015/09/14/oo-controversies-tell-dont-ask-vs-the-web/
We actually have a project with fat domain models which has this exact problem. As requirements change over time and code gets more complex, a huge, fat model is quite inflexible to perform different operations and handle new requirements. Instead of adding new service workflow paths (classes) acting differently on the same simple data model, you have to make expensive, difficult refactors on the enormous, complicated domain model. It encapsulates the data and prevents anyone from modifying the data in unexpected ways but at the same time, it makes it really difficult for new workflow to manipulate the data in new ways.
I'm building a MVC4 app, I've used EF5 model first, and kept it pretty simple. This isn't going to a huge application, there will only ever be 4 or 5 people on it at once and all users will be authenticated before being able to access any part of the application, it's very simply a place order - dispatcher sees order - dispatcher compeletes order sort of application.
Basically my question is do I need to be worrying about repositories and ViewModels if the size and scope of my application is so small. Any view that is strongly typed to a domain entity is using all of the properties within that entity. I'm using TryOrUpdateModel in my controllers and have read some things saying this can cause a lot of problems, but not a lot of information on exactly what those problems can be. I don't want to use an incredibly complicated pattern for a very simple app.
Hopefully I've given enough detail, if anyone wants to see my code just ask, I'm really at a roadblock here though, and could really use some advice from the community. Thanks so much!
ViewModels: Yes
I only see bad points when passing an EF Entities directly to a view:
You need to do manual whitelisting or blacklisting to prevent over-posting and mass assignment
It becomes very easy to accidentally lazy load extra data from your view, resulting in select N+1 problems
In my personal opinion, a model should closely resembly the information displayed on the view and in most cases (except for basic CRUD stuff), a view contains information from more than one Entity
Repositories: No
The Entity Framework DbContext already is an implementation of the Repository and Unit of Work patterns. If you want everything to be testable, just test against a separate database. If you want to make things loosely coupled, there are ways to do that with EF without using repositories too. To be honest, I really don't understand the popularity of custom repositories.
In my experience, the requirements on a software solution tend to evolve over time well beyond the initial requirement set.
By following architectural best practices now, you will be much better able to accommodate changes to the solution over its entire lifetime.
The Respository pattern and ViewModels are both powerful, and not very difficult or time consuming to implement. I would suggest using them even for small projects.
Yes, you still want to use a repository and view models. Both of these tools allow you to place code in one place instead of all over the place and will save you time. More than likely, it will save you copy paste errors too.
Moreover, having these tools in place will allow you to make expansions to the system easier in the future, instead of having to pour through all of the code which will have poor readability.
Separating your concerns will lead to less code overall, a more efficient system, and smaller controllers / code sections. View models and a repository are not heavily intrusive to implement. It is not like you are going to implement a controller factory or dependency injection.
I like to strive for DRY, and obviously it's not always possible. However, I have to scratch my head over a concept that seems pretty common in MVC, that of the "View Model".
The View Model is designed to only pass the minimum amount of information to the view, for both security, maintainability, and testing concerns. I get that. It makes sense.
However, from a DRY perspective, a View Model is simply duplicating data you already have. The View Model may be temporary, and used only as a DTO, but you're basically maintaing two different versions of the same model which seems to violate the DRY principal.
Do View Models violate DRY? Are they a necessary evil? Do they do more good than bad?
This has been brought up time and time again. Not only is it a pretty substantial dupe but the answer is subjective and argumentative. ViewModels are a response to DDD and the concept of persistence ignorance.
To say not using ViewModels is bad means ignoring that Django and Rails and most PHP ORM/MVC frameworks don't care at all about those concepts. Do you want somebody to tell you all those other languages and frameworks are "doing it wrong?".
Whether or not you want to use ViewModels is 100% dependent on what architecture styles you are going for and what the goals of the application are.
This is like asking is dragging and dropping GridViews in a WebForm app appropriate? Depends on a lot of things.
There is also a misconception about DRY that you have here. Do Proxy classes from a WCF service violate DRY? Does the ViewModel contain logic? The primary goal of DRY is to not have duplicated logic with a meaningful purpose. Do a couple of DTOs that share object shapres violate that?
The DDD principal of bounded contexts would make for a good read too. If a ShoppingCart object needs to function differently in a warehouse vs ecommerce website setting does that mean you to share the types? What happens when the only shared functionality is totaling a price ( price + tax + shipping )? Do you create a base class just for that therefore increasing coupling? What are the tradeoffs in time/cost/maintenance for being 100% DRY for a simple method like GetTotal(). Does violating DRY when it makes sense actually decreasing the complexity and overall cost of maintaining your codebase?
I'm sorry for answering with so many questions but hopefully now you can see the nuances and intricacies of the question you asked. ;)
One could also note that not using view models would be a violation of the single responsibility principle -- your entity should not be polluted with UI concerns.
I also think the real value of view models doesn't necessarily become apparent in version 1.0 of your application. You will thank yourself when working on version 2.0 when you completely re-think how your back-end works but you don't have to carry those changes out to the view layer.
I am planning to build a web application using ASP MVC3 that runs on Azure with a SQL Azure back end. I would like to use the Microsoft stack and have no plans to ever change to another stack. I am looking into the use of WCF and WF but that would be in the future.
I looked at the traditional and Code First approach to using Entity Framework but I can't see if there is any advantage in using one or the other approach. Sure they each have advantages but for me I don't care if my classes do inherit from EF classes. All I want is to find the most efficient solution.
Can anyone out there give me some advice as to which approach might be the best.
thanks very much
Richard
This is really more of an opinion gathering question and probably belongs more to the Programmers site of StackExchange, but I'll take a stab:
I am definitely a traditional approach kind-of-a-guy. To me, data is key. It is most important. Various objects, layers, applications, services come, go and evolve. But data lingers on. Which is why I design my databases first. In my experiences, data has always been king.
I'd go with Code First approach.
This great blog post by Scott Guthrie explains its advantages.
Code first for me also. If you suddenly started to hate Entity Framework and wanted to switch to NHibernate you will have a lot less work on your hands.
Also, there is a cleaner separation of concerns by totally isolating your domain layer from your data access layer.
I am not 100% sure it still applies, but I think the code generation, partial class malarky of entity framework can cause problems when testing.
Did I mention code first is a lot less hassle.
Code First is an "Architecturally correct" approach, but reality tends to differ on these things when you have to consider effort, value, and speed of developement.
Using the "Model First" approach is much faster and easier to maintain. Database changes propagate with a simple right click "Regen from database", you don't get strange errors creeping into your code when you forget to change a property name or type.
Having said that you can have a bit of both with the the new POCO support in EF4. You can remove the dependencies on base classes while at the same time use the modelling tools:
A lot of good links in this thread:
Entity Framework 4 / POCO - Where to start?