When and where to validate data depends on the kind of application you are building, the use cases (and their quality requirement on the input data), and on the constraints implemented in your database. Rules which are enforced by constraints on the DB usually don't have to be validated on the application side as long as there is no process implemented in your application which can change the data before it will be used. However, there will usually exist certain rules not implemented as db constraints, because they may change dynamically, or may be not be enforced at all times or not for all records of a data set.
Since you were talking about "changing the rules", let me focus on application-side validation, and not database constraints. In most systems which utilize a database, one will have a distinction between
Loading and saving some data from the db.
Using or processing the data in certain use cases or processing steps, either interactively or automatically or both.
Application-side validation (or domain-object validation) should not be intermixed with #1, and not entangled with it, otherwise you don't have a chance implement processes like
- editing of data interactively (with intermediate, invalid states)
- correction of the data (for example, after change of a business rule which makes certain objects invalid)
- quality assurance (where you want to display the data in its invalid state)
Hence, be careful what kind of validation you enforce at construction time in your domain objects, and which validation rules you provide as separate methods, which might be called at a later point in time. Making the construction-time validation too strict would forbid to implement certain use cases.
However, certain use cases may require more strictly validated input data, or require to strictly validate their output data before it is processed further.
That is where you have to look at:
find out which use case needs to have which business rules enforced, and when
implement validation rules for those, and call them at the appropriate places (which is not necessarily after the data was loaded from a DB, but maybe at a later point in time)
Of course, when your system does not support any use cases which allow correction or quality assurance of the domain objects's content, then you can do the validation also at construction time.
In short: the decision of which valiation rules to apply immediately when an object is loaded from a database depends heavily on the use cases of your system, and it is not an "all-or-nothing" decision.
reconstitute
method is. Thank you.User
can purchase, we want those rules to be enforced onUser::purchase
notUser::construct
.name
length with wherename
changes.name
changes, I should put it where I create the object which hasname
too. And I don't think duplicate logic is a good idea.