Re:Thriving in a Crowded and Changing World: C++ 2006–2020 [...
by tialaramex on Saturday July 17, 2021 @07:27AM
(#27865066)
Also, if there is actually an invalid state for the result type, and your type system has a sum type here, it can implement the sum type by overlaying it, producing machine code that's just as nice as for old school C or C++ programs yet programs that have readable sum types. The actual best of both worlds.
Rust for example promises that Option<NonZeroU32> is the same size (four bytes) as u32, even though it has much more appropriate semantics for some cases. I can't accidentally end up with a zero where I wanted anything else, and I can't easily forget to handle the None case where there wasn't a non-zero answer.
A product type also allows returning weird states: no error and no value, or both error and value. I strongly believe that invalid states should be unrepresentable, rather than allowed by the type system and then fought by discipline and tooling.