All Topics
All Topics
Technology
Technology
Design
Design
Programming
Programming
Science
Science
News
News
Gaming
Gaming
Entertainment
Entertainment
Business
Business
Finance
Finance
Sports
Sports
Health
Health
Food
Food
Travel
Travel
Art
Art
Music
Music
Books
Books
Education
Education
Politics
Politics
Personal
Personal
No algorithm. No AI slop. No ads. Just RSS. Pro-human. Indie writers. Real journalism. Open web. Chronological. Hand toasted.

Defensive Programming Patterns in Rust: When "This Should Never Happen" Actually Does

By

PaulHoule

5mo ago· 18 min readenInsight

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 pulled
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, 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.
Snippet from the RSS feed
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…

You might also wanna read