Always Valid

Jeff Palermo recently wrote up a blog post about “The fallacy of the always valid entity”. This post is a more thought out commentary to the ideas therein and could be better suited with a name of “The fallacy of the fallacy of the always valid entity”.

Jeff appears to be arguing with something that he for lack of better terminology just does not understand. He gives an example and then asks the question of:

  • “The fact that name is required needs to be context-bound.  When is it invalid?”
  • This is referring to one type of validation that occurs within a domain. This is a validation to perform an operation. Generally speaking this type of validation is not performed by the object itself but is represented as observations of that object by another object. Jeff is right in that trying to make these things always valid makes no sense.

    Of course no one in the “always valid object” camp has ever made such a statement. This brings us to the crutch of the argument … What do we want to keep valid?

     

    clydsdale ==?  mohawk pony

    Not surprisingly some great people have dealt with these problems in the past.We can look at by going into philosophy (yeah boring I know) for a moment. Let’s say there are two horses a big Clydesdale and my friend’s daughter’s pony “samantha”. We have all seen the Budweiser commercials so we can imagine what the Clydesdale looks like but “samantha” is quite different. She is short, kind of thin, white with a black nose, and has her hoofs painted most of the time (likely due to her proximity to my friend’s daughter).

    If we were to look at these two things we know that they are both horses. But they are still quite different, why is that? Plato put forth the concept of ideals, that there is somewhere an ideal horse which represents all of the recognizable traits of a horse. All horses can be descended from the one ideal horse, the ideal horse represents all of their common traits.

    So you must be thinking how does this relate back to the original topic of objects always being valid? We have introduced a second type of validation!

    Suppose we had a unicorn with no horn? Would it still be a unicorn? What about a cyclops with two eyes? These things are invariants of the objects (they belong on the concept of the ideal). If we were to have an object that did not meet these invariants it would in fact cease being the concept that we knew it as.

    We run across these types of things regularly in our domains! Let’s imagine we are building grain silos … could we have a grain silo without a capacity? If we were writing poker software could we have a poker table without any seats? For a product application does it make sense to allow a sale line item without a product?

    It can be quite useful for us to model our domains using invariants. The main reason for this is that it helps with DRY. Quite often we will see that nearly all or all operations require a certain thing to be true, as such the checks are run in many places. As an example a customer must have a name to place an order, they also must have a name to move, or to open a credit account. We could always be diligent to check that the customer has a name in various contexts or we can build into the customer object the invariant that the name will always be non-null. Invariants help us to narrow our thinking when we rationalize about our domain.

    TDD will quickly lead you to the need for invariants. Consider when I have a BattleService that takes a parameter of a Cyclops … Without using invariants the first test I should be writing is should_throw_not_a_cyclops_exception_when_cyclops_has_two_eyes() … As soon as I find myself writing this test I should be seeing the language and realizing that I am being silly. In case that does not work I should at the least see that if I moved such a thing to be an invariant of my object that I could be saving myself code/tests elsewhere.

    Now to bring this back to Jeffrey’s original misunderstanding of the always valid viewpoint, it is not that an object must always be valid for everything, there are lots of context based validations… Always valid means that you are not breaking your invariants.

    This entry was posted in Uncategorized. Bookmark the permalink. Follow any comments here with the RSS feed for this post.

    17 Responses to Always Valid

    1. Branko says:

      It would be good to see an example of mapping the “always valid” domain model exceptions to the localized UI messages. Perhaps something where a mapping framework like AutoMapper can be utilized? I guess the exceptions would be custom but still an example would be very useful. Thank you.

    2. Harry says:

      If I remember correctly, in DDD, invariances should be reinforced at the aggregate level, mostly by aggregate root. I think Jeffery’s point is that object level ‘always valid’ is irrelevent especially when aggregate is internally handling the internal stuff (loading, creating, … etc). And the invariance and the aggregate boundary is the context Jeffery was talking about.

    3. Tom says:

      Hi,

      Would be great to see some code of this, just a simple customer edit example.

    4. Tom says:

      Good post as always.

      I would like to see a code example of this if possible. I sometimes find it hard to picture how the code would be. Could you do it for a simple example of a say a customer which has contact addresses and when editing a customer he/she must have details (title, name etc) and at least one contact address?

    5. Qolabisk says:

      aPtDeK comment5 ,

    6. Illugi says:

      An interesting paper to read while thinking about these matters http://www.swen.uwaterloo.ca/~drayside/PAPERS/rayside_oopsla00.pdf

      I do not think Greg should provide any code examples, invariants should not be viewed as something that easily can be understood by simple patterns or code examples. It’s far to fundamental and important for your domain and the deeper understaning of your design.

    7. Stephen says:

      Gutted, I wrote a sizable reply but I don’t remember doing the ‘captcha’ (looks to much like a banner to me, isn’t immediately obvious, ah well).

      Basically I was saying that in terms of validation, entities already validate quite a lot by just being .net types, for example- we know an entity has these properties, and we also enforce how those properties look (int, DateTime, string – etc)..

      It seems to me there are some universally correct validations for an entity, where any usual scenario would want these validations.. if not then you would probably want entities to be a property bag which seems scary.. it seems sensible that an entity should validate itself to these universal concerns (with compile time errors where possible, ie type correctness).

      But that any additional concerns are concerns of a specific operation, and they should validate that a given entity satisfies their requirements.. my example was that if you passed a ‘Comment’ to presentation logic, it may only care that you have a Name, Body and a post date.. but passing a comment to the persistence layer would have different concerns.. that the comments date is now in the future (for example).

      However you manage to generalize these validations is up to you..

      Variants are good for things that the type system can enforce, thus getting compile time validation.. but most validation I think happens at runtime, but I think tools like code contracts could massively help push runtime concerns to compile time.

    8. Gustavo says:

      I agree with Nate, most of us wanna see some piece of code, specially about CQS!

      Please Greg, make us happy!

      Sory bad english

    9. Greg says:

      Nate,

      What sort of code would you be looking for here? I specifically stayed away from implementation as there is more than one way to implement an invariant depending on the style of your domain.

      I can put up a new post with an example implementation if you want but it will have many things that seem different about it (i.e. its not just a property bucket)

      Greg

    10. Nate says:

      Greg, I enjoy your writing. I agree with you a lot. But I’m going to stop paying attention to you until I see some source code. Jeffrey releases plenty of it. Where’s yours?

    11. Alex James says:

      The idea that there are contexts for validation is something I have struggled with before:

      http://blogs.msdn.com/alexj/archive/2009/01/07/nullable-false-but-when-exactly.aspx

      Looking forward to chatting about this.

    12. Eldon Ferran de Pol says:

      Hi Greg,

      Excellent article and I totally agree. I find the distinction you make between different types of validation particularly useful. There is a clear difference between an object that is not in a fit state for some purpose and one that breaks incontrovertible laws about what it means to be of that type.

      Do you have any good 3.0 patterns around invariants? For immutable types I tend to have guards in the constructor. Where I have state modifying methods I sometimes factor to a private method. Still all a bit clunky though.

      Gillian,

      Jeff’s argument that always valid is bad with entities is exactly the problem: there is nowhere it is more important in the context of invariants. To extend Greg’s example. A Cyclops with two eyes is not in need of questioning to find out whether it can wear glasses. It is simply not a Cyclops, by definition and, at a code level, by invariant.

      DDD, an aspect of which Jeff puports to be demonstrating in his post, and all OO modelling is based on the pretty simple premise that the better software reflects the real world the more chance it has of meeting requirements for that world. Why would anyone prepared to put in the time and effort to apply DDD ever allow a Cylops with two eyes to exist? It is never valid. In any context. That is what we mean by invariant. It always holds true within the given domain.

      Jeff’s example is the direct equivalent of the two-eyed Cyclops. I think this is the point he hasn’t grasped. The fallacy he talks of is not a fallacy at all. It is a subtlety he has completely missed in what “always valid” means to the people who actually use it

    13. Greg says:

      @kyle re invariant.

      They are things about our objects that are included *in the definition* of the object. For instance that a unicorn has a horn (I don’t check to make sure it has a horn, I assume it). His example is domain dependent, in some domains the fact that an order has a customer may very well be an invariant.

      the point of this post is really more to explain the error in Jeff’s post. We must ALWAYS insure that our invariants are true … We also have validation that is context specific and can be broken (i.e. an entity is valid for an operation) but for invariants they are *always* true.

    14. Kyle Baley says:

      Greg,

      Trying to get a sense of what you mean by invariants. They are things that, when satisfied, mean the object simply can’t exist, yesno? I.e. you don’t *need* to write the test checking to see if a cyclops has two eyes because that case is not physically possible?

      And the type of validation from Jeff’s example, where you need a customer’s name in order to fill an order, is a different type of validation? That is, the customer’s name isn’t an invariant.

    15. Gilligan says:

      I always thought people bottled up “Always valid” in too specific a context. Jeff is only arguing “always valid” is bad with entity invariants. We have more objects in the domain model than entities. We have value objects, services, components (transient state-based objects), Repositories, Messages, etc. All of these have “invariants”. A BudweiserCommercial service would have an “invariant” that it can only register Clydesdale horses, for example.

    16. Blair Davidson says:

      Hi Greg,

      I do strongly agree with you.

      Just commenting on the following quote.

      “This is referring to one type of validation that occurs within a domain. This is a validation to perform an operation. Generally speaking this type of validation is not performed by the object itself but is represented as observations of that object by another object. Jeff is right in that trying to make these things always valid makes no sense.”

      If we have object that can be valid in different states we can use the state pattern to do the validation in each different state. I still think we should validate an object in the constructor and as we perform operation like change address on an entity to stop an object from moving into an invalid state.

      I have used the old isvalid approach before and you end up seeing checks everywhere for this in the service layer methods. I have found it to be annoying checking it everyone and it hurts when you forget to check it as it breaks code in other places that you have assumptions of things being in a certain state.

      I would really love to get other peoples ideas and techniques and maybe share some code on the above.

      Blair Davidson

    17. Blair Davidson says:

      Hi Greg,

      I do strongly agree with you.

      Just commenting on the following quote.

      “This is referring to one type of validation that occurs within a domain. This is a validation to perform an operation. Generally speaking this type of validation is not performed by the object itself but is represented as observations of that object by another object. Jeff is right in that trying to make these things always valid makes no sense.”

      If we have object that can be valid in different states we can use the state pattern to do the validation in each different state. I still think we should validate an object in the constructor and as we perform operation like change address on an entity to stop an object from moving into an invalid state.

      I have used the old isvalid approach before and you end up seeing checks everywhere for this in the service layer methods. I have found it to be annoying checking it everyone and it hurts when you forget to check it as it breaks code in other places that you have assumptions of things being in a certain state.

      I would really love to get other peoples ideas and techniques and maybe share some code on the above.

      Blair Davidson

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>