Question

I am building a common interface for several different backends that are shared libs loaded at runtime dependend on the used platform. It looks basically like the code below. My problem is, that while 90% of the functions of all backends are the same (just different implementations but same purpose) some of them have features that are not available to other platforms at all.

If I had a wrapper function for all features than they would run into the void for backends that do not support them which I want to avoid. I also don't like the idea of having implementations of backend functions that just return errors.

What would be a good way to have a generic common interface while still being able to call functions specific to a backend if the user wants to limit his application to that platform?

class CommonInterface
{
    void DoA(); // Calls InternalDoA() of loaded backend

    void DoB(); // Calls InternalDoB() of loaded backend

    void DoC(); // Calls InternalDoC() of loaded backend ???
};

class BackendOne
{
    void InternalDoA();

    void InternalDoB();

    // DoC does not exist!
};

class BackendTwo
{
    void InternalDoA();

    void InternalDoB();

    void InternalDoC();
};

Thanks a lot in advance!

Was it helpful?

Solution

I also don't like the idea of having implementations of backend functions that just return errors.

There is usually no one-size-fits-all solution for this. One has to decide on a by-case basis about the most appropriate solution.

Here are some options:

1) Make an empty or "dummy" implementation of DoC, if you know for sure not reacting to a call of this feature C which is not available won't cause any harm from the user's point of view.

2) Return an error / throw an exception if you think the caller must not ignore the fact C is not available. Don't feel unhealthy about it, this is often the correct approach, if you like it or not. If you throw an exception, state this clearly in the documentation, so the API user is demanded to handle it. And if callers think they can ignore the error within their context, they still have the choice to do so.

3) In case you think the user needs to query the availability of a feature C before actually calling / not calling the function "DoC", you could also provide something like bool IsFeatureCAvailable() in the interface (and return an error from DoC if the user calls it though it is not available).

Licensed under: CC-BY-SA with attribution
scroll top