4 ms·
Tangential C style survey... For code like this: if (some_function(some_memory) != ERROR) { // ... } else { goto cleanup; } This a
by AceJohnny2 3y ago
Tangential C style survey... For code like this:
if (some_function(some_memory) != ERROR) {
// ...
} else {
goto cleanup;
}
This approaches what I dub "Happy Path Indentation Syndrome" (HPIS), where the "normal"/"happy path" functionality of the code happens under the `// ...` inside the passing scope.
If you have several such functions that can each fail, this approach means your "happy path" follows the deepening scope / indentation.
Instead, I much prefer styling it like this (assuming, obviously, that the "happy path" happens always):
if (some_function(some_memory) == ERROR) {
goto cleanup;
}
// ...
How do people approach this kind of situation?
- AceJohnny2 3y ago> If you have several such functions that can each fail, this approach means your "happy path" follows the deepening scope / indentation. In fact, I once had an interview candidate approach a simple string parsing problem by checking each char in a nested scope, happily going a dozen deep and not seeing a problem!
- whstl 3y agoYour preferred version is often called "guard clause" when it's in the beginning of functions. Although there's nothing preventing them from being in the middle... I do agree that it's much better for readability.
- 01HNNWZ0MV43FF 3y agoIncidentally the latter is sometimes called railway error handling https://blog.logrocket.com/what-is-railway-oriented-programming/ https://blog.logrocket.com/what-is-railway-oriented-programm...
- Alifatisk 3y ago> goto cleanup; Isn’t goto a big no no?
- frankjr 3y agoNot in C - it doesn't have a better / cleaner mechanism for dealing with error situations. https://sourcegraph.com/search?q=context%3Aglobal+repo%3A%5Egithub%5C.com%2Fopenbsd%2Fsrc%24+lang%3Ac+%5E%5Cs*goto+%5Cw%3B%24&patternType=regexp&sm=0 https://sourcegraph.com/search?q=context%3Aglobal+repo%3A%5E... https://sourcegraph.com/search?q=context%3Aglobal+repo%3A%5Egithub%5C.com%2Ftorvalds%2Flinux%24+lang%3Ac+%5E%5Cs*goto+%5Cw%3B%24&patternType=regexp&sm=0 https://sourcegraph.com/search?q=context%3Aglobal+repo%3A%5E...
- Alifatisk 3y agoThat’s so interesting ans goes against everything I’ve been taught during high school and uni!
- AceJohnny2 3y agoThis is one of those lessons that go: 1. Junior level: don't do it 2. Journeyman level: don't do it 3. Master level: don't do it, except when...