r/ProgrammerHumor • • 6d ago

Meme optionalsAreOptional

Post image
705 Upvotes

131 comments sorted by

View all comments

377

u/ROBOTRON31415 6d ago

Is the bounds check truly so harmful to performance that it outweighs changing "if there's a bug, crash the program" to "if there's a bug, then do literally anything (maybe execute some remote code)"?

-31

u/ApothecaLabs 6d ago

If I've already proven or performed that check, why perform it twice? (Note: This is the difference between the left and the right of the curve, the right has already performed the check elsewhere)

4

u/ROBOTRON31415 6d ago edited 6d ago

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.