"Parse, don't validate" through the years with C++

· coding · Source ↗

TLDR

  • Walks through applying Alexis King’s parse-don’t-validate paradigm to a date parser across C++98, C++11, C++17, and C++23.

Key Takeaways

  • The core idea: use the type system so a successfully constructed type is already valid, eliminating downstream validation branches.
  • C++98 version uses a private constructor, enum-based ParseStatus, no heap allocation, and no exceptions, suitable for embedded targets.
  • C++11 version delegates parsing to std::get_time and uses exceptions for failure; C++17 swaps exceptions for std::optional return values.
  • C++23 introduces std::expected for rich error information without exceptions, the clearest expression of the pattern in the series.
  • A private constructor is the enforcement mechanism across all versions: invalid Birthdate instances simply cannot be constructed.

Hacker News Comment Review

  • No substantive HN discussion yet.

Original | Discuss on HN