github twitter email rss
Pattern: Special Case
0001 Jun 1
2 minutes read

Pattern: Special Case

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.

How it works

The basic idea is to create a subclass to handle the Special Case. Thus, if you have a customer object and you want to avoid null checks, you make a null customer object. Take all of the methods for customer and override them in the Special Case to provide some harmless behavior. Then, whenever you have a null, put in an instance of null customer instead.

There’s usually no reason to distinguish between different instances of null customer, so you can often implement a Special Case with a flyweight [Gang of Four]. You can’t do it all the time. For a utility you can accumulate charges against an occupant customer even you can’t do much billing, so it’s important to keep your occupants separate.

A null can mean different things. A null customer may mean no customer or it may mean that there’s a customer but we don’t know who it is. Rather than just using a null customer, consider having separate Special Cases for missing customer and unknown customer.

A common way for a Special Case to override methods is to return another Special Case, so if you ask an unknown customer for his last bill, you may well get an unknown bill.

IEEE 754 floating-point arithmetic offers good examples of Special Case with positive infinity, negative infinity, and not-a-number (NaN). If you divide by zero, instead of getting an exception that you have to deal with, the system just returns NaN, and NaN participates in arithmetic just like any other floating point number.

Further Reading

I haven’t seen Special Case written up as a pattern yet, but Null Object has been written up. If you’ll pardon the unresistable pun, I see Null Object as special case of Special Case

[Patterns of Enterprise Application Architecture]()


Back to posts


comments powered by Disqus