4 ms·
Your cleanup argument holds true for C and its ilk, but not for anything else. In C you DO have to do manual cleanup, but in any language with exceptions you c
by mullr 17y ago
Your cleanup argument holds true for C and its ilk, but not for anything else. In C you DO have to do manual cleanup, but in any language with exceptions you can (and should) do that in a finally block. Or in C++, via one of the many scope-aware smart pointer classes. In higher level languages, it is idiomatically correct to have many exit points from a function.
As for being harder to debug... it depends. Again, if you MUST do manual resource deallocation, then I can see your case. Having duplicated cleanup code inside the control flow gets old fast. But if you've got exceptions, then such a rule leads very quickly to unnecessarily deep, convoluted control structures. I've flattened many such structures by a) factoring chunks out to separate functions and b) returning early when appropriate.
It is very common for a function/method to either throw an exception or return a default value based on some parameter. In these cases, it's pound-you-in-the-face clear to have a list of "if(check) return whatever;" clauses at the top. If you do this before resource allocation, you don't even need to worry about cleanup. This feels like a much "purer" way to write a function to me, almost like applying pattern matching before falling back to imperative mode.
- makecheck 17y agoThat's true, and I do use that approach ("RAII") in languages like C++. It definitely makes cleanup less of a problem. It also means that setup should be done no earlier than necessary, declaring variables very close to their first use (otherwise, a setup/cleanup cost may be paid for no reason). Exceptions act like early returns themselves, but I will use them for truly exceptional cases (only). In other words, if a function can return 3 values, I consider those the "normal" cases that should weave through to the end of the function; if the function runs out of memory, I think that's an exceptional case that can return immediately.