3 ms·
> trust the input of your fellow functions, and don't lose too much time looking for assertions to add. Rust makes it so easy to add assertions that it's well
by jph 5y ago
> trust the input of your fellow functions, and don't lose too much time looking for assertions to add.
Rust makes it so easy to add assertions that it's well worth doing IMHO, and the assertions make it easy to detect corner cases such as with lengths, collections, comparisons, unexpected inputs, etc.
Rust comes with a handful of assertions, and there are crates that provide many more, as well as runtime equivalents for function input validation. I wrote the "assertables" crate to help with these: https://github.com/sixarm/assertables-rust-crate https://github.com/sixarm/assertables-rust-crate
- dystroy 5y agoIMO those assertions are more useful in tests (which Rust make easy) than to protect your functions from inconsistent inputs.
- duped 5y agoReturning a `Result<>` for corner cases is so much better than random asserts because it forces callers to handle them. Personally I reject anything that looks like `assert(...)` found outside of tests and ask they be replaced with a proper error or the idiomatic way to express a fatal/unrecoverable error in your language. In Rust that's `unreachable!` and `panic!`, not `assert!`.
- trevyn 5y agoI think an appropriate assert_eq! is more idiomatic than an equivalent panic!, since it automatically reports the offending value in the panic message.
- pornel 5y agoIt depends on what contract you have with the function caller. For example, assertions/panics are fine for reporting programmer's errors (i.e. situations that happen due to a bug in the software, not due to runtime environment). There's no point to force programmers to write error-handling branches that will never be used in a properly written program. This is the reason why methods like `split_at` just panic if you give them a wrong index. You're not supposed to make invalid indices in the first place.
- jph 5y agoYes. The assertables crate provides three macro flavors, to handle the three purposes of panic, or Err, or branch: assert*!(...) // () or panic! help message assume*!(...) // Result Ok(true) or Err help message assure*!(...) // Result Ok(true) or Ok(false)