Re: Runtime optional interface
Sounds like you have some conflicting requirements. You don't want to
tell the user the interface isn't available (by returning a null
pointer), nor do you want to give him errors when he invokes methods on
the interface. The only way I can see to achieve that is to not make
the interface optional.
Now, a lot of the solution will depend upon what your design goals
actually are. Do you want the interface to always be there, but the
implementation loaded only if it's used? Do you want to deny
functionality unless they install some add-on?
My first thought would be a Interface * queryInterface() sort of
approach where you either get back a valid pointer to the interface or a
NULL. If you don't want to return a NULL, you could throw at this point
and make them deal with it in some other fashion. The nice thing here
is that if you just don't want the overhead of loading the
implementation if it isn't needed, you could have this method create the
instance that implements the interface at this point (much like some of
the singleton patterns).
C++ is a statically typed language. One of the effects of this is that
the user either uses the optional interface or he doesn't when his code
is compiled. If he doesn't, no problem. If he does, then he needs
access to the interface whether the interface is "available" or not.
Now, if the implementation is always available if he is going to use the
interface, then, again, there is no problem. The problem comes in when
the user doesn't know if he has the interface or not. In this scenareo
the user has to test for the presence of the interface in order to take
the correct code path. There are a lots of ways you can provide for him
to test this. You could provide a method bool hasInteface(), you can
let him query the interface and test if it exists (the Interface *
queryInterface() approach), you can have the interface methods fail if
they aren't available, or some variant of these. Personally I would be
really annoyed at a error from the interface methods. I would much
rather make my codepath choice up front.
A last approach is to make everything dynamic (such as they do with
things like browser addons). The problem with this approach is that the
user still has to deal with whether or not the interface is available
and he always has to invoke methods in some interpreted sort of fashion.
Good luck with your problem,
joe