Programming Search⌘K

Patternadvanced

Downcasting

Also called downcast smell, instanceof chain.

A code smell: code tests the run-time class of an object and casts it to a subclass to reach what it needs, because the type it was given does not offer that operation.

Family
code-smell
Intent
Find the casts from a general type to a specific one, and give the general type the operation, or keep the specific type, so that the cast is not needed.
Also called
type refinement

Intent

Find the places where code takes an object of a general type, checks which subclass it really is, and casts it to that subclass to read a field or call a method. Each such place says that the general type lacks something the code needs. Give the general type that operation, or keep the specific type in the variable from the start, so that the cast is not needed.

Problem

Wikipedia defines downcasting as "the act of casting a base or parent class reference, to a more restricted derived class reference", and notes that it "is only allowable if the object is already an instance of the derived class, and so this conversion is inherently fallible."1 The opposite move, an upcast, "is always possible."1

Its list of code smells describes the smell in one line: "a type cast which breaks the abstraction model; the abstraction may have to be refactored or eliminated."2 The code was given a Notice, but it needs an EmailNotice. Either Notice should offer what the code needs, or the code should never have lost the more specific type.

The forces are these:

  • The check moves from compile time to run time. Wikipedia's example shows a Java method that casts an Object to a String, and says that "downcasting prevents the compiler from detecting a possible error and instead causes a run-time error."1
  • Each cast is a list of the subclasses. Code that tests for each subclass in turn must be changed when a subclass is added, and the code that forgets one fails at run time. This is the same cost as Repeated Switches, with the class as the switch value.
  • Containers of the top type force it. Wikipedia gives as its example of a badly considered design the "containers of top types", such as the Java containers before generics, which require "downcasting of the contained objects so that they can be utilised again."1
  • The language can make the cast safe but not remove the need. The Go specification says of a type assertion x.(T): "If the type assertion is false, a run-time panic occurs." The form v, ok := x.(T) gives a boolean in place of the panic, and "No run-time panic occurs in this case."3 JEP 394 adds a type pattern to Java's instanceof, because the instanceof-and-cast idiom is "tedious" and "the repetition provides opportunities for errors to creep unnoticed into programs."4 These forms make each cast safer. The design question, why the code needs a cast at all, stays.

Solution

Choose the fix by why the code lost the type.

  1. The operation belongs on the general type. Each subclass knows how to do it in its own way. Add the operation to the base class or interface, and let each subclass implement it. This is Replace Conditional with Polymorphism, with the type test as the conditional; the catalogue at refactoring.com has a card for it.5 The call is then a dynamic dispatch.
  2. The code that needs the specific type is in the wrong place. Move it into the subclass with Move Function, or call it at the point where the specific type is still known.5
  3. A container or a callback lost the type. Use a generic type, so that a list of Email stays a list of Email. See Parametric polymorphism.
  4. The set of cases is closed and known. Some data is a fixed set of shapes, such as the nodes of a syntax tree or the results of a parser. Make it a sum type (a sealed interface in Java, a union of tagged objects in TypeScript), and use pattern matching that the compiler checks for missing cases. This is a type test by design, not a smell.

Some casts stay. Code at the edge of a program, which reads JSON, a message from a queue or an object from a plugin, gets a value whose type it cannot know ahead. A check of the type there is a validation, and it should happen once, at the edge, so that the code inside works with the checked type.

Example

A program sends notices. The function that writes the log line takes a Notice, tests for each subclass, and reads the field that each subclass has. When the team adds push notices, the function throws at run time, and nothing warned them.

import assert from "node:assert/strict";

// Before: the base class has no operation, so the client tests and reaches into subclasses.
class NoticeBefore {}
class EmailNoticeBefore extends NoticeBefore {
  constructor(address) { super(); this.address = address; }
}
class SmsNoticeBefore extends NoticeBefore {
  constructor(phone) { super(); this.phone = phone; }
}
class PushNoticeBefore extends NoticeBefore {
  constructor(device) { super(); this.device = device; }
}
function logLineBefore(notice) {
  if (notice instanceof EmailNoticeBefore) return `email to ${notice.address}`;
  if (notice instanceof SmsNoticeBefore) return `sms to ${notice.phone}`;
  throw new TypeError(`unknown notice ${notice.constructor.name}`);
}

// After: each class says how it is described, and the client calls one method.
class Notice {
  describe() { throw new Error("subclass must implement describe"); }
}
class EmailNotice extends Notice {
  constructor(address) { super(); this.address = address; }
  describe() { return `email to ${this.address}`; }
}
class SmsNotice extends Notice {
  constructor(phone) { super(); this.phone = phone; }
  describe() { return `sms to ${this.phone}`; }
}
class PushNotice extends Notice {
  constructor(device) { super(); this.device = device; }
  describe() { return `push to ${this.device}`; }
}
const logLine = (notice) => notice.describe();

assert.equal(logLineBefore(new EmailNoticeBefore("ada@example.com")), "email to ada@example.com");
assert.equal(logLine(new EmailNotice("ada@example.com")), "email to ada@example.com");
assert.equal(logLine(new SmsNotice("+15550100")), logLineBefore(new SmsNoticeBefore("+15550100")));
assert.throws(() => logLineBefore(new PushNoticeBefore("tablet-7")), TypeError); // the subclass that the chain forgot
assert.equal(logLine(new PushNotice("tablet-7")), "push to tablet-7");
console.log("notices: tests pass");
Output
notices: tests pass

In the second version, a class that is added must say how it is described, and the log function does not change. In JavaScript the reminder is a method that throws; in Java and Go, as the examples show, the compiler gives the reminder.

Language What the example shows
JavaScript an instanceof chain, replaced by a method on each class, as above
Python an isinstance chain, replaced by an abstract method with abc
Java a raw List with casts and a ClassCastException, replaced by a generic list, and a cast chain replaced by an interface method
Go type assertions on an interface, replaced by a method in the interface
PythonGitHub
from abc import ABC, abstractmethod


# Before: the client tests the class and reaches into each subclass.
class NoticeBefore:
    pass


class EmailNoticeBefore(NoticeBefore):
    def __init__(self, address):
        self.address = address


class SmsNoticeBefore(NoticeBefore):
    def __init__(self, phone):
        self.phone = phone


class PushNoticeBefore(NoticeBefore):
    def __init__(self, device):
        self.device = device


def log_line_before(notice):
    if isinstance(notice, EmailNoticeBefore):
        return f"email to {notice.address}"
    if isinstance(notice, SmsNoticeBefore):
        return f"sms to {notice.phone}"
    raise TypeError(f"unknown notice {type(notice).__name__}")


# After: an abstract method, so each subclass must say how it is described.
class Notice(ABC):
    @abstractmethod
    def describe(self): ...


class EmailNotice(Notice):
    def __init__(self, address):
        self.address = address

    def describe(self):
        return f"email to {self.address}"


class SmsNotice(Notice):
    def __init__(self, phone):
        self.phone = phone

    def describe(self):
        return f"sms to {self.phone}"


class PushNotice(Notice):
    def __init__(self, device):
        self.device = device

    def describe(self):
        return f"push to {self.device}"


def log_line(notice):
    return notice.describe()


assert log_line(EmailNotice("ada@example.com")) == log_line_before(EmailNoticeBefore("ada@example.com"))
assert log_line(SmsNotice("+15550100")) == "sms to +15550100"
assert log_line(PushNotice("tablet-7")) == "push to tablet-7"
try:
    log_line_before(PushNoticeBefore("tablet-7"))
    raise AssertionError("the chain should not know push notices")
except TypeError:
    pass


# A subclass that forgets the method cannot be made at all.
class FaxNotice(Notice):
    pass


try:
    FaxNotice()
    raise AssertionError("an abstract method was not implemented")
except TypeError:
    pass
print("notices: tests pass")
Output
notices: tests pass

With abc.ABC and @abstractmethod, Python refuses to make an instance of a subclass that does not implement describe, so the mistake shows when the object is made, not when the log line is written.

JavaGitHub
import java.util.ArrayList;
import java.util.List;

public class Main {
    // Before: an abstract class with no operation, and casts in the client.
    abstract static class NoticeBefore {}

    static final class EmailBefore extends NoticeBefore {
        final String address;
        EmailBefore(String address) { this.address = address; }
    }

    static final class SmsBefore extends NoticeBefore {
        final String phone;
        SmsBefore(String phone) { this.phone = phone; }
    }

    static String logLineBefore(NoticeBefore n) {
        if (n instanceof EmailBefore) {
            return "email to " + ((EmailBefore) n).address;
        }
        if (n instanceof SmsBefore) {
            return "sms to " + ((SmsBefore) n).phone;
        }
        throw new IllegalArgumentException("unknown notice " + n.getClass().getSimpleName());
    }

    // After: the interface has the operation. A class that implements Notice
    // and has no describe method does not compile.
    interface Notice {
        String describe();
    }

    record Email(String address) implements Notice {
        public String describe() { return "email to " + address; }
    }

    record Sms(String phone) implements Notice {
        public String describe() { return "sms to " + phone; }
    }

    record Push(String device) implements Notice {
        public String describe() { return "push to " + device; }
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    public static void main(String[] args) {
        check(logLineBefore(new EmailBefore("ada@example.com")).equals(new Email("ada@example.com").describe()), "email");
        List<Notice> notices = List.of(new Email("ada@example.com"), new Sms("+15550100"), new Push("tablet-7"));
        List<String> lines = new ArrayList<>();
        for (Notice n : notices) {
            lines.add(n.describe());
        }
        check(lines.equals(List.of("email to ada@example.com", "sms to +15550100", "push to tablet-7")), "lines");

        // A container of the top type: the compiler cannot check what comes out.
        List raw = new ArrayList();
        raw.add("ada@example.com");
        raw.add(42);
        boolean failed = false;
        try {
            for (Object o : raw) {
                String address = (String) o;
                check(address.contains("@"), "address");
            }
        } catch (ClassCastException e) {
            failed = true;
        }
        check(failed, "the cast should fail at run time");

        // A generic container keeps the type, so no cast is needed,
        // and raw.add(42) on a List<String> would not compile.
        List<String> addresses = new ArrayList<>();
        addresses.add("ada@example.com");
        for (String address : addresses) {
            check(address.contains("@"), "generic address");
        }
        System.out.println("notices: tests pass");
    }

    static void check(boolean ok, String what) {
        if (!ok) {
            throw new AssertionError(what);
        }
    }
}
Output
notices: tests pass

The raw List is the container of the top type that Wikipedia names: it holds Object, so each element must be cast back, and the wrong element fails with a ClassCastException at run time. The generic List<String> keeps the type, and the compiler rejects the wrong element. Since JDK 16, the cast after instanceof can be written as n instanceof EmailBefore e, which removes the repeated type name, but not the chain of tests.

package main

import "fmt"

// Before: an interface with no methods, and type assertions in the client.
type NoticeBefore interface{}

type EmailBefore struct{ Address string }
type SmsBefore struct{ Phone string }
type PushBefore struct{ Device string }

func logLineBefore(n NoticeBefore) (string, error) {
	if e, ok := n.(EmailBefore); ok {
		return "email to " + e.Address, nil
	}
	if s, ok := n.(SmsBefore); ok {
		return "sms to " + s.Phone, nil
	}
	return "", fmt.Errorf("unknown notice %T", n)
}

// After: the interface has the operation, and each type implements it.
// A type without Describe does not satisfy Notice, and the compiler says so.
type Notice interface{ Describe() string }

type Email struct{ Address string }
type Sms struct{ Phone string }
type Push struct{ Device string }

func (e Email) Describe() string { return "email to " + e.Address }
func (s Sms) Describe() string   { return "sms to " + s.Phone }
func (p Push) Describe() string  { return "push to " + p.Device }

func logLine(n Notice) string { return n.Describe() }

func main() {
	before, err := logLineBefore(EmailBefore{"ada@example.com"})
	if err != nil || before != logLine(Email{"ada@example.com"}) {
		panic("email")
	}
	if logLine(Sms{"+15550100"}) != "sms to +15550100" || logLine(Push{"tablet-7"}) != "push to tablet-7" {
		panic("after")
	}
	if _, err := logLineBefore(PushBefore{"tablet-7"}); err == nil {
		panic("the chain should not know push notices")
	}

	// The single-value form of a type assertion panics when it is false.
	func() {
		defer func() {
			if recover() == nil {
				panic("expected a panic")
			}
		}()
		var n NoticeBefore = SmsBefore{"+15550100"}
		_ = n.(EmailBefore).Address
	}()
	fmt.Println("notices: tests pass")
}
Output
notices: tests pass

An empty interface accepts any value, so the before version compiles whatever the caller passes, and finds out at run time. The interface with a Describe method moves that check to the compiler: a call logLine(Fax{}) with a type that has no Describe does not compile.

Consequences

The operation has one name, and each type keeps its own version of it. A reader of the client sees one call, and a type that is added cannot be forgotten by a chain of tests that it does not know about.

The base type grows. Each operation that a client needs becomes a method on the base type, and a base type with many methods that only one client uses is a Large Class in the making. When many unrelated operations must work over a fixed set of subclasses, the operations may belong outside the classes. The Visitor pattern and a sum type with pattern matching both keep the operations together and keep the compiler's check for missing cases.

The two fixes trade in opposite directions. With methods on the classes, a class costs little to add and an operation costs a change to each class. With a sum type and pattern matching, an operation costs little to add and a case costs a change to each match. Choose by which of the two changes more often.

How to fix it

  • The cast reaches a behaviour that each subclass has in its own way: move the behaviour onto the base type with Replace Conditional with Polymorphism.5
  • The cast reaches a behaviour that only one subclass has: move the code that needs it into that subclass with Move Function, or call it where the subclass is still known.5
  • The cast undoes a container of the top type: use a generic container.1
  • The cases are closed: use a sum type and a checked pattern match.
  • The cast is at the edge of the program: keep it, check once, and pass the checked type inward.

Repeated Switches. A chain of type tests is a switch on the class. See Repeated Switches.

Refused Bequest. A subclass that does not support what its parent offers forces the clients to test for it. See Refused Bequest.

Type conversion. A downcast is one kind of conversion between types. See Type conversion.

References

  1. Wikipedia, Downcasting, revision 1383382579, the introduction, Uses and Considerations
  2. Wikipedia, Code smell, revision 1379558939, Common code smells, Downcasting
  3. The Go Programming Language Specification, Type assertions
  4. JEP 394, Pattern Matching for instanceof, Summary, History and Motivation
  5. Martin Fowler, Catalog of Refactorings, the cards Replace Conditional with Polymorphism and Move Function

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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/Z3B3PQ/text.yaml