Veezoo

Module 4 · Lecture 4.3

Subclasses

Attributes that only some instances have can silently filter answers. Subclasses are the construct that fixes it.

An online bookstore sells physical books and digital downloads. Same Order class, but a shipment only exists for physical orders, and a download URL only for digital ones. This lecture shows the subtle bug that mixture causes and the construct that fixes it.

Key points

  • When they fit: subclasses are for attributes that are relevant to only some instances of a class.
  • The bug they fix: "show all orders" returned only physical orders, because the answer displayed shipping mode and only physical orders have one.
  • Every subclass needs a name and a definition that says which instances belong to it, for example order type equals physical.
  • Not every instance has to belong to a subclass, so a subclass can cover just part of the parent class.
  • Specific attributes move down: the shipment relationship goes to Physical Orders, and download URL, download count, and expiration date go to Downloads.
  • Shared attributes stay up: quantity, unit price, and book stay on the parent class Order, and both subclasses inherit them.
  • Users can ask about a subclass directly ("how many downloads?") and compare subclasses against each other in one question.

Check your understanding

Orders are physical or digital. Shipment exists only for physical orders, the download URL only for digital ones. How should this be modelled?

What does every subclass need?

Quantity and unit price are defined on Order, not on the subclasses. What happens when a user asks for the average unit price of downloads?