|
Archives
D Programming
DD.gnu digitalmars.D digitalmars.D.bugs digitalmars.D.dtl digitalmars.D.dwt digitalmars.D.announce digitalmars.D.learn digitalmars.D.debugger C/C++ Programming
c++c++.announce c++.atl c++.beta c++.chat c++.command-line c++.dos c++.dos.16-bits c++.dos.32-bits c++.idde c++.mfc c++.rtl c++.stl c++.stl.hp c++.stl.port c++.stl.sgi c++.stlsoft c++.windows c++.windows.16-bits c++.windows.32-bits c++.wxwindows digitalmars.empire digitalmars.DMDScript |
D - Delegates vs interfaces
Another interesting subject of debate, that unfortunately often gets hidden
behind the opinions of biased people (with, say, commercial interests in one
of the two).
The design problem is this: how to allow users to register a handler for
asynchronous events
Two alternative approaches exist:
class SomeComponent
{
// 1. using delegates
void registerForEvents( delegate handler )
// 2. using interfaces
void registerForEvents( interface handler )
}
I argue that neither approach is better or more simple or more expressive
than the other, it depends on the use case
1) When the component supports a single event (say 'OnTimer') and you don't
need any context to handle it, use a delegate
2) When the single OnTimer event must be handled by a specific object (e.g.
it represents a timeout on one of multiple connections), use an interface.
In this case implemented by the Connection class. The context ('this')
can then be used inside the handler function of the connection
3) When the component supports multiple kinds of events, and the client is
required to handle them all, use an interface.
An interface can define a group of related handler functions, and forces
the user to implement them all.
4) When the component supports multiple events, but some clients are only
interested in one or few of those, use a delegate for each separate event.
This avoids the well-known 'Java Adapter' problem where you need to
provide an empty implementation for all interface methods, and override
only the ones you want to handle.
5 [ maybe you can think of more cases ]
So D (and any other useful programming language) should offer support for
both, and programmers should decide on a case-by-case basis which one to use
As for "signals and slots", to me that seems different terminology for the
same issue. A "signal" is a stateless event originally coming from Unix
AFAIK (typical example being the 'kill' signal), with an implicit context
being the application that receives the signal. "delegate" seems to be
corresponding language concept usable to implement it. "slot" would then be
the handler function itself. It's nothing new though, and delegates &
interfaces are more generic: they can have parameters (state)
Sep 06 2003
"Jeroen van Bemmel" <someone somewhere.com> wrote in message news:bjclj0$1vgq$1 digitaldaemon.com...Another interesting subject of debate, that unfortunately often gets Sep 08 2003
|