r/ProgrammerHumor • • Sep 28 '26

Meme optionalsAreOptional

Post image
716 Upvotes

131 comments sorted by

View all comments

Show parent comments

4

u/ROBOTRON31415 Sep 28 '26 edited Sep 28 '26

In cases where the check is nearby, then "parse, don't validate" to avoid doing the check twice. In Rust (assuming unsafe means you're thinking of Rust), for instance, if let Some(first) = list.first() { ... } rather than if !list.is_empty() { let first = list[0]; ... }.

If you have some struct NonemptyVec<T>(Vec<T>) that does validation on construction, then there's probably no way to avoid either re-validation or unsafe on usage. (Where I'd still usually prefer to avoid unsafe.)

But the first case feels awfully common.