Input Validation: First line of defense
Every time an input is received, it can only be in two states, i.e., correct or incorrect. For an input to be correct, it must follow certain rules, e.g., it should be of the expected type, or it should only be between x and y or maybe something else based on the business requirements. For an input to be incorrect, all it needs is to not to follow any of those rules.
Validating the input has many advantages, e.g., it saves precious resources from processing the incorrect input. Early validation is similar to preemptive thinking, it allows for taking precautions against known issues while enforcing correctness.
The benefits of putting validations in place
Validating the input data is of utmost importance to ensure correctness and accuracy of the generated output after computation. If done correctly, it helps to reduce bugs and improves confidence on the algorithm.
Applying validations upfront ensures that the computation is performed on correct data. Some of the straight forward benefits of applying validations on the input data are mentioned below.
1. Guards against incorrect input value
Passing incorrect input can result in wrongful computation, exceptions or even errors in some cases.
2. Filters request(s) with invalid input state
Uninitialized variables and data structures can be unknowingly passed as arguments to the methods.
3. Enforces correctness in computation by filtering out the ‘out of range’ input values
Not all data is valid for some computations, validating the data before processing ensures that only correct and meaningful data is used while the rest is ignored.
4. Ensures the accuracy and correctness of the algorithm
Validating the input data for correctness and range also ensures the accuracy and correctness of the entire algorithm.
Here’s the link to my book on design patterns that I recently worked on. Hope you will find it useful.