9 ms·
> it really is just syntax It's really not. When the impact of "syntax" are non-local like that, it's more than syntax. A compiler would handle this beyond the
by loup-vaillant 6y ago
> it really is just syntax
It's really not. When the impact of "syntax" are non-local like that, it's more than syntax. A compiler would handle this beyond the parsing stage. At the very least, it would seriously massage the AST to remove `defer` from it.
> if we assume defer is implemented like attribute cleanup and fix up the compile errors, your first and fourth example compile to the identical assembly code:
This is to be expected: they ultimately do the same thing, and optimisers are known to do significant, non-local transformations to the code.
> move the "business logic" into a separate function, one that takes the necessary resources as arguments.
So now I have a function with (likely) too many arguments, that's used only once, and my eyes have to jump around to get to it (or I have to reach for the F2 key). The pyramid may be more visible, but that's a meagre advantage.
> In my opinion the nested if style is better than using defer because it's completely linear with no backward jumps.
Not even a criterion in my book. I suspect you're having an overly operational mindset. A mindset I suspect has held the whole field back a couple decades. Don't think of it like a backward jump. It's meant to be viewed as deferred execution, triggered by scope exit.
> you can hardly complain about cleanup code being far from init code because the whole resource handling function is less than 20 lines of code
That was an example, dummy. In real code, I'd have more than 3 things to initialise, and their initialisation might not be as trivial (or as repetitive) as what I've shown here. That's when I really want to read the code from top to bottom, with concerns packed together. Defer/cleanup lets me do that. The other solutions, less so.