4 ms·
I've been in the "only a single return" and "early return plz" camps at various points in my career. Right now? I'm early return. When I wrote C and C++ code
by jpollock 11y ago
I've been in the "only a single return" and "early return plz" camps at various points in my career.
Right now? I'm early return.
When I wrote C and C++ code with locks and malloc/free? One exit only.
It's all about avoiding bugs.
In C code heavy with locks and memory allocation, you need to make sure your post-conditions are correct. That is near impossible when there is more than one return [1].
In C++, with RAII and Java with "try-with-resources", I can ensure proper cleanup. At that point, it's about making it easy for someone who is reading the code to avoid screwing it up. I need to make it easy for them to flow through the code, keeping the cognitive load as low as possible. Functions do what they say on the box and _only_ what they say on the box. At that point, my goal is to make a decision, act on it and move on. I don't want to carry that state forward - it means I have to keep it in mind for every line after it. I'm even trending towards having the majority of the methods in my classes be static functions with no state.
Finally, if I've got a function that has two different flows and I'm deciding between them with an if? I've probably actually got two different functions pretending to be one. I then try to refactor and get rid of the if.
[1] http://programmers.stackexchange.com/questions/154974/is-this-a-decent-use-case-for-goto-in-c/154980#154980 http://programmers.stackexchange.com/questions/154974/is-thi...
- legulere 11y agoBut in C you usually use `goto Error;` which basically is just a `return` + you can do the cleanup yourself.
- CyberDildonics 11y agoThat means that you have to put all your unlocks and deallocations there AND you have to check them to see if they were allocated/locked in the first place.