API question: Delagates/FPs or Interface?

Dan murpsoft at hotmail.com
Tue Apr 17 12:25:31 PDT 2007


Hi Robert,

I would write an array of structs such that the function probing/handling the state change already has the appropriate struct in hand, and merely looks up the callback, and also has the name of the callback on hand (such as "onErrorState" as a char[])

Any other relevant metadata may also be attached; according to performance refactoring and such considerations.

Does this help, should I rephrase it, or does that not work?

Sincerely,
Dan

~~~~~~~~
Robert Fraser Wrote:
> 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