Correct Code: Pattern for handling user input

Correct Code: Pattern for handling user input

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.

The pattern


When I handle user input, this pattern appears:

  1. Input normalization
  2. Parsing the input
  3. Norm validation
  4. Business validation
  5. Action

Input normalization

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.

Input parsing

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.

Norm validation

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.

Business validation

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:

  1. 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. 
  2. 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.
  3. If the previous two apply and are correct, validate the business object as per business rules.

The action

And the last one is the action itself. Tips are found here.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.