by notacoward · 6y ago · 0 comments
(1) Makes it pretty clear why exceptions are even more of a control-flow nightmare than goto. What a messy graph.
(2) The 'defer' diagram is a big WTF. Couldn't even figure out which box is supposed to represent which statement in the example.
(3) I'd love to see a graph of the control flow when you throw in a few spurious lambdas like "advanced" C++ programmers tend to do (and similar in a few other languages). Might even make exceptions look good.
That makes exceptions fall more towards the "easy-to-write, hard-to-read" side of things; implied side-effects make your code slim in the present, treacherous as combinatorial elements increase. With error codes you pay a linear cost for every error, which implicitly discourages letting things get out of hand, but adds a hard restriction on flow. With goto, because so little is assumed, there are costs both ways: boilerplate to specify the destination, and unconstrained possibilities for flow.
Jumping backwards is the primary sin associated with goto, since it immediately makes the code's past and future behaviors interdependent. There are definitely cases where exceptions feel necessary, but I believe most uses could be replaced with a "only jump forward" restricted goto.
A good use case for understanding the control flow of 'defer' is when cleaning up resources.
mutex.lock();
defer { mutex.unlock(); }
val f = File.open(filename);
defer { f.close(); }
// write to file
It's a nice construct because it keeps construction and destruction close together instead of far apart mutex.lock();
val f = File.open(filename);
// write to file
f.close();
mutex.unlock();And yet in practice, it’s really not that confusing. Expressivity counts for more than the number of branch opcodes generated by the compiler.
Flowcharts feel like a simple and universal way of talking about, well, control flow, but they imply a certain kind of bias toward a kind of reasoning which isn't necessarily all that better than code itself.
I found the defer diagram very accurate and understandable, but I already knew what "defer" does.
From the preceding examples, I understand that the little box is an instruction the developer didn't write, but was added automatically. From the graph, I understand that the instructions are executed in a different order from what it's written by the developer (and exactly in reverse order).
(It's actually even simpler than that when accounting for the functor and monad properties of Result<T, Err>, but the graphical representation for a "functor" or "monad" is a bit more complex; these would be drawn as labeled regions, and functor and monad properties would describe how such regions can be "merged" or "combined".)
What do you mean?