API question: Delagates/FPs or Interface?

Robert Fraser fraserofthenight at gmail.com
Tue Apr 17 11:46:38 PDT 2007


Hi all,

I'm working on a new NAT/firewall traversal library in D right now, and I have a question for you all: since D has enough expressive power to expose both function pointers and interfaces, which would you prefer for a set of "callback" functions. In particular, the library allows a client to start establishing a connection in a separate thread, and when the state of the connection changes, a function is called to inform the client.

I had two possible solutions in mind:
1. Create an interface with the required methods (such as onFailedState, onErrorState, onSuccessState, etc.) specified. The library takes a pointer to an implementing object and calls the methods through that.
2. Accept a set of function pointers or delegates (I'll overload the methods so either is acceptable), and call the functions through that. One advantage of this is that a single callback function is easily interchangeable without having to re-implement the entire interface, and it promotes code reuse because a client might want to implement, for example, only a single onFailedState method, but have a different onSuccessState for different types of connections.

If you think the first option would be better for something like this, there are a couple of other places with a single callback function is needed (for example, to deal with an incoming connection invitation) that don't fit into a set... Should these be interfaces as well?

Thanks for whatever input you have,
All the best,
Robert Fraser



More information about the Digitalmars-d mailing list