Imagine this... I have a field in the database titled 'current_round'. This may only be in the range of 0,1,2,3.
Through the application logic, it is impossible to get a number above 3 or less than 0 into the database.
Should there be error checking in place to see if the value is malformed (i.e. not in the range 0-3)? Or is this just unnecessary overhead? Is it OK to assume values in a database are correctly formatted/ranged etc (assuming you sanatise/evaluate correctly all user input?)
I generally don't validate all data from the database. Instead I try to enforce constraints on the database. In your case depending on the meaning of 0, 1, 2, 3 I might use a lookup table with a foreign key constraint or if they are just numeric values I might use a check constraint (differs from DB vendor to the next).
This helps protect against changes made to the DB by someone with direct access and/or future applications that may use the same DB but not share your input validation process.
Wherever you decide to place validation prior to insertion in the database is where you should catch these things.
The process of validation should take place in one place and one place only. Depending on how your application is structured:
Then you will need to decide on where to place this logic in your application.
In my case, domain objects contain the validation logic and functions with data mappers that actually perform the insert and update functions to the database. So before I ever attempt to save information to the database, I confirm that there are valid values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With