Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

There is a design problem that I came upon while implementing an interface:

Let's say there is a Device interface that promises to provide functionalities PerformA() and GetB(). This interface will be implemented for multiple models of a device. What happens if one model has an additional functionality CheckC() which doesn't have equivalents in other implementations?

I came up with different solutions, none of which seems to comply with interface design guidelines:

  • To add CheckC() method to the interface and leave one of its implementations empty:
interface ISomeDevice
{
    void PerformA();
    int GetB();
    bool CheckC();
}

class DeviceModel1 : ISomeDevice
{
    public void PerformA() { // do stuff }
    public int GetB() { return 1; }
    public bool CheckC() {
        bool res;
        // assign res a value based on some validation
        return res;
    }
}

class DeviceModel2 : ISomeDevice
{
    public void PerformA() { // do stuff }
    public int GetB() { return 1; }
    public bool CheckC() {
        return true; // without checking anything
    }
}

This solution seems incorrect as a class implements an interface without truly implementing all the demanded methods.

  • To leave out CheckC() method from the interface and to use explicit cast in order to call it:
interface ISomeDevice
{
    void PerformA();
    int GetB();
}

class DeviceModel1 : ISomeDevice
{
    public void PerformA() { // do stuff }
    public int GetB() { return 1; }
    public bool CheckC() {
        bool res;
        // assign res a value based on some validation
        return res;
    }
}

class DeviceModel2 : ISomeDevice
{
    public void PerformA() { // do stuff }
    public int GetB() { return 1; }
}

class DeviceManager
{
    private ISomeDevice myDevice;
    public void ManageDevice(bool newDeviceModel)
    {
        myDevice = (newDeviceModel) ? new DeviceModel1() : new DeviceModel2();
        myDevice.PerformA();
        int b = myDevice.GetB();
        if (newDeviceModel)
        {
            DeviceModel1 newDevice = myDevice as DeviceModel1;
            bool c = newDevice.CheckC();
        }
    }
}

This solution seems to make the interface inconsistent.

  • For the device that supports CheckC(): to add the logic of CheckC() into the logic of another method that is present in the interface. This solution is not always possible.

So, what is the correct design to be used in such cases? Maybe creating an interface should be abandoned altogether in favor of another design?

share|improve this question
1  
If being pedantic, I think in this case you are really dealing with two separate interfaces despite them being highly similar. –  zxcdw Jun 4 at 9:44
    
It is true. But consider that in the case that I'm working on there is a dozen of methods that are consistent with the interface except a small verification required by one of the implementations. I mean, the scale of the real problem is bigger than in the example I made up in the post. –  Limbo Exile Jun 4 at 9:52
1  
Explicit casts break abstraction, avoid. Do you need to check C? Can you raise the abstraction level of that and just Check? That way, anything that needs to check something can, and anything that doesn't can simply return true. An interface describes what an object can do, it doesn't describe how it does it, having no-op implementations is completely valid if they are unnecessary. –  Phoshi Jun 4 at 10:00
    
I can raise the abstraction level, in fact it's exactly what I've done before hesitating in the correctness of the design and asking this question. The other implementations have nothing to check, so they just return true. However, I've always thought about the interfaces as describing what an object must do, what an object can do. –  Limbo Exile Jun 4 at 10:08
1  
@LimboExile I disagree; it doesn't break abstraction at all. The fact of the matter is that it doesn't make sense for all objects to have checkC. To insist on treating all devices the same in situations where you need to make use of the differences between them will simply result in loss of information (you won't be able to tell which devices really implement checkC and which don't if you force that interface upon every device). –  Doval Jun 4 at 12:28

2 Answers 2

up vote 2 down vote accepted

Consider this solution:

interface IDevice
{
    void PerformA();
    int GetB();
}

interface INewDevice : IDevice
{
    bool CheckC();
}

class DeviceModel1 : INewDevice
{
    ...
}


class DeviceModel2 : IDevice
{
    ...
}

class DeviceManager
{
    private IDevice myDevice;
    public void ManageDevice(bool newDeviceModel)
    {
        myDevice = (newDeviceModel) ? new DeviceModel1() : new DeviceModel2();
        myDevice.PerformA();
        int b = myDevice.GetB();
        if (newDeviceModel)
        {
            INewDevice newDevice = myDevice as INewDevice;
            bool c = newDevice.CheckC();
        }
    }
}

Wherever you don't care about the difference between an IDevice and an INewDevice, you can use the methods common to both. If you do need behavior specific to new devices, you cast to the new interface, so you don't tie yourself down to any particular implementation.

If the casting bothers you, see this question for ways of creating a new type that may contain a value of type A or B (or C, or ...) and provides a type-safe way of taking actions depending on what the type of the value actually is. I especially like Joey's answer for its use of named parameters and lambdas. You could for example make collections that hold Either<IDevice, INewDevice> and then you can use the Match method to avoid any casting. E.g.

IList<Either<IDevice, INewDevice>> devices = // get a list of devices
foreach (var device in devices) {
    device.Match(
        Left: oldDevice => // things to do if it's an old device
        Right: newDevice => // things to do if it's a new device
    );
}

There's no risk of doing a wrong cast using this approach.

share|improve this answer

It depends a lot, really (now that's a surprise). Here are a few things to consider:

What is the contract of the interface?
If the interface should allow performA and getB, but device2 requires checkC to be called, then it does not adhere to the interface. If the interface defines that C must be checkable, then device1 does not adhere. If your algorithm uses that check, it might be the latter.

Can you define a reasonable default behavior?
If it's just a check you could always return true.

Is it an optional operation?
Define it to be optional. The interface might specify that throwing an exception is allowed. Add another method CanCheckC that returns whether the operation is supported. Or add TryCheckC that returns true iff a check was performed and returns the result in an out-parameter.

Is it a new type of interface?
If, in general, devices can't check C but some class of device can, maybe this is a new interface. So add a new interface IDeviceWithCCheck that provides the additional operations and use type checks in your algorithm before you cast.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.