←back to thread

Parse, Don't Validate (2019)

(lexi-lambda.github.io)
389 points melse | 2 comments | | HN request time: 0.684s | source
Show context
pansa2 ◴[] No.27643457[source]
“Parse, don’t [just] validate”.

Say I have a string that’s supposed to represent an integer. To me, “Validate” means using a regex to ensure it contains only digits (raising an error if it doesn’t) but then continuing to work with it as a string. “Parse” means using “atoi” to obtain an integer value (but what if the string’s malformed?) and then working with that.

I first thought this article was recommending doing the latter instead of the former, but the actual recommendation (and I believe best practice) is to do both.

replies(2): >>27644989 #>>27646359 #
1. b3morales ◴[] No.27644989[source]
You seem to suggest that it's possible to parse without validating, which I'm not sure I follow. Surely validation is just one of the phases or steps of parsing?
replies(1): >>27645283 #
2. pansa2 ◴[] No.27645283[source]
Functions like `atoi` parse strings into integers, but will happily accept “ 10blah” and return 10. In my experience it’s best to validate that the string is well-formed (e.g. contains only digits) before passing it to one of those functions.