Splitting Tasks into Overridable Methods

Problem
You have several long or complicated tasks in non-sealed classes and want to know how to implement them.

Solution
Split the tasks into two or more protected and overridable methods.

Comments
Inheriting classes can easily redefine individual sub-tasks when complex methods are split up.

Example

// Incorrect implementation.
public class Document {
    public virtual void Read() {
        // Read the document's header.
        ...
        // Read the document's body.
        ...
        // Read the document's footer.
        ...
    }
}

// Correct implementation.
public class Document {
    // Note the method is not overridable.
    public void Read() {
        ReadHeader();
        ReadBody();
        ReadFooter();
    }

    protected virtual void ReadHeader() {
        // Read the document's header.
        ...
    }

    protected virtual void ReadBody() {
        // Read the document's body.
        ...
    }

    protected virtual void ReadFooter() {
        // Read the document's footer.
        ...
    }
}

// New type like Document with additional functionality.
public class DocumentWithImages : Document {
    protected override void ReadBody() {
        // First, read the document's body.
        base.ReadBody();
        // Next, parse any images.
        ...
    }
}

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