3 ms·
Another example, let's say you're parsing a subscriber name for an email list, and you have a few checks such as whether it's too long, has whitespace, orcontai
by satvikpendem 4y ago
Another example, let's say you're parsing a subscriber name for an email list, and you have a few checks such as whether it's too long, has whitespace, orcontains forbidden characters:
pub fn parse(s: String) -> SubscriberName {
let is_empty_or_whitespace = s.trim().is_empty();
let is_too_long = s.graphemes(true).count() > 256;
let forbidden_characters = ['/', '(', ')', '"', '<', '>', '\\', '{', '}'];
let contains_forbidden_characters = s
.chars()
.any(|g| forbidden_characters.contains(&g));
if is_empty_or_whitespace || is_too_long || contains_forbidden_characters {
panic!("{} is not a valid subscriber name.", s)
} else {
Self(s)
}
}
And let's say your code to add a new subscriber to the email list only accepts a SubscriberName, not a String:
pub struct NewSubscriber {
pub email: SubscriberEmail,
pub name: SubscriberName,
}
Because `parse` gives back a SubscriberName if and only if all of the parse checks pass, you simply cannot add a new subscriber without all checks passing; the function will simply fail otherwise.
This example comes from the excellent book Zero To Production In Rust, which has a chapter on type-driven development [0].
[0] https://zero2prod.com https://zero2prod.com
- still_grokking 4y ago"Funny" code. I'm quite sure nobody would do something like that "in production"… The problem starts with the signature of this function: There is—of course—no function which could take an arbitrary String and return a SubscriberName. You need to return at least an Option, or better a Result. But at this point the fun starts. You need to thread this wrapped value throughout your whole program. Crashing your program (by a panic in the above function, or by a unwrap somewhere later) because someone sent you an invalid String is not an option in real life.
- satvikpendem 4y agoThat's a simplified example that I grabbed in the middle of the book before the author refactors it, of course you shouldn't `panic` if you don't need to.
- still_grokking 4y agoI've pointed this out as I think the follow-up problem is more difficult actually. It's easy to validate something "and just throw an exception". The fun starts when you can't do that (or don't want to do it like that).