Defensive Programming Patterns in Rust: When "This Should Never Happen" Actually Does
By
PaulHoule
5mo ago· 18 min readenInsight
100/100
Golden Brown
Bagelometer↗
Crisp on the outside, thoughtful on the inside. A keeper.
Score100TypeanalysisSentimentneutral
Summary
The article discusses defensive programming patterns in Rust, focusing on how developers often use comments like "// this should never happen" to mark code that actually has vulnerabilities. The author explains their hobby of finding conditions under which these supposedly impossible scenarios can occur, noting that in 90% of cases they can indeed happen due to unconsidered edge cases or future code changes. The piece emphasizes that while Rust's compiler prevents memory safety issues, implicit invariants not enforced by the compiler often break down at these points, making them critical spots for defensive programming practices.
Key quotes
· 5 pulledI have a hobby. Whenever I see the comment // this should never happen in code, I try to find out the exact conditions under which it could happen.
And in 90% of cases, I find a way to do just that.
More often than not, the developer just hasn't considered all edge cases or future code changes.
In fact, the reason why I like this comment so much is that it often marks the exact spot where strong guarantees fall apart.
Often, violating implicit invariants that aren't enforced by the compiler are the root cause.
I have a hobby.
Whenever I see the comment // this should never happen in code, I try to find out the exact conditions under which it could happen.
And in 90% of cases, I find a way to do just that.
More often than not…

