News for hackers. Stuff that matters.
Re:Push ifs up and fors down by stouset on Wednesday November 15, 2023 @06:38PM (#38283965)
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.

There are no comments on this comment yet.