Sub topic 2
Why check-then-cast is awkward
This chapter assumes you can write Java classes and subclasses, and that you already know instanceof and reference casts. You should also be comfortable with &&, || and !, and have written an equals method before. The chapter looks at the old idiom for using a value as a more specific type and at where it falls short. The next chapter introduces the language feature that replaces it.
The idiom in full
Sometimes you hold a reference of a general type, such as Object, and need to use it as a specific type. Java has always required two steps for this. First you test the runtime type with instanceof. Then you cast, usually into a new variable.
Object o = "hello";
if (o instanceof String) {
String s = (String) o;
System.out.println(s.length());
}This code is correct and safe. The cast cannot fail, because the if guarantees the object is a String. The problem is how much the code has to say to express one fact: "if o is a String, use it as a String."
One fact, stated three times
The idiom names the type String three times and the object o twice. It also introduces a second name, s, for the same object.
| Part | Code | What it does |
|---|---|---|
| Test | `o instanceof String` | Asks whether the runtime type is `String` or a subtype |
| Cast | `(String) o` | Tells the compiler to treat the value as `String` |
| Declaration | `String s =` | Gives the converted reference a name and a static type |
Each part is needed in the old language, but the three together are one idea. Because the idea is written out in pieces, nothing in the language connects them.
The compiler does not link the test and the cast
The compiler treats the if condition and the cast as unrelated. It never checks that the type you tested is the type you cast to. Here is a copy-and-paste mistake that compiles without complaint:
public class CastMismatch {
public static void main(String[] args) {
Object o = 42;
if (o instanceof Integer) {
String s = (String) o; // compiles, but o is an Integer
System.out.println(s.length());
}
}
}The program compiles because o is declared as Object, and a cast from Object to String is legal in general. At run time the if branch is entered, since o holds an Integer. The cast then throws ClassCastException.
This kind of mistake is easy to make when you edit one branch of a chain and forget the other line. The failure happens only when that branch runs. A rarely used branch can hide the bug for a long time.
Chains multiply the noise
The repetition grows with every type you handle. A method that formats several kinds of values looks like this:
public class Describe {
static String describe(Object o) {
if (o instanceof String) {
String s = (String) o;
return "String of length " + s.length();
} else if (o instanceof Integer) {
Integer i = (Integer) o;
return "Integer " + (i + 1);
} else if (o instanceof int[]) {
int[] a = (int[]) o;
return "int array of length " + a.length;
} else {
return "something else";
}
}
public static void main(String[] args) {
System.out.println(describe("hello"));
System.out.println(describe(41));
System.out.println(describe(new int[3]));
System.out.println(describe(2.5));
}
}Each branch has a condition line and a cast line, and the real work comes after both. The type appears three times per branch. If you rename a type or change which type a branch handles, you must edit all three places and keep them consistent.
A second name for the same object
The idiom also forces you to name the same object twice. After String s = (String) o;, both o and s refer to the same object. You must pick a name for s and keep track of which one to use.
Choosing the wrong one is a quiet error. Inside the block, o.length() would not compile, so the compiler catches that case. But when both names have a type that supports the operation you are calling, the compiler accepts either one. For example, o.toString() works on both. A later edit can then use the wrong variable without any error.
The variable can drift from the test
The declaration is also an ordinary local variable. Nothing stops you from placing the cast somewhere other than directly under the test. The old equals idiom does exactly that:
public final class Point {
private final int x;
private final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Point)) {
return false;
}
Point p = (Point) o;
return x == p.x && y == p.y;
}
@Override
public int hashCode() {
return 31 * x + y;
}
public static void main(String[] args) {
System.out.println(new Point(1, 2).equals(new Point(1, 2))); // true
System.out.println(new Point(1, 2).equals("not a point")); // false
System.out.println(new Point(1, 2).equals(null)); // false
}
}Here the test is negated and returns early. The cast sits several lines later, in a different statement. This code is correct, and the reader has to see that the early return false is what makes the cast safe. The compiler does not see this relationship. It relies on the programmer to keep the test and cast in agreement. This is a common source of subtle bugs when the code is edited later.
The null case works because instanceof is false for null, so the method returns before the cast. Chapter 8 covers that in detail.
Casts also work on generic types, with a catch
The idiom gets harder with generic types. You cannot test for List<String> at run time, because the type argument is erased. You would write the following:
import java.util.Collection;
import java.util.List;
public class Sizes {
static int size(Collection<String> c) {
if (c instanceof List) { // raw type in the test
List<String> list = (List<String>) c; // cast to a parameterized type
return list.size();
}
return 0;
}
public static void main(String[] args) {
System.out.println(size(List.of("a", "b")));
}
}The test must use the raw type List. In this case the cast to List<String> is safe, because the compiler knows c is a Collection<String>, but you may still see an unchecked warning depending on your compiler settings. The type argument has to be written again, in the cast. The language gives you no single place to say "this is a List of the same element type."
What a better design needs
The drawbacks above point to what a replacement has to do. It should:
- Name the tested type once.
- Declare the variable as part of the test, so there is no second statement to keep in sync.
- Give the variable the tested type automatically, so a mismatch cannot happen.
- Make the variable usable only where the test is known to have succeeded.
A type pattern does all four, and you will write your first one in the next chapter. Point 4 is the subtle one. It leads to the idea of flow scoping, which gets its own chapters.
Summary of the drawbacks
- The type is written two or three times per branch, so the code is longer than the idea.
- The compiler does not connect the tested type to the cast type, so a mismatch compiles and fails at run time with
ClassCastException. - The same object has two names, which makes it easy to use the wrong one.
- The cast can drift away from the test, as in the early-return
equalsidiom, and the compiler cannot verify that they still agree. - Generic types need a raw type in the test and the full type in the cast.
Exercise
The method below compiles. Explain what happens when you call show(7) and show("seven"), and name the specific weakness of check-then-cast that it demonstrates.
static String show(Object o) {
if (o instanceof Integer) {
String s = (String) o;
return s.toUpperCase();
}
return "other";
}
Show answer
show("seven") returns "other", because the test is false and the cast is never reached. show(7) enters the branch and throws ClassCastException at the cast, because the test checks for Integer while the cast converts to String. The compiler accepts this because it does not link the type in the instanceof test to the type in the cast, and o is declared as Object. The weakness is that the test, the cast and the declaration are three independent pieces that must be kept consistent by hand.
Exercise
Rewrite this branch so the tested type is named in the condition only once as far as the old idiom allows, and list how many times the name Integer still appears: if (o instanceof Integer) { Integer n = (Integer) o; return n + 1; }
Show answer
The old idiom does not allow any reduction. Integer appears three times: in the instanceof test, in the declaration Integer n, and in the cast (Integer) o. That is the repetition that a type pattern removes in the next chapter.