Re:Push ifs up and fors down
by Gadiguibou on Thursday November 16, 2023 @08:50AM
(#38289461)
You can also often encode those checks in the type system like in the Option example near the start of the article.
Assuming your type system is robust enough to support such things. That's not the case for many mainstream languages.
In the article, when I saw this
> For f, it’s much easier to notice a dead branch than for a combination of g and h!
My first thought was "yes, but now if anyone _else_ calls h or g, the checks never happen (because they live in f). I'd much rather have h and g check what _they_ need in order to run correctly. That way, if another call to one of them is added, we no longer need to rely on _that_ call correctly checking the conditions. Plus it avoids duplication.
But... and this goes back to the original point from your post... this is a matter of code being correct over time; changeability. If you're worried about performance, then having the same check in 2 different places is a problem. If you're not (less) worried, then having the code less likely to break later as changes are made is helpful.