expression
Enforce a domain invariant at construction
A domain invariant is a condition that every valid value must satisfy. A percentage in this example is an integer from zero through 100. Place its field inside a module and expose only a checked constructor and a read-only accessor. Private fields prevent ordinary outside code from constructing unchecked values, but every future constructor and mutation path must also uphold the invariant. Expected result (NOT RUN): valid: 85 invalid rejected: true Common mistake: Making the tuple field public or adding an unchecked setter. Static Rust example; not a verified ByteMind executable assessment.
Formal Syntax & Structure
rust syntaxrust
pub fn new(value: u8) -> Option<Self>Working Example
Example Snippetrust
mod domain { pub struct Percent(u8); impl Percent { pub fn new(value: u8) -> Option<Self> { (value <= 100).then_some(Self(value)) } pub fn value(&self) -> u8 { self.0 } }}fn main() { let p = domain::Percent::new(85).unwrap(); println!("valid: {}", p.value()); println!("invalid rejected: {}", domain::Percent::new(101).is_none());}