Part 3 of 7 · 2 min read
The tagged class problem
A tag and a switch are polymorphism done by hand.
EJ Item 23 describes a class that stands for several kinds of object and uses a tag field to record which kind an instance is. Its example is a Figure that holds a tag (RECTANGLE or CIRCLE), fields for both shapes, and an area method with a switch on the tag.
EJ lists the faults. The class is cluttered with the enum, the tag and the switch. Several implementations are jumbled in one class. Each instance carries fields it does not use. Fields cannot be final without extra constructor work. The compiler does not check that the right fields are set for the tag. A new flavour needs a change to the source of the class, and a new case in every switch, or the program fails at run time. And the type of an instance does not show its flavour. EJ's summary: tagged classes are verbose, error-prone and inefficient, and a tagged class is a weak imitation of a class hierarchy.
The cure is subtyping. Make a root type with an abstract method for each tag-dependent operation, and one subclass per flavour, each holding only its own fields. This is what the Shape example above does. EJ says the hierarchy fixes every fault of the tagged class: it is simpler, the fields can be final, the compiler checks the constructors, and a new flavour is a new class with no edits to old ones.
A made-up count. A tagged Figure has 5 methods that each switch on the tag, and 2 flavours. Adding a third flavour means 5 new case branches, one in each method. In the hierarchy, adding a third flavour means one new class with 5 methods, and nothing else changes.
Tagged class
A tagged class is one class that stands for several kinds of object, using a tag field and switch or if statements to tell them apart.
Example: a Notification class with a type field ("EMAIL", "SMS") and an if on it inside send().
Check yourself: 1. Which two things does a tagged class need that a hierarchy does not? 2. What happens when a flavour is added to a tagged class? 3. Where do the fields of a circle live in the hierarchy?