4 ms·
How does "defer" make it harder to reason about the code? Especially when the alternative is a bunch of resource-flag-tests and cleanup labels? There is a reas
by usrbinbash 5y ago
How does "defer" make it harder to reason about the code? Especially when the alternative is a bunch of resource-flag-tests and cleanup labels?
There is a reason why it was introduced in Go.
- yk 5y agoBecause the compiler has to introduce code implicitly. The control flow is usually very explicit in C, with this feature it is less explicit.
- pjmlp 5y agoUntil a signal gets raised.
- usrbinbash 5y agoSo its better to make the control flow explicitly complicated with a bunch of labels and resource-flags and doing so inconsistently (because everyone has a slightly different view on how to implement it), than having the compiler do it in a consistent way? Pragmatic point of view: In 99% of cases, the developer doesn't care what the compiler produces and doesn't have to. A mechanism providing a complex control flow in the compiler output but is incredibly easy to read and reason about in the source code is useful in the vast majority of cases. And for the 1% of cases where the programmer actually needs to know what the compiler produces, and / or full control over the control flow, the solution is simple: don't use `defer` and there, done, full control to the developer. So where exactly is the downside?
- jstimpfle 5y agoYou don't need to code with "a bunch of labels and resource flags", though. There are most often good ways to clean up in a reasonable way. Even the simplistic malloc()/free() works with straight line code, just initialize to NULL and you can call free() without even checking that the resource was acquired. It's also often valid to not clean up at all because the OS cleans up after process exit. And besides, if resources aren't released in the same function you'd need to come up with a different way to clean up anyway.
- usrbinbash 5y ago> There are most often good ways to clean up in a reasonable way. Yes, and if a defer keyword were to be introduced in C, all these reasonable ways could still be used by anyone who wants to, while we could let the compiler handle it when we don't want to, making the source easier to read and reason about.
- foxfluff 5y agoIt's slightly less explicit, but at least it's still all explicitly contained within your function. For example, you don't have to open up the definitions for a dozen different classes and read their destructors to know what happens (if anything) when your function returns. (That's the kind of stuff that can make C++ nigh impossible to reason about.) It seems barely more implicit than expression-3 in a for loop. I don't feel like it's going too far for C.