Validation in a DDD world

It’s a common question, “Where do I put validation?”  Simple answer: put it where it’s needed.

But it’s not just a question of “where”, but of “when”, “what” and “why”.  If we treat our entities as data holders, we might think to put all of our validation there, in the form of reactive validation, where the entity is allowed to be put into an “invalid” state.

Validation depends completely on the context of the operation you’re trying to perform.  If we start looking at command/query separation and closure of operations not only on our service objects but our entities as well, we can treat our entities with a little more respect and not drag them around into areas they don’t really belong.  Simply put, if we control the operation side of the equation, why in the world would we allow our entities to get into an invalid state?  Life becomes much more complicated if we start having “IsValid” properties on our entities.

Think about that question, “is this entity valid”.  You can’t answer that question unless you know the context for validation.  Are you validating for persistence?  For changing an attribute?  For changing state (in the state pattern)?  For ETL?

In our current application, we have at least 3 different well-known locations for validation:

  • On our messages
  • In a command object
  • In our entities, for ETL scenarios

For about 5 seconds we considered trying to combine all of this validation into one grand uber-validator rules engine.  Ha. ha. ha.

Worst-case scenario

In the absolute worst case, we would have validation on our entities.  Something like an “IsValid” property or a “Validate” method.  Because we need to make judgment calls on what you’re trying to validate, things can get messy.  If all of your validation is on your entity, why are you even doing the Domain Model pattern in the first place?  Validation directly on entities is more suited for CRUD-y applications, where patterns like Active Record are more appropriate.

If you let your entities become invalid, you’ve most likely lost the context of what operation was being performed on the entity on the first place.  An entity may change state for a wide variety of reasons for a wide variety of operations, so certain attributes may be valid in one operation and invalid in the next.

Imagine an Order class that has several valid states, New, Confirmed, Placed and so on.  Often, we’ll place certain validation in the context of state changes, such as when an order is New versus moved from New to Confirmed.

Suppose we want to require a PhoneNumber for New orders.  But someone comes in that literally does not have a PhoneNumber, which our sales rep confirms through an email.  The Confirmed Orders are therefore allowed to have a blank PhoneNumber.  Are we supposed to capture all of this in a single Validate method?  I certainly hope not.

If you have to put validation on an entity, make sure you capture the context of what the operation the validation is operating against, likely in the name of the method.  For loading or ETL scenarios, I could imagine an IValidateForLoading interface that entities could opt-in to, just in the case where we don’t have control over hydrating the entity from bad data.

Thinking operationally

Instead of thinking of changing state on an entity, we need to move up to a higher level of command/query separation, where we perform and execute commands on one or many entities.  Am I performing validation, or reporting the result of an operation?  Lately, I’ve tended to go with the latter.

In that case, validation can take many forms.  I can use Castle Validators on my message object, to ensure that certain fields are required, this date can’t be in the future, and so on.  In my Command object, I’ll do further business rule validation, where I might need to coordinate between several different entities to determine if this operation can be performed successfully.

And that’s where I think we should move towards in terms of validation.  Instead of answering the question, “is this object valid”, try and answer the question, “Can this operation be performed?”.

Because our command objects know answers to all of the “Who, what, why” questions, they are in the best position to perform contextual validation based on the operation the user is trying to execute.

Validation doesn’t belong in one place, nor should they be constrained to one technology.  Validation belongs as close to the operation being performed as possible, to minimize risk of contaminating our entities with bad data or blurring its cohesion.

Summing it up

If I could look back at one thing that improved my take on validation the most, it’s adherence to a closure of operations.  I’d encourage you to go back to those sections on command/query separation and closure of operations in the Big Blue Book.  Once I adhered to those two concepts, validation was merely another step in reporting the success or failure of an operation, and like many good simplifications, a host of symptoms I mistook for separate diseases just went away.

About Jimmy Bogard

I'm a technical architect with Headspring in Austin, TX. I focus on DDD, distributed systems, and any other acronym-centric design/architecture/methodology. I created AutoMapper and am a co-author of the ASP.NET MVC in Action books.
This entry was posted in DomainDrivenDesign. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • Michael Hart

    “If all of your validation is on your entity, why are you even doing the Domain Model pattern in the first place? Validation directly on entities is more suited for CRUD-y applications, where patterns like Active Record are more appropriate.”

    What about cases when you put your validation in your entity constructor? Do you consider that an anti-pattern?

    I’ve been doing this to ensure my entities aren’t created in invalid states and it’s been working fine so far – but I’m interested to hear if there are some downsides to this. (obviously it doesn’t cover all validation scenarios, but still… it is validation done on the entitiy)

  • Thanks for this info, Jimmy! what you’re saying makes a lot of sense, and helps to answer some of the questions i posted, and validates some of the things i’ve been thinking and trying recently. i definitely need to go back and read up on the command query separation section.

  • @Michael

    It works inasmuch as the parameters communicate what is needed to create a transient instance. I’m not a fan, however, of exceptions telling users what is invalid, as it’s often input from a UI.

    I’ve gone back and forth from a ctor taking the required parameters. I think it’s just not a binary decision though, it really depends on the operations you need to support.

  • Cool beans. Your post has led my mind in some new directions regarding validation, I’ll be sure to read the suggested material, hopefully that will help to further illuminate my understanding.

  • Dennis Kozora

    After reading the numerous articles/comments etc from Derick, Sean etc. I figured I’d share the current approach I have decided to follow.

    First, the methodology I currently use has grown from the concepts JP Boodhoo has presented in the past. Furthermore, I do not like attribute driven validation frameworks nor do I like IValidatable.IsValid methods in my entities.

    Simply, I prefer just to have validator classes IValidator with Validate(T entity). These validators can then be injected into my services, presenters etc. Simplifies testing and makes the design pluggable.

    In my experience, coupling the validation into an entity can “paint yourself into a corner”. Take for example an Event Management system. Say you have a Registration aggregate. The Registration could be validated differently based upon its state. For example, consider the following progression of the registration in the enterprise: pending->processing->approved->imported into CRM. Each one of those “states” would likely require different validators and different validation logic. With IoC containers, its easy enough to load a validator based upon an entity state.

    “In an attempt” to manage “reactionary validation”, I follow an implementation which leverages “validation rules”. Those rules objects ultimately include lambda expressions, descriptions, names etc. The validators would then just leverage those rules inside its Validate method.

  • Michael Hart

    @Jimmy

    Indeed, and I’m not creating my entities from my UI, so I don’t run into this issue (nor am I using exceptions, preferring a Notification approach). I tend to have UI validation as close to the UI as possible, so I end up in a similar situation to what you’re talking about with multiple validation points – still trying to get comfortable with this approach though.

    I find it useful to have the validation on the constructor to ensure that re-hydrated entities and those created within the domain itself are always in a valid state. With the IValidateForLoading approach you were discussing, how does this work in terms of creation? Do you just ensure that you call the appropriate method during the constructor? Or is this some sort of post-loading hook for an ORM?

  • Michael Hart

    (also forgot to point out that for complex creation scenarios, a fluent Builder approach has worked well for us too – this gives you more flexibility over just having a constructor – and child entities, related entities, etc can be validated too)

  • Jimmy,

    For your next post, I would love to see a quick-and-dirty C# example outlining the concepts above for a common, everyday situation, e.g. ChangePassword or some other well-known scenario. Specifically what I’d like to see is how information relating to invalid inputs, etc. flows back to the UI.

    Regarding the “Closure of Operations” you mentioned, from what I remember this is a way of saying “XYZ in XYZ out”. This makes it sound as like you’re passing a simple DTO as a parameter of the command object and then evaluating a Boolean on a returned DTO of the same type for success/failure as well to determine which values on the DTO are invalid and/or missing.

  • @Michael

    We don’t really use it for creation, but that’s just us. Creation comes through a specific operation from the user side, so a factory or something similar is where we usually go.

    @Jonathan

    Closure of operations definitely needs its own post. Thanks for the suggestion!

  • T Moriarty

    @Dennis Kozora,

    “With IoC containers, its easy enough to load a validator based upon an entity state.”

    Are you implying that you are placing business/validation logic inside your IoC container?

  • Hey Jimmy,

    I’ve been trying to wrap my head around the validation concept.

    For example, I’m working on a system right now that tracks build numbers on products. I have a business rule that states numbers can’t go backwards. For example, I have product A which is version 1. Bob goes and makes it version 3. Alice comes along and tries to make it version 2. In my mind, this is clearly a business rule that belongs in the entity representing the product. But I need to communicate with Alice that she tried to “move backwards”.

    Right now, the product entity simply throws an exception. My application service knows how to handle that exception. But this feels like using an exception for flow control which is a huge smell to me.

    I’ve seen mentioned in several places a “Result” object. Is this basically a local context object that collects data as the domain is executed?

  • @Justin

    OperationResult is just for us a result of an operation. It has a Success property and an ErrorMessages property, as well contextual information.

  • @bogardj,

    How do you get the OperationResult back to the application service? Return it from the domain method? That doesn’t seem likely as you’d be constraining your domain model. Is it similar to what Udi defines in his “domain events”?

  • I’m not sure I see why it’s such a bad thing to have validation in the entity objects.

    I’ve worked on a bunch of thick client apps. In these apps, the user can change data in numerous different places, as opposed to a web app where you’re going to call a controller method or post to a page, etc.

    Even in a web app (let’s say I’m using an MVC framework), if I put my validation in my controller action methods, it’s possible that more than one controller could edit the same entity object and that I could need to put the same validation logic in more than one place. In some cases, I can see why the controller validation method makes sense.

    I’ve always done the IsValid() on the entity that throws an exception when IsValid() determines that the entity is not valid. I’m open to other ways, but I haven’t seen anything else yet. I’ve done the IValidator thing that another commenter mentioned, although I don’t totally see what I gain from doing it that way (at least for 95% of validation situations).

    If you have a better way than the way I’m doing it, I’d be interested in that post and specifically why you did it a certain way.

  • Not sure I agree with this post. You describe the validation within the domain as if its an awful idea and the examples you give make it sound ridiculous and not consistent with DDD but I don’t think thats in any way true:

    > If we treat our entities as data holders, we might think to
    > put all of our validation there, in the form of reactive
    > validation, where the entity is allowed to be put into
    > an “invalid” state.

    Not sure thats true, if you view your entities as behavioral then you ask them to do X and they tell you whether they are happy with this (bearing in mind their current state).

    > If all of your validation is on your entity, why are you even
    > doing the Domain Model pattern in the first place?
    > Validation directly on entities is more suited for CRUD-y
    > applications, where patterns like Active Record are more
    > appropriate.

    It definitely wouldn’t/couldn’t all be in your entity, not sure anyone would argue that. I’ve had this discussion with Greg a few times and I see the point and I like the always valid idea but I don’t think its that or you’re doing CRUD and shouldn’t be worried about a domain model.

    > Are we supposed to capture all of this in a single Validate
    > method? I certainly hope not.

    Don’t think anyone would recommend. Entities co-ordinate behavior, they should be kept light so in this case the validation method(s) would at most co-ordinate other objects. So if your Order does go through different states then each state class could have its own validaiton rules.

    > If you have to put validation on an entity, make sure you
    > capture the context of what the operation the validation is
    > operating against, likely in the name of the method

    Absolutely, but thats the key point…validation is entirely contextual. In some cases validation is an either/or thing, an aggregate is valid or it isn’t.

    However once you get interesting behavior involved its “valid for X”, which is in my view where the always valid approach and the normal approach draw together.

    > And that’s where I think we should move towards in terms
    > of validation. Instead of answering the question, “is this
    > object valid”, try and answer the question, “Can this
    > operation be performed?”.

    Absolutely, but thats true whatever approach you take. And one way to help with this is to move behavior into your domain model, including your entities (again though, they probably co-ordinate the behavior rather than containing the code). In that context it becomes “are you prepared to do X, no, OK I’ll report notification of reasons why” and then “do X, oh you’ve told me in no uncertain terms your not happy to participate in that behavior”.

    > In my Command object, I’ll do further business rule
    > validation, where I might need to coordinate between
    > several different entities to determine if this operation can
    > be performed successfully.
    > And that’s where I think we should move towards in terms
    > of validation. Instead of answering the question, “is this
    > object valid”, try and answer the question, “Can this
    > operation be performed?”.

    Not sure I like that, that mindset totally turns your entities into data-holders. Absolutely I agree on focussing on behavior, and co-ordinating that behavior, but moving it all into commands…na.

    > Because our command objects know answers to all of
    > the “Who, what, why” questions, they are in the best
    > position to perform contextual validation based on the
    > operation the user is trying to execute

    If its cross aggregate then I’d use a service (which I assume is similiar enough to be the same idea), if its within the boundaries of a single aggregate then I think the aggregate root itself has all it needs as long as the method you call is correct (“DoX”).

  • @Jimmy
    One question, when you talk about commands are you talking about command objects or command messages? I think its the former.

  • k03123

    hi jimmy,

    i read your post on validation at http://grabbagoft.blogspot.com/2007/10/entity-validation-with-visitors-and.html.

    i tried to post there and saw this blog and thought this is your new blog.

    anyway, in your example lets say Order has many OrderLines. for an Order to be valid for persistence, all the OrderLines also needs to be valid. now where does the validation of OrderLines belong?

    thanks

  • @k03123

    In that case, if Order completely manages the OrderLines, it might belong in Order. Or, in OrderLine, and Order calls Validate on each order line. Either way, I’d let the Inappropriate Intimacy smell guide you.

  • Arnis L.

    Just ignored this problem all the time. Seemed fine to add it where it was needed.

    At least now I’ll know what to say next time someone will ask me this question.

  • JRod

    If you are enforcing command query separation so that your domain model only contains behaviors, why wouldn’t you put the validation within each bahavior method? I dont see what is wrong with this. I think each method should be responsible for checking whether that operation can be performed and returning a summary of problems to the caller. Putting it anywhere else seems like your domain objects can be manipulated with no restrictions and possibly put in an invalid state. Does anyone see any downside to this approach?

  • Pingback: DDD:关于模型的合法性,Entity.IsValid()合理吗? – 幸福框架 | 查问题()

  • Josip
  • Tengiz Tutisani

    I don’t agree with this post. So, you’re saying you can change the state of the entity in any way you want, as long as the command (which is changing the entity) thinks it’s right? that’s not DDD.

    In DDD, you should Ask, don’t Tell the entity what’s right and what’s wrong. If the command is able to decide what’s right and what’s wrong about the entity’s state, then command can change the entity’s state without asking entity; so you have an anemic model, which I’m sure you know is not right.
    In DDD, only entity can change its own state, so the entity will have to decide on its own, if the change can be done.

    So, the right approach would be, you give the entity all the information about the change, and ask the entity to change its state based on that information. If entity decides it’s an acceptable change, the state will be changed. Otherwise, entity can give you a result that says why the requested change is not acceptable. That sounds more like DDD.

    You may rewrite this post, but this gives me an idea what NOT to do in DDD. Thank you for that!

    • jbogard

      Lots of good points!

      First, DDD is not about structural patterns, Evans makes that quite clear. It’s important not to get hung up on the OO part, that’s the least important part of DDD. In fact, Evans goes on to say we wishes he put all that entity/aggregate/repository business as an appendix!

      Second, we tried the approach you describe. It’s….painful. How does the entity communicate validation failure? Either a return object (success/fail), or an exception. Exception being the lousier choice. A return object – fine, but now I need to indicate which items are invalid, and how etc. Then this needs to be mapped back out to the UI. Those parts are not trivial, and decidedly not fun. And my god help us if you need to validate *across* entities. All sorts of “nopes” there.

      So instead, we go with more of a pipeline. Aggregates are consistency boundaries, so we need to make sure their state is consistent. As far as tell don’t ask, we’re asking the system as a whole to make a change, not a single entity or aggregate. Users don’t give a flying flip about entities or aggregates, they care about the state of the system.

      With a pipeline approach, commands flow in to the system, get authorized, validated, then passed to the entity.

      You might not like this, but it’s a simpler approach, which is what I prefer in the long run. Simple beats pedantic.

      • Tengiz Tutisani

        I understand, that’s your choice, and you can do however you feel better.
        As I already mentioned, if commands do validations, that means commands can change entity’s state in any way. And if commands can do that, then anything else also can do that. And if anything can do that, then your entities are nothing but data containers. Then you are referring to data objects (or maybe DTOs), not entities. This is the difference between entities and anything else. And that’s called anemic model, regardless of your denial.
        So, what I don’t like (and what even scares me) is that such entities (which I call them entities because you want to call them entities), because they can be changed from anywhere, eventually they get changed from everywhere. And you end up having many commands / services and all change entities in all sorts of ways. And when the software system grows and becomes complex, you start scratching your head about many issues that occur in many places, such as commands contradicting to each-other, overwriting each-other’s values unintentionally, and so on. That kind of software, to me, is hard to maintain and enhance long run.
        I’ve been there, I don’t plan to go back. Honestly, I dislike that approach because it has made my life harder in the past, many times.
        I’ve tried both approaches, and I started with this same step – made entities as data containers, and created services that each changed entity in any way they wanted. With growing complexity, I felt I made a mistake in the initial design. And that kept repeating for long time, until I realized that complexity should be handled differently.

        And you’re absolutely right – implementing DDD in the right way is not trivial, but it’s like an up-front investment. Investment is in terms of designing the entities in the right way – encapsulating their state and behavior into them. Right, my entities may become a bit more complex than your entities, but my commands will be simpler than your commands, so I don’t feel bad about that. Long run, opposite to your disclaimer, DDD approach (the way I described) should win. In simple solutions, your approach is probably more attractive to many developers, hoping that they will get along with it.

        However, please don’t take it as a resistance to what you prefer, it’s just based on my personal experience. I’ve tried both, and “always consistent entities” (on their own, without commands ensuring their consistency by governing their state) is what I prefer.
        I think that every reader will make conclusions if they are given the right choices.

        • jbogard

          You’re conflating consistency with validation. One can certainly put all of the state changing inside the entity/aggregate, nothing is stopping you from doing that.

          And remember – DDD isn’t about entities and aggregates, it’s not about OO. One can certainly have an anemic domain model (or intentionally, a persistence model) and be doing DDD. That took me a few years to understand, too. I was focusing far too much on structural patterns when that was the least important part of DDD.

          I am rather comfortable with my approach, it’s scaled quite well for us, especially when focusing on CQRS, having first-class commands and queries, and very few services. I’m not too worried about things getting “messed up” in the future, no pattern/approach prevents that. We just use pull requests to ensure quality.

          But this is hard because I’m not sure what I’m arguing against. The times I’ve seen UI-level validation inside of entities has been…..ugly to say the least, but I’m happy to entertain alternative approaches. Perhaps a gist to highlight what you’re talking about?

          • So you are basically saying this http://www.martinfowler.com/bliki/AnemicDomainModel.html is no longer relevant?

          • jbogard

            I don’t think so. One can certainly have behavioral models that satisfy invariants, but not have them perform the validation of a command. We do this all the time. Highly behavioral models, 100% encapsulated. Just validation is not a responsibility directly of an aggregate, but of the domain as a whole. Validation, like services and repositories, being part of the whole model.

          • I am not talking about validation since I still believe that commands must be valid with best effort from the sending side. As Alberto says, there is validation, this term is heavily overused. What got in my face is your phrase “one can have an anaemic and still use DDD”. Well, surely strategic patters are way more important, but won’t we mitigate nearly all of its goodness by using anti-patterns for the tactical part?

          • jbogard

            Oh, yes, sorry. In general, that’s not what I’ve found. By doing “DDD” it means to me that I’m doing strategic design and service/microservice-oriented architecture. Bounded contexts and the like.

            But many times I’ll build bounded contexts that are small enough that the first part of the book doesn’t even apply. There’s ubiquitous language, that’s critical, but if my subdomain/microservice is so small that I can use the stupidest thing that could possibly work, transaction scripts from PoEAA, why not?

            I do think “anemic” is the wrong word. Anemic means there’s behavior, but in the wrong place. Helpers, services etc. I now use the term “persistence model” when it’s a model whose names match the ubiquitous language, but there’s such minimal behavior, I don’t build an actual domain model.

          • Surely, a bounded context could be whatever inside. Legacy systems are bounded contexts with all this mud inside… I see the point, some of bounded contexts that we have are in fact just stateful process managers, for example. Or even CRUD.

          • jbogard

            I *think* so. That’s part of why I liked the concept of microservices, it frees us to decide exactly what internal architecture should be for each context.

            At least, that’s my interpretation of it. But I’ll be at NDC next week if you want to chat more about it! I’m still trying to figure out how this all fits into the broader DDD context…

          • Will you be visiting the Particular dinner event on the 7th?

          • jbogard

            Yep!

          • Tengiz Tutisani

            You guys let me know your conclusions, because I stay with my opinion – described above is an anemic domain model, which is an anti-pattern (and it’s explicitly named as anti-pattern in Martin’s page too, which Alexey referred to).
            BTW, I was thinking about this, and Martin’s article confirmed it to me. Quote from his post: “I don’t know why this anti-pattern is so common. I suspect it’s due to many people who haven’t really worked with a proper domain model, particularly if they come from a data background. Some technologies encourage it; such as J2EE’s Entity Beans…”. I’m pointing to the the last sentence here. There are indeed several technologies that encourage it, and among them – who could guess – AutoMapper. I personally have discouraged usage of AutoMapper in Repository implementations at my current job, by saying that it encourages mapping from property bags into property bags, which means business entities would be nothing other than property bags coming out of Repositories (and not entities anymore).
            So, this is not a question you will answer positively, so take it rather rhetorically – don’t you think you should attach a declaimer to the AutoMapper’s documentation, warning people of Anemic Models resulted by incorrect usage of it?
            Anyway, I’m going to soon write a post which will explicitly discourage usage of AutoMapper inside Repositories to map from data access objects into entities. It’s just better that way.
            And I suspect that you are influenced by AutoMapper to design entities which are just property bags [or opposite maybe].

          • jbogard

            Lol ok agree to disagree.

            Meanwhile I’ll be here shipping software, consistently, for years using this and other patterns.

            Tools aren’t the problem, people are, and no matter if my tool existed or not people will build awful anemic software. But not me :)

          • Tengiz Tutisani

            Good point and nothing against you here.
            Here is another thought – you should add a feature to AutoMapper to map from properties into constructor arguments (because entities are normally immutable, but initialize by taking constructor arguments). That would be very handy when mapping inside repositories. If we assume that entities can be constructed by passing constructor param values from the properties with same names (case insensitive), then the mapping would be just perfect. This one is not rhetorical. I was thinking to build a mapper like that myself (I have written code that does this same task inside small projects, nothing more than that). But I think your framework would be the perfect place for such feature.

          • jbogard

            Well good news that feature exists! Not probably advertised too much, it’s still a lot of work to get this to work in C# but it’s there

          • Jimmy decided not to join us at Particular event, so I had no chance to discuss this :) However, that I assume is meant by “good parts of DDD” is all the blue books talk after chapter 11 – the strategic design. In fact, DDD is how Vaughn Vernon summarises – “developing an ubiquitous language inside bounded context” and this has nothing to do with how you create your entities. I personally think that tactical patterns are of great value but in reality finding context/service boundaries becomes the most important. When every significant system component is placed on a context map, life becomes easier, we get something to reason about. We can also take one mapped piece and change its implementation and here where we come to tactics, not before.

          • jbogard

            Ha yeah…I went to the geek beers after, but I had to have a burger. I think we’re on the same page – structural patterns for me are still important, but not the MOST important.

            One other thing I thought of – even inside a bounded context, I often have what Udi calls “business components”, and I can see those boundaries defining which structural patterns are used. For example sometimes I have an API anti-corruption component, that just does the dumbest thing possible, straight up SQL.

          • Tengiz Tutisani

            I get it. I guess the difference between what you are describing and what I believe in is – where the business knowledge is *implemented*. Everything inside bounded context will obviously express ubiquitous language, and that part does not differ. What differs is where I put the actual code that carries and implements the business knowledge, including validation and constraints. I believe that business knowledge should be housed inside business entities, and everything else around (in the bounded context) can manipulate entities, but only in the ways that entities would allow (because again, entities are the primary house of knowledge implementation). What you guys are describing is, to spread the business knowledge in several components (within the same bounded context), not just manipulation but also decisions about what’s wrong and what’s right about these manipulations. From my experience (and I get that you may have different experiences), I feel completely lost in systems when all kinds of manipulations and decisions (which I call business knowledge) are allowed – and thus written and spread – everywhere. I prefer to think about entities as “always consistent by their own nature” and if anything, I don’t even guess where the knowledge is buried – go straight to entities and there it is. This is very helpful when the system is already mature and some requirements may change, or defects need to be fixed. In such situations, if I find myself looking at more than entities to figure out how the state got corrupt, I start hating it – because I want to keep it simple, maybe because my brain can hold up to 7 items at the same time, and never more. I don’t want to remember which command is doing what to the entity, and then think what these all commands together want from entity. Context map and brainstorming, spreading the business knowledge everywhere (as long as within the bounded context), is very tempting when you are creating a software and shipping the first version of it, or if you are going to maintain and extend the software throughout its life cycle. But when it’s about not just you, it’s very important to design entities that can at least ensure the non-corrupted state at all times. This is my preference, and I hear your preference, but I don’t share it.

          • jbogard

            When I build these systems, all the relevant files reside right next to each other. View, handler, validator, commands and queries, expressjs modules. All named after the action, so I don’t have jumping around. I suppose that’s why it’s never bothered me, I organize by vertical slices, not layers.

            When I did a layered architecture, yeah it was super important to put all the logic inside entities otherwise I’d go nuts.

          • dave falkner

            Couldn’t AutoMapper be used just as well for mapping a properly-encapsulated OO domain model to property bags at the system boundary? Not wanting to bother with all of the mapping was part of my current teams reluctance to go with a domain model approach.

      • I think many people get confused by the term “validation” versus invariants. You wrote about this before https://lostechies.com/jimmybogard/2010/02/24/strengthening-your-domain-aggregate-construction/. Protecting invariants in the entity is not the same as operation validation and I agree with you there completely. By invariant constraints we can ensure an aggregate cannot be put in invalid state, however this does not mean we can use it for validation purposes since the exception handling would be hard to complete. I personally think that validation is needed at all levels. The higher level is to get validation error, the better, the easier is it to inform the sending party about wrong action.