I was wondering whether using a Belt and Braces (Suspenders) approach to programming - and to data validation in particular - was good practice or not. This came about from the following example.
I was creating a form and I added Listeners to all the fields which should mean that the OK
button is only enabled if all the fields in the form have valid values. I was then writing the code which was run when the OK
button is clicked.
The pessimistic side of me decided that Belt and Braces never hurt anyone and it couldn't hurt to validate the form again in case there's a bug in my form logic.
But then I didn't know what to put in if the validation fails. If I do something like this:
if (! form.isValid()) {
displayErrorMessage();
}
then I have to create code to display an error message which should never be shown. Anyone maintaining this code in future is then going to worry about and possibly be confused by this in theory needless dialog. The last thing I want is someone wondering why this particular dialog is never displayed.
An option at the other end of the scale is:
if (! form.isValid()) {
throw new RuntimeException("This should never happen!");
}
Frankly, I feel dirty even typing that but perhaps there's a good reason to use it which I have missed.
So finally I ended up with:
assert form.isValid();
However, the downside of that is that it's not really belt and braces since the braces aren't there at run-time so if there is a bug in the code my form's trousers are still going to fall down as it were.
So maybe I shouldn't have the extra validation at all, but there's still a part of me which thinks it couldn't hurt.
I'd be interested to hear what you do in similar situations.
(Edit: the question is asking what is the best way to ensure the form returns valid data. Assume that the output of the form is validated again before it ends up in the database and so on.)