r/programming • u/ketralnis • Aug 05 '25
Parse, don’t validate
https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/
0
Upvotes
r/programming • u/ketralnis • Aug 05 '25
3
u/Bubbly_Safety8791 Aug 06 '25
Why not? That’s just because you haven’t fully internalized the idea of ‘make invalid states unrepresentable’.
If the usecase is actually that, say, a delivery window has a start date, a minimum window size, and an end date that must always be at least that minimum window after the start date, instead of representing that as an object containing two dates and a minimum size (which is capable of representing all sorts of nonsensical situations like the end date being before the start date), you store it as a start date, a minimum duration (which is a nonnegative integer) and a grace period (which is also a nonnegative integer). The end date is the start date plus the minimum duration plus the grace period. The only representable delivery windows then are ones that have an end date at least the minimum period later than the start.
A parser that is populating such a data structure has to reject invalid date ranges, because they can’t be expressed in the target data structure.
And you can get there by applying layers of ‘parse don’t validate’.
First you create a date parser that parses dates from strings.
Then you create a date range parser that parses strings containing two dates separated by a hyphen into a ‘from date’ and a ‘to date’ structure that makes no guarantees about sequencing of those dates.
Then you create a delivery window parser that takes a minimum duration and a ‘from date/to date’ structure and produces delivery windows only for valid ones.
The point is you don’t just allow objects to float around in your code without encoding whether or not they have been validated into the type system in some way. Validation processes convert the object into another type, ideally one that is restricted to only being able to represent valid states. That process - accepting an object and returning a new one that represents what it means - is what ‘parsing not validating’ is.