3 ms·
Sure, I'll play devil's advocate! > Guard clause – exit a function early if certain conditions are not met. This makes the rest of the function easier to write
by mrkeen 3y ago
Sure, I'll play devil's advocate!
> Guard clause – exit a function early if certain conditions are not met. This makes the rest of the function easier to write (no nested if-statements).
If you have:
if(!isUserPort(strPort)) return;
You're gaining knowledge about input, and then immediately throwing it away (assuming the 'happy' path.)
Later when you use strPort, do you check it again? If you pass it to another function, do you check it there too?
"Parse, don't validate" is the name that's been given to the following:
case parsePort strPort of
NotAPort -> ...
RootPort port -> ...
UserPort port -> ...
It's more nested, but now you can pass your UserPort around and not check it too many or too few times.
- WesolyKubeczek 3y agoHm Unless your parsePort returns a specialized type which then can be enforced by the compiler, and all your other APIs use the specialized representation, it's sort of "six of one, half a dozen of the other" situation because if you're throwing your strPort around, you'll be parsing it again and again and again. And I can achieve what you are showing me just the same by putting my guard clause up the stack, closer to the main program or whatever. Not all data is so clear cut, your guard clause may be guarding against a numeric struct member whose value is out of range for this one function to operate. Which is why I usually have a few different wrenches for each size of nut I may encounter. Not dunking on your approach, let a hundred flowers bloom and all that.