3 ms·
> Avoid callbacks in your API This is good advice especially if you want to write bindings for other languages, including callbacks (as I've found) adds a lot
by radarsat1 14y ago
> Avoid callbacks in your API
This is good advice especially if you want to write bindings for other languages, including callbacks (as I've found) adds a lot of difficulty to that stage.
However, two main projects I work on use callbacks extensively. The reason is that they are essentially event-based, and it would seem much less user-friendly to force the user to implement a huge switch statement, particularly when user-defined events are involved.
How else could callbacks be avoided? In some cases, they just seem like the most user-friendly option.
Although for bindings they are more difficult, using callbacks can be great when binding to higher-level languages, where the user can specify what should happen using a short lambda function (e.g. Python, etc.) A switch statement or whatever is much more obnoxious in those cases, so what other solutions are there?
- justincormack 14y agoInterfaces like epoll let you pass and return you a 64 bit value which can be an address of a callback or a value to look up in a dispatch table. The user can choose. This is very flexible.
- ambrop7 14y agoA very nice feature of epoll is that an epoll file descriptor (which monitors a set of file descriptors) can itself be monitored via epoll/select/poll. This means that if epoll is available, a library can abstract all its I/O via a single file descriptor. Think of a complex operation that involves multiple sockets and timer events. All the user needs to do is monitor this one file descriptor in his event loop, and call a function in the library which determines which of its own file descriptors have become ready, and reacts appropriately, possibly by calling callbacks if the user needs to be notified. Unfortunately if you're trying to be portable, you can't do this, and instead have to implement a complete event notification abstraction (unless you know you will only ever be dealing with this one file descriptor). E.g. user of the library needs to implement functions like addWait(fd, io_type, callback), delWait(wait_id), addTimeout(milliseconds, callback), delTimeout(timeout_id).