2 ms·
> I suppose experienced developers do as little as possible in callbacks (talking about C/C++ mostly) I have personally come to embrace the opposite approach:
by ambrop7 9y ago
> I suppose experienced developers do as little as possible in callbacks
(talking about C/C++ mostly)
I have personally come to embrace the opposite approach: let callbacks do absolutely anything someone could do outside of a callback. This way, code gets simpler and clearer. For example, if a Socket object contained in HttpConnection calls back to HttpConnection telling it the connection is dead, the HttpConnection class should be able to just do something like "server->connections.remove(this); return;". Yes that remove is HttpConnection self-destructing; after that statement HttpConnection and the Socket no longer exist.
Ensuring safety of this is really simple: whenever you call a callback, the next statement must be "return" and more specifically you must return back to who called you without touching anything which might be dead now. Or perhaps more idiomatically you can "return callback();" when both the callback and the calling function return void.
In the case that you would want to do something after the callback is done, instead ask the event loop to call you "soon", and make sure your destructor will cancel that. For example this can be just a timer with zero timeout, or a special event queue designed for this purpose (in which case LIFO scheduling will get you natural "recursive" evaluation order).
- passthefist 9y ago> Or perhaps more idiomatically you can "return callback();" when both the callback and the calling function return void At least in JS I think that is idiomatic, it's an option for linting: https://eslint.org/docs/rules/callback-return https://eslint.org/docs/rules/callback-return.