2 ms·
1) I'd much rather have a function check a condition in a single place, than have 20 places in the code which check the same condition before calling it -- the
by stouset 3y ago
1) I'd much rather have a function check a condition in a single place, than have 20 places in the code which check the same condition before calling it -- the whole point of functions is to encapsulate repeated code to reduce bugs
That's fine, but it's often a good idea to separate "do some work on a thing" and "maybe do work if we have a thing". Using the example in the article, it is sometimes useful to have multiple functions for those cases:
fn frobnicate(walrus: Walrus) {
...
}
fn maybe_frobnicate(walrus: Option<Walrus>) {
walrus.map(frobnicate)
}
But also… in languages like Rust, most of the time that second one isn't needed because of things like Option::map.