3 ms·
I'm not sure I see how "parse, don't validate" would apply when using a newtype—would you mind explaining further? I think the main point of this article is th
by tbroadley 6y ago
I'm not sure I see how "parse, don't validate" would apply when using a newtype—would you mind explaining further?
I think the main point of this article is that newtypes aren't an application of "parse, don't validate". If you validate that user input doesn't contain XSS, then wrap it in a `SafeHtml` newtype, that's validation, not parsing. The article outlines ways that you could wrap the user input but forget to validate.
By contrast, suppose you have a type like `type SafeHtml = TextNode Text | DivNode SafeHtml | ...`. You parse the user input into a value of this type. If the parse fails, it's because the user input contained something unsafe. The article contends that it's harder to accidentally wrap an unsafe string, since you have to parse a safe HTML string to get a value of type `SafeHtml`.
(Although I'm not sure I buy that last point. With both methods you'd want to keep the `SafeHtml` type's constructors in a module and not export them. Otherwise you could wrap arbitrary text in the newtype or in the `TextNode` constructor. Both seem equally possible to me.)
- nyanpasu64 6y agoReturning an Option<newtype> is closer to "parsing" than returning a bool.