On 2012-02-16 11:23, Jonathan M Davis wrote:
On Thursday, February 16, 2012 11:11:20 Jacob Carlborg wrote:
You can create an abstract class that implements some parts of the
interface. Then the user (developer) is free to choose to inherit from
the interface or the abstract class.
Which results in a classic problem that you run into in Java all the time when
dealing with event-based programming (since it deals with events via
interfaces). If you have a class that only really needs to implement a couple
of the functions from the interface of an event listener, then you can derive
from the class which implements it and gives them all empty bodies. But if you
need your class to implement multiple such interfaces, you can only do that
with one of them, which gets really annoying, because then you have to create
a bunch of empty method bodies yourself. It's one of the classic examples
where multiple inheritance would be desirable.
Interfaces and abstract classes is the simple solution. If the class
hierarchy is quite simple won't be a problem. It looks like it is quite
simple in this case. Or one could skip the interface completely perhaps.
The current situation in D is exactly the same (though, since we don't have a
swing equivalent, I don't think that it's something that D programmers are
frequently running into at the moment). AIUI, Java is going to be adding the
ability to give interfaces default implementations such that that
implementation is effectively copy-pasted into your class when you implement it
and don't provide an implementation yourself (rather than the function in your
class overidding it as would be the case with an abstract class). This nicely
solves the event listener problem, and D doesn't have that. I assume that
that's the sort of thing that the OP is looking for.
Since D have delegates I would use those for event handling and not
listeners. I think they are a much better fit, as long as you don't have
to force the user to handle many different events on the same object.
Now, if you use template mixins, I believe that it's possible to use that to
mixin default implementations for the functions in an interface, which should
solve the problem for D. So, that's probably good enough for D without having
to make it so that interface functions can have default implementations.
- Jonathan M Davis
Template mixins cause their own problems. You can't overload methods
with template mixins, may it's possible to get around that with aliases,
I don't remember.
--
/Jacob Carlborg