Patterns for Defensive Programming in Rust
6 months ago
- #Defensive Programming
- #Rust
- #Compiler Checks
- The comment '// this should never happen' often indicates unconsidered edge cases or future code changes.
- Indexing into a vector without length checks can lead to bugs; use slice pattern matching for compiler-enforced safety.
- Avoid lazy use of '..Default::default()' to prevent bugs from unset fields; explicitly initialize all fields.
- Destructuring in trait implementations (like PartialEq) ensures all fields are considered when structs evolve.
- Use 'TryFrom' instead of 'From' for fallible conversions to make failure cases explicit.
- Avoid non-exhaustive matches with '_ => {}'; explicitly handle all variants to prevent missed cases.
- Use descriptive names instead of '_' for unused variables to improve code clarity.
- Temporary mutability patterns help prevent accidental modifications after initialization.
- Make constructors return 'Result' and use non-exhaustive structs to enforce valid states.
- Use '#[must_use]' on important types to ensure return values are handled.
- Replace boolean parameters with enums or parameter structs for better readability and safety.
- Enable Clippy lints like 'indexing_slicing' and 'fallible_impl_from' to enforce defensive patterns.