5 ms·
I'm browsing this, and I'm not seeing the way I do it, which is sort-of-like #5 but not quite... I tend to wrap the code that has multiple exits-to-label in a
by spacedcowboy 4y ago
I'm browsing this, and I'm not seeing the way I do it, which is sort-of-like #5 but not quite... I tend to wrap the code that has multiple exits-to-label in a do...while(0) loop, and use break to get there...
So it might look like:
do {
if (false == call_func1()) {
cleanup_any_state();
break;
}
if (false == call_func2()) {
cleanup_any_state();
break;
}
} while (0);
At any point you can branch to the common exit-statement, and keep on testing for failure as you go through the algorithm without indenting forever.
Generally there's no too much state to clean up in the code I've been using this in, but obviously later 'break' conditions would have to clean up the state for earlier ones too. That's easy to abstract into functions for the cleanup though.
- gleenn 4y agoAt this point couldn't you just write an actual function and use "return"?
- spacedcowboy 4y agoSo the sort of stuff I've been using this in is encryption/decryption, where there's a whole boatload of things you have to set up, read/create OIDs, configure identities, fetch certificates, match algorithms, etc. etc. All of that has to be ok before you finally get to the bit that does the work, and since I'm using ObjC with its ARC feature, I don't need to deallocate anything, they'll be deallocated as they go out of scope. I tend to release critical RAII stuff in my -dealloc method anyway if there's anything there to be done. So it's really a whole long list of id result = nil; do { if (setup-X-fails) break if (setup-Y-fails) break ... result = call_method(X,Y,Z,A,...F) } while (0); ... which works out pretty well, and is very readable. The setup-xxx stuff can be several pages of code for each method - and useful in their own right, so integrating it into the loop doesn't seem preferable.
- billforsternz 4y agoI don't like the code pattern if ( false == func() ). Function func() already returns a boolean, no need to compare that to a second boolean (false or true) to generate a third boolean. Sorry, a little off topic I know.
- spacedcowboy 4y agoIt's there for illustration, that's all. I don't actually write code like that, but I want to make sure that you understand the condition in the code snippet.
- rocqua 4y agoIn languages without type coercion, it helps add some type checking by ensuring you return a bool rather than some value that has truthity.