It is important to always validate inputs. If you don’t validate inputs you
are leaving yourself open to future headaches, annoyances and bugs.
Input validation to me should be done as generically as possible and yet every
single input type should be flexible enough to validate independently.
I have been using this mechanism for input validation for a while, and it works very
well for me:
As you can see from the above, we have one small, tight interface InputValidation
which contains a single Validate method. This is very powerful, because we only
need to implement validation in one place, and yet we can also have the flexibility
of keeping the validation logic right next to the the definition of the structure
it is validating.
In our example above, Thing.Validate validates that the ID field is a valid UUID
and also validates that the Name field is not an empty or missing attribute.
What this looks like in practice is as follows:
Inside our handler we instantiate the type of Thing we want to decode from the
request body and validate. We pass the request and the Thing to decodeAndValidate
where we perform a json decode. We then take the resultant struct and call it’s
own validate method, returning any validation errors.
Why is this cool?
I really like this mechanism because it is trivial to mock for unit tests
as well as a super clean and sexy solution to the problem. Not to mention
it also makes sense that the logic for validation should be a function pointer
off the structure itself.
Another reason why this is cool is that you will not have to write extra amounts
of copious boiler plate to take advantage of this solution. You will already be
making your struct you will be deserializing into, and already be writing validation
This solution also scales for reuse if you need to reuse these input structures
in other places. Not to mention you have a consistent means for deserialization
and validation of these structures. Here is a link to the full gist.