Question

This is a very naive question about input validation in general.

I learned about input validation techniques such as parse and validatestring. In fact, MATLAB built-in functions are full of those validations and parsers. So, I naturally thought this is the professional way of code development. With these techniques, you can be sure of data format of input variables. Otherwise your codes will reject the inputs and return an error.

However, some people argue that if there is a problem in input variable, codes will cause errors and stop. You'll notice the problem anyway, and then what's the point of those complicated validations? Given that codes for validation itself take some efforts and time, often with quite complicated flow controls, I had to admit this opinion has its point. With massive input validations, readability of codes may be compromised.

I would like hear about opinions from advanced users on this issue.

Was it helpful?

Solution

Here is my experience, I hope it matches best practice.

First of all, let me mention that I typically work in situations where I have full control, and won't build my own UI as @tom mentioned. In general, if there is at any point a large probability that your program gets junk inputs it will be worth checking for them.

Some tradeoffs that I typically make to decide whether I should check my inputs:

  • Development time vs debug time
    • If erronious inputs are hard to debug (for example because they don't cause errors but just undesirable outcomes) the balance will typically be in favor of checking, otherwise not.
    • If you are not sure where you will end up (re)using the code, it may help to enforce any assumptions that are required on the input.
  • Development time vs runtime experience
    • If your code takes an hour to run, and will break in the end when an invalid input value occurs, you would want to check of this at the beginning of the code
    • If the code runs into an error whilst opening a file, the user may not understand immediately, if you mention that no valid filename is specified this may be easier to deal with.

OTHER TIPS

The really (really) short story:

  • Break your design down into user interface, business logic and data - (see MVC pattern)
  • In your UI layer, do "common sense" validation, e.g. if the input is a $ cost value then it should be >= 0, be able to be parsed into a decimal etc.
  • In your business logic layer, validate the value, e.g. the $ cost value might not be allowed to be greater than the profit margin (etc.)
  • In your data layer, validate the data operation, e.g. that insert operation succeeded

The extra really short story: YES! Validate all inputs.

For extra reading credits see: this!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top