Base Classes with Optional Features

Problem
How should you use inheritance when a base class can’t implement a feature and derived classes don’t have to either?

Solution
Make the method in the base class virtual and have it throw a NotSupportedException. Also, expose a virtual Boolean method in derived classes. Clients can use this method to check an optional feature’s availability.

Exception
If only a few derived classes will implement an optional feature, place them in an interface.

Example

public class File {
    // Read is an optional feature.
    public virtual void Read() {
        throw new NotSupportedException("Reading isn't supported.");
    }

    public virtual bool CanRead() {
        return false;
    }
}

public class TextFile : File {
    public override void Read() {
        // Implement the Read feature here.
        ...
    }

    public override bool CanRead() {
        // Inform clients that the Read feature is available.
        return true;
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s