←back to thread

Parse, Don't Validate (2019)

(lexi-lambda.github.io)
389 points melse | 2 comments | | HN request time: 0.495s | source
Show context
dgb23 ◴[] No.27640445[source]
This principle can be applied to dynamic languages as well if you have some mechanism such as type hinting, pre-conditions etc. that are checked by a linter during development, even if it isn't, you can still use it at runtime with sufficient error handling.

The essential point of this blog post is to avoid "shotgun parsing", where parsing/validating is done just from a procedural standpoint, where it matters when exactly it happens. In the paper "Out of the Tar Pit" it is asserted that this leads to "accidental complexity" (AKA "pain and anxiety"), which is something every programmer has experienced before, possibly many times.

I've become a fan of declarative schema to (json-schema/OpenApi, clojure spec etc.) to express this kind of thing. Usually this is used at the boundaries of an application (configuration, web requests etc.) but there are many more applications for this within the flow of data transformations. If you apply the "parse don't validate" principle you turn schema-validated (sic!) data into a new thing. Whether that is a "ValidatedData" type or meta data, a pre-condition or runtime check says more about the environment you program rather than the principle in discussion. The benefit however is clear: Your code asserts that it requires parsed/validated data where it is needed, instead of when it should happen.

replies(2): >>27642136 #>>27642139 #
1. frogulis ◴[] No.27642136[source]
I think the article goes a little further than what you describe -- it would have you use a strong type that cannot represent illegal values.

There's a follow-up article by the same author (that I unfortunately can't find), in which she explains this point.

As an example, returning a NonZero newtype over Int is not as type safe as using an ADT that lacks a zero value altogether. Using a NonEmpty newtype over List is not as type safe as using the NonEmpty ADT that has an element as part of its structure.

Basically newtype still has use, but it is not as airtight as a well-designed ADT.

replies(1): >>27649682 #
2. runeks ◴[] No.27649682[source]
> There's a follow-up article by the same author (that I unfortunately can't find), in which she explains this point.

I think this is it: https://lexi-lambda.github.io/blog/2020/11/01/names-are-not-...