My 15yo daughter has got programming as a subject in her high school. A couple of days ago, she came asking for help. The program she wrote had a bug. While asking her what are the possible options, I came to one simple realization: handling user input has rules. Naimly, her bug was that she was missing the very first step, which I did intuitively. Breaking it down for her is the basis of this post.
When I handle user input, this pattern appears:
- Input normalization
- Parsing the input
- Norm validation
- Business validation
First I get raw input from the user. In an attempt to make it user friendly I try to normalize users input. For example, it is allowed to type in 10.00, and 10,00. If a url does not end with a “/”, we add it, etc. You don’t want to do this step with sensitive information, like passwords, but you want the email lowercase.
Then I parse the input to correct types. If parsing fails, I report an error. I already tried to normalize the input and there is nothing I can do at this stage, so I abort, notifying the user. Many frameworks do this automatically, so we need not parse to correct types.
Then I validate the norm. (I made up the name, in absence of a better one. Please. Help.). This is the simplest validation, that validates that an object fulfils the norm. An integer is less than 5, string length is greater than 0 etc. We all do these, hopefully.
The tricky part is business validation. It comes without saying there is not common set of rules for all domains, but I found a couple of things that you might find interesting:
- Always check if there isn’t one business object created already. Unique constraints are good, but we, hopefully, don’t show sql exceptions to end users. For example, a user must not buy the same digital goods twice.
- Always compare the previous state with the new state when updating a business object. For example, it might not be possible to ship a product because its order got cancelled in between. The UI data might be days old.
- If the previous two apply and are correct, validate the business object as per business rules.
And the last one is the action itself. Tips are found here.