by raincole · 3y ago · 0 comments
if(!needToDoTheThing()) return;
DoTheThing();
We could have written it this way: if(needToDoTheThing()) {
DoTheThing();
}
else {
return;
}
The later is closer to how pattern match looks like. But in my experience, the majority of programmers prefer early return. I regularly see people "refactor" if-else to if-early-return, but I've never seen the opposite.If you nest if/else, you'll quickly approach a point where you have to keep a complex logic tree in your head to determine which states the system could be in inside of any given branch. If you use guard clauses and return early, you'll keep this complexity down to a minimum, since the list of possible states changes linearly with your code instead of exponentially.
I know not everybody likes it, but I think this makes cyclomatic complexity an extremely valuable metric for measuring "ease-of-reading".
safeDiv :: (Monad m, Alternative m) => Int -> Int -> m Int
safeDiv x y = do
guard (y /= 0)
pure (x `div` y)
main :: IO ()
main = do
print $ safeDiv @Maybe 1 0
print $ safeDiv @[] 1 0
-- print =<< safeDiv @IO 1 0 -- guard throws an error in IO
Try it out at https://play.haskell.org/saved/a6VsE3uQ