Invalid Object Is an Anti-Pattern
I&#x27;m not a Rails dev (.NET actually) but I have stumbled with this question before: should I allow invalid objects to lay around my domain?<p>It may be tempting to validate as soon as the constructor&#x2F;setter is hit. And this works great for things like a name length or an email format as the article points out. The problem with this approach is when you hit a validation that is complex and&#x2F;or needs IO. What if there&#x27;s some info in the database that would allow or not you to construct the object the way you need? You would go to the database and check the info in your constructor?<p>Strike one.<p>Some validation only makes sense on a specific operation. The object you constructed, due to some business rule, may be invalid to delete but valid to update for instance. Feels more natural to validate the object with a context: is the object valid <i>to this operation</i>?<p>Strike two.<p>Not to mention the inconvenience of never being able to have invalid entity for things like integration with other systems and logging. What if you receive, from a webservice or something, a valid object format-wise but invalid from the business rule perspective? Being able to deal with an invalid instance feels more natural, when logging such exceptional behavior, inform the other system about it, etc. In this scenario of inevitable invalid data is better to handle it built into one entity rather than fighting against a bag of properties without any form at all.<p>Strike three.