Patterncore
Special case
Also called Special Case, special case subclass.
A special case is a subclass, or another implementation of the same interface, that gives the behavior for a particular case, such as a missing customer, in place of null.
- Family
- architectural
- Intent
- Return an object with the special behavior in place of null or an odd value.
Intent
A special case is "A subclass that provides special behavior for particular cases."1 When a finder has no normal object to return, it returns a special case object. The special case has the same interface as the normal object, so the callers need no test for null.
Problem
The catalog says: "Nulls are awkward things in object-oriented programs because they defeat polymorphism."1 A caller can call a method on any object of the right type. But if the variable can be null, the call fails when the program runs.
So each caller must test for null and decide what to do. Often each caller does the same thing, for example it shows a default name. The test and the default are then copied in many places, and one place that forgets the test fails. Null is not the only case. The catalog also names infinity, "which has special rules for things like addition that break the usual invariants of real numbers".1
Solution
The catalog says: "Instead of returning null, or some odd value, return a Special Case that has the same interface as what the caller expects."1 The parts are:
- The normal type. It is a class or an interface that the callers use, such as
Customer. - The special case. It is a subclass of the normal class, or another implementation of the interface, such as
UnknownCustomer. It gives the behavior that the callers would otherwise write after a test for null: a default name, an empty list, zero. - The source. A finder or a factory returns the special case in place of null.
- A way to ask, if needed. A method such as
is_known()lets the few callers that must act differently find the special case without a type test.
find_customer(1) -> Customer(Ann) .bill_line() -> "customer 1: Ann, ..."
find_customer(9) -> UnknownCustomer(9) .bill_line() -> "customer 9: current resident, ..."
callers: c.bill_line() (no test for None)
In the following program, a visitor that has not signed in gets an AnonymousUser, which is a special case of User.
class User:
is_authenticated = True
def __init__(self, name):
self.name = name
def greeting(self):
return f"hello, {self.name}"
class AnonymousUser(User): # the special case for a visitor who has not signed in
is_authenticated = False
def __init__(self):
super().__init__("")
def greeting(self):
return "hello, guest"
sessions = {"s1": User("Ann")}
def current_user(session_id):
return sessions.get(session_id, AnonymousUser())
for s in ["s1", "s2"]:
user = current_user(s)
print(user.greeting(), "| signed in:", user.is_authenticated)
hello, Ann | signed in: True
hello, guest | signed in: False
Example
Each example has a normal Customer and an UnknownCustomer special case with the same methods. The finder returns the special case for an ID that has no record. The program finds customers 1, 2 and 9, and prints a bill line for each with no test for null. Customer 9 has no record, so its line shows "current resident" and the basic plan. Last, the program counts the known customers with is_known.
class Customer:
def __init__(self, customer_id, name, plan):
self.customer_id = customer_id
self.name = name
self.plan = plan
def is_known(self):
return True
def bill_line(self):
return f"customer {self.customer_id}: {self.name}, plan {self.plan}"
class UnknownCustomer(Customer):
"""The special case: the same interface, with the behavior for a customer with no record."""
def __init__(self, customer_id):
super().__init__(customer_id, "current resident", "basic")
def is_known(self):
return False
ROWS = {1: ("Ann", "premium"), 2: ("Bob", "basic")}
def find_customer(customer_id):
if customer_id not in ROWS:
return UnknownCustomer(customer_id) # not None
name, plan = ROWS[customer_id]
return Customer(customer_id, name, plan)
customers = [find_customer(i) for i in (1, 2, 9)]
for c in customers:
print(c.bill_line()) # no test for None
print("known customers:", sum(1 for c in customers if c.is_known()))
customer 1: Ann, plan premium
customer 2: Bob, plan basic
customer 9: current resident, plan basic
known customers: 2
- Verdict: idiom.
UnknownCustomeris a subclass ofCustomerthat overridesis_known. Python checks the methods only when the program calls them, so the special case must have each method that the callers use. find_customernever returnsNone, so the loop callsbill_linewith no test.
import java.util.List;
import java.util.Map;
public class Main {
static class Customer {
final int id;
final String name;
final String plan;
Customer(int id, String name, String plan) {
this.id = id;
this.name = name;
this.plan = plan;
}
boolean isKnown() { return true; }
String billLine() { return "customer " + id + ": " + name + ", plan " + plan; }
}
// The special case: the same interface, with the behavior for a customer with no record.
static class UnknownCustomer extends Customer {
UnknownCustomer(int id) { super(id, "current resident", "basic"); }
@Override
boolean isKnown() { return false; }
}
static final Map<Integer, String[]> ROWS = Map.of(
1, new String[] {"Ann", "premium"},
2, new String[] {"Bob", "basic"});
static Customer findCustomer(int id) {
String[] row = ROWS.get(id);
if (row == null) return new UnknownCustomer(id); // not null
return new Customer(id, row[0], row[1]);
}
public static void main(String[] args) {
List<Customer> customers = List.of(findCustomer(1), findCustomer(2), findCustomer(9));
for (Customer c : customers) System.out.println(c.billLine()); // no test for null
System.out.println("known customers: " + customers.stream().filter(Customer::isKnown).count());
}
}
customer 1: Ann, plan premium
customer 2: Bob, plan basic
customer 9: current resident, plan basic
known customers: 2
- Verdict: idiom.
UnknownCustomeris a subclass, so the compiler checks that the finder returns aCustomerand that callers use only its methods. Optional<Customer>is the other common choice. It makes the caller handle the missing case, while a special case gives the caller a default behavior.
class Customer {
constructor(id, name, plan) {
this.id = id;
this.name = name;
this.plan = plan;
}
isKnown() {
return true;
}
billLine() {
return `customer ${this.id}: ${this.name}, plan ${this.plan}`;
}
}
// The special case: the same interface, with the behavior for a customer with no record.
class UnknownCustomer extends Customer {
constructor(id) {
super(id, "current resident", "basic");
}
isKnown() {
return false;
}
}
const ROWS = new Map([
[1, ["Ann", "premium"]],
[2, ["Bob", "basic"]],
]);
function findCustomer(id) {
const row = ROWS.get(id);
if (row === undefined) return new UnknownCustomer(id); // not null
return new Customer(id, ...row);
}
const customers = [1, 2, 9].map(findCustomer);
for (const c of customers) console.log(c.billLine()); // no test for null
console.log("known customers:", customers.filter((c) => c.isKnown()).length);
customer 1: Ann, plan premium
customer 2: Bob, plan basic
customer 9: current resident, plan basic
known customers: 2
- Verdict: idiom.
UnknownCustomerextendsCustomerand overridesisKnown. The finder returns it in place ofnullorundefined. - Optional chaining
?.is the other answer to a missing value: it avoids the error, but each caller must still choose what to show.
package main
import "fmt"
// Customer is the interface that callers use.
type Customer interface {
IsKnown() bool
BillLine() string
}
type knownCustomer struct {
id int
name, plan string
}
func (c knownCustomer) IsKnown() bool { return true }
func (c knownCustomer) BillLine() string {
return fmt.Sprintf("customer %d: %s, plan %s", c.id, c.name, c.plan)
}
// unknownCustomer is the special case: the same interface, with the behavior for a customer with no record.
type unknownCustomer struct{ id int }
func (c unknownCustomer) IsKnown() bool { return false }
func (c unknownCustomer) BillLine() string {
return fmt.Sprintf("customer %d: current resident, plan basic", c.id)
}
var rows = map[int][2]string{1: {"Ann", "premium"}, 2: {"Bob", "basic"}}
func findCustomer(id int) Customer {
row, ok := rows[id]
if !ok {
return unknownCustomer{id} // not nil
}
return knownCustomer{id, row[0], row[1]}
}
func main() {
var customers []Customer
for _, id := range []int{1, 2, 9} {
customers = append(customers, findCustomer(id))
}
known := 0
for _, c := range customers {
fmt.Println(c.BillLine()) // no test for nil
if c.IsKnown() {
known++
}
}
fmt.Println("known customers:", known)
}
customer 1: Ann, plan premium
customer 2: Bob, plan basic
customer 9: current resident, plan basic
known customers: 2
- Verdict: idiom. Go has no subclasses, so
Customeris an interface and the special case is a second type that implements it. - A nil interface value would panic on
c.BillLine(). The finder returnsunknownCustomerand never nil.
use std::collections::HashMap;
// Customer is the interface that callers use.
trait Customer {
fn is_known(&self) -> bool;
fn bill_line(&self) -> String;
}
struct KnownCustomer {
id: u32,
name: String,
plan: String,
}
impl Customer for KnownCustomer {
fn is_known(&self) -> bool {
true
}
fn bill_line(&self) -> String {
format!("customer {}: {}, plan {}", self.id, self.name, self.plan)
}
}
// The special case: the same interface, with the behavior for a customer with no record.
struct UnknownCustomer {
id: u32,
}
impl Customer for UnknownCustomer {
fn is_known(&self) -> bool {
false
}
fn bill_line(&self) -> String {
format!("customer {}: current resident, plan basic", self.id)
}
}
fn find_customer(rows: &HashMap<u32, (&str, &str)>, id: u32) -> Box<dyn Customer> {
match rows.get(&id) {
Some((name, plan)) => Box::new(KnownCustomer { id, name: name.to_string(), plan: plan.to_string() }),
None => Box::new(UnknownCustomer { id }), // not an Option that each caller must check
}
}
fn main() {
let rows = HashMap::from([(1, ("Ann", "premium")), (2, ("Bob", "basic"))]);
let customers: Vec<Box<dyn Customer>> = [1, 2, 9].iter().map(|&id| find_customer(&rows, id)).collect();
for c in &customers {
println!("{}", c.bill_line());
}
println!("known customers: {}", customers.iter().filter(|c| c.is_known()).count());
}
customer 1: Ann, plan premium
customer 2: Bob, plan basic
customer 9: current resident, plan basic
known customers: 2
- Verdict: idiom.
Customeris a trait, andUnknownCustomeris a second type that implements it. The finder returnsBox<dyn Customer>. - Rust has no null references. Without the special case, the finder would return
Option, and each caller would have to handleNone.
Consequences
Benefits.
- No repeated tests for null. The default behavior is in one class, and not in each caller.
- No errors from a missing test. The finder never returns null, so no caller can forget the test.
- Polymorphism works again. The callers call the same methods on each object, and each class gives its own behavior.
Liabilities.
With null, one caller that forgets the test fails. In the following program, the finder returns None for a customer with no record. The code for the name tests for None, but the code for the plan forgets it.
This code runs but gives a wrong answer on purpose.
class Customer:
def __init__(self, name, plan):
self.name, self.plan = name, plan
ROWS = {1: Customer("Ann", "premium")}
def find_customer(customer_id):
return ROWS.get(customer_id) # None when there is no record
def name_on_bill(customer_id):
c = find_customer(customer_id)
return "current resident" if c is None else c.name
def plan_on_bill(customer_id):
return find_customer(customer_id).plan # this place forgets the test for None
print("name:", name_on_bill(9))
try:
print("plan:", plan_on_bill(9))
except AttributeError as e:
print("AttributeError:", e)
name: current resident
AttributeError: 'NoneType' object has no attribute 'plan'
Return an UnknownCustomer with the name "current resident" and the plan "basic", and remove the tests for None from the callers.
Errors can hide. If the missing object is an error, such as a broken foreign key, a special case lets the program continue with wrong data. The program must decide which missing cases are normal.
One more class for each case. Each special case is a class to keep in step with the normal class. When the normal class gets a new method, each special case needs it too.
The callers can still need to know. Some code must act differently for the special case, for example a report that counts only the known customers. The interface then needs a method such as is_known.
When not to use it
When the callers must handle the missing case themselves. If each caller does something different, there is no default behavior to put in a class. An optional type, such as Optional in Java or Option in Rust, makes each caller handle the case.
When the missing value is an error. Raise an exception or return an error. A special case would hide the problem.
Variants and related patterns
Null object. The Null Object is a special case for a missing object whose methods do nothing. The book names Null Object as a kind of special case.2
Several special cases. One type can have more than one special case, for example one for a customer with no record and one for a customer whose record is not yet loaded. Each one has its own behavior.
Refactoring. The refactoring Introduce special case replaces the repeated tests for a special value with a special case object.
Related ideas. Null reference and nullability describe the problem that the pattern solves. A special case with no state of its own can be one shared instance, because no caller can change it. A Test double is a different idea: it replaces an object in a test, not in the program.
Known uses
- Django gives an
AnonymousUserfor a visitor that has not signed in: "django.contrib.auth.models.AnonymousUser is a class that implements the django.contrib.auth.models.User interface".3 For example, itsis_authenticatedis False and itsidis always None.3
References
- Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Special Case, pattern summary
- Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 18, Base Patterns, Special Case
- Django documentation, django.contrib.auth, AnonymousUser object
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 3ZYVBP Edit this page History Report an error Markdown