Join the discussion
Write your take first — we'll ask for email only when you're ready to publish.
- Hacker News
- C++ could use some do-notationby rienbdj
- Abstracting any part of code structure in C++ is a wasps nest that will attack you back.by marcosdumay
- C is perfectly capable of type-driven design. He's already got the type (struct), and although C is a bit limited, he can:
* return pointer-or-null
* choose "invalid" sentinel values and then use birthdate_is_valid(...) to check validity.
* Add an is_valid bool field (or even an error enum like in the C++23 example)
* Add an out field in the constructor function for the error code (similar to how ObjC does things).
by kstenerud - Or use an out field for the type itself, and use the return value for an error code (or just a bool). A common pattern in C#.by tech_hutch
- Cool, incredibly low bar.
All four of your examples are validate.
Know any languages that are worse than C at this?
by mrkeen - The point of parse-don't-validate is that the type checker prevents you from having a value of a particular type that's invalid.
Pointer-or-NULL doesn't work, because all pointers are nullable in C; you can always have a Foo* (NULL) that's doesn't actually point to a valid Foo.
Invalid sentinel values are definitionally values of a particular type that are invalid. Same with an is_valid field.
An out field in the constructor means that whatever you actually return in the case of an error is going to be a well-typed Foo that's invalid.
by wk_end - I'm not a Haskell programmer, but from my limited awareness: Wouldn't they want to encode the restriction that April 31 doesn't exist directly in the type system instead of using raw integers for the underlying struct?by blt
- A very specific shortcoming of this implementation is indeed "Day of Month" and "Month of Year" aren't given their own types! The type specification should likely be applied all the way down! I felt the examples conveyed the point well enough and it was shorter in many cases.by dwrodri
- First thought, assuming that birth year starts at 1900 is bad for a number of reasons; one of which, "process this list of authors and ..."
What about everyone born before 1900?
by jsymolon - Or what if they were born after 1999?
It's just a toy example not a production ready birthday validation library.
by Neywiny - Assuming it is necessarily known which is the birth year of anyone assumed to have been in existence is already a big hypothesis if we go in that direction.by psychoslave
- It’s a contrived example. And I have to assume the author intended it to be contrived given that he also put an upper bound at 1999 in an article written in 2026 in an industry that skews young.
But the pattern applies regardless of the validation logic.
by alpinisme - Author has used LLMs to generate Java code in C++. It detracts from his point.by bregma
- No, it doesn't.by SuperV1234
- What Java code?
Regardless of how they might have used LLMs, I tend to have an issue with this kind of complaint, given the C++ example code on the Design Patterns: Elements of Reusable Object-Oriented Software book, released in 1994, 2 years before Java was made public.
Or the examples from "Using the Booch Method: A Rational Approach", "Designing Object Oriented C++ Applications Using The Booch Method", or "Using the Booch Method: A Rational Approach".
Additional there are enough framework examples starting with Turbo Vision in 1990, MacAPP in 1989, OWL in 1991, MFC in 1992,....
Somehow a C++ style that was prevalent in the industry between 1990 and 1996, that I bet plenty of devs still have to maintain in 2026, has become "Java in C++".
by pjmlp - I don't see how this is in any way preferable to having an ordinary default constructor that does the same thing:
// There are a few ways to let API callers bring their own // memory, as they would in a no-malloc environment and this // stack-friendly c'tor is a stand-in for that. static Birthdate epoch() { return Birthdate(1900, 1, 1); }by usefulcat - Some readers will expect Birthdate() to be equivalent to Birthdate(0, 0, 0), and naming it Birthdate::epoch() makes it clear that it is not that. I don't think it's worth it, but there is an upside.by plorkyeran
- Heh, I can especially tell the first code example is LLM-generated. Humans don't usually write comments like:
There's just something about this comment that doesn't feel right. I've seen these kinds of phrasings in LLM output before but I'm not sure exactly how to describe them.// There are a few ways to let API callers bring their own // memory, as they would in a no-malloc environment and this // stack-friendly c'tor is a stand-in for that.by MarsIronPI - Author here. The post didn't get much traffic when I uploaded so I didn't engage much with the thread. Looks like I should've come back!
I specifically wrote that by hand to note the specific shortcomings of this approach when evaluated under King's thesis. I do acknowledge that I use LLM models heavily when drafting the code snippets in this blog post, and I do a mini review in the conclusion of the downsides of using these models.
by dwrodri - The C example could have implemented a lot of validation just by checking the return value of sscanf():
This still does not catch trailing garbage, but you could check for that as well:if (sscanf(user_input, "%4u-%2u-%2u", &year, &month, &day) != 3) { // return an error }
The result would be 4 if there was at least one trailing character. Too bad there is still no std::scan() companion to C++23's std::print().if (sscanf(user_input, "%4u-%2u-%2u%c", &year, &month, &day, &dummy) != 3) { // return an error }by gsliepen - Although it feels intuitively as though a std::scan could make sense, it doesn't, at least not with the sort of API I've seen suggested
Consider a hypothetical Goose type, we can express any Goose usefully as output and, conveniently, some potential inputs could be read as a Goose successfully though most arbitrary strings cannot be understood as a Goose.
Providing std::print for Goose is simple, we've got a variable (or maybe a constant) of type Goose, we just emit the correct sequence of symbols. It's annoying to actually write all the boilerplate in C++ 23 but that's mechanical it's not actually tricky to do just very boring (and so hence maybe C++ 26 makes that easier via reflection)
But how could std::scan for Goose work? We need a Goose variable to potentially store the Goose if we read one, but how can we make a default Goose? No, each Goose is unique and there is no substitute, this can't work.
The std::scan idea seem attractive for simple almost untyped input, strings, integers, that sort of thing, but the whole point of "Parse, don't validate" is that you probably want to parse email addresses and ISBNs and ISO dates, you don't want a string, another string and a third string.
Rust's FromStr trait is more appropriate. Given a type implements FromStr we can parse any string to (maybe) get an instance of that type, but we don't need an "empty" instance first because we're doing the construction when we call the function.
by tialaramex - The second sentence of your summary is fine, but I don’t like the first sentence:
> Use your language’s type system to parse unstructured inputs.
We don’t use the type system to parse. We use the type system to provide evidence (also called a proof or a witness) that parsing was successful, and we rely on the language’s access control facilities (public/private) and the soundness of its type system to prevent fabrication of false evidence.
by mayoff - I like the linking of "construction of a type is evidence of correctness"!by dwrodri
- It seems like the C++98 example is the best by far? Keeps all error information while remaining concise and easy to understand. Not to mention 50 times faster. (Could be improved by adding some simple type aliases like BirthYear that explicitly start from 1900.)
IMO the main takeaway is that malformed input is not an exceptional state when parsing, and should be treated as a first class citizen. Everything else is yak shaving how you want to handle the (status, validObject) tuple coming from the parser.
by foobar1726 - The compile time is 50 times faster, not the runtime.by philip-b
- The C++11 example is the weakest in the article by its own thesis. Public throwing constructor, no year check, no leap-year check, so Birthdate(0, 2, 30) constructs cleanly. The C++17/23 shape (private ctor + static factory) is the actual mechanical insight from King's essay. Make the constructor a function that can fail, so the type itself carries the proof.by _alphageek
- exactly, use std::expected as the return type, avoid exceptions, and make a failable factory constructor to build your type. Make invalid states unrepresentable!!!by noitpmeder
- Just to note, a throwing constructor is “just as good” as static factory method, provided you want to use exceptions for validation errors. Which you shouldn’t, but from the perspective of testing types as proof, it’s just as good.by simonask