OverviewWhen special tags in fields are used to distinguish between types of objects, errors are possible in which a tag mislabels the associated data—a bug pattern known as the Impostor Type. We'll examine the symptoms and causes, define ways to prevent this error, and discuss some tempting hybrid implementations that don't use impostor types but hold danger nonetheless. All but the most trivial of programs manipulate some types of data. Static type systems provide a way to ensure that a program doesn't manipulate data of a given type inappropriately. One of the advantages of the Java language is that it is strongly typed, so that the possibility of a type error is eliminated before the program is ever run. As developers, we can use this type system to produce more robust and bug-free code. Often, though, the type system is not used to its full potential. Many programs make less use of the static type system than they could, instead relying on special fields to contain tags that distinguish the types of data. By relying on these special fields, such programs give up the very protection that the type system was designed to provide. When one of these tags mislabels its data, it generates what I call an Impostor Type bug pattern. In a nutshell, here is our latest bug pattern:
|