andersch.dev

<2025-08-11 Mon>

Parse, Don't Validate

"Parse, Don't Validate" is a programming principle that aims to make erroneous representations of data impossible.

The basic idea is to leverage the strong type system by creating opaque types for things that need to conform to a specific structure, e.g. email_t for an email address instead of just a char*. Parse the input into the correct type once, and then all functions that need to work with that type will be forced to use the functions that return it.

// instead of this...
if (validateEmail(untrustedInput) != true) {
   return error;
}
/* Rest of system uses `untrustedInput` */

// do this:
email_t theEmail = parseEmail(untrustedInput);
if (theEmail == PARSE_ERROR) {
   return error;
}
/* Rest of system uses `theEmail` */

Resources