architect-handbook

Software Architect Handbook

View on GitHub

Special Case

A subclass that provides special behavior for particular cases.

Overview

Nulls are awkward things in object-oriented programs because they defeat polymorphism. If it’s possible for a variable to be null, you have to remember to surround it with null test code so you’ll do the right thing if a null is present. You often end up writing similar code in lots of places.

Nulls are a common example of such problems and others crop up regularly (e.g., dealing with infinity, which has special rules for things like addition that break the usual invariants of real numbers).

Instead of returning null, or some odd value, return a Special Case that has the same interface as what he caller expects.

How It Works

When to Use It

Use Special Case whenever you have multiple places in the system that have the same behavior after a conditional check for a particular class instance, or the same behavior after a null check.