When Polymorphism Fails — cover art: a small storybook elf in a green hood sits cross-legged on a worn oak table, surrounded by a half-circle of small carved wooden monster-figurines (orc, troll, dragon, elf-maiden, goblin), pointing accusingly at one with a scowl. 👍

2004 · Drunken Blog Rants · Rant

“Polymorphism only makes sense when the polymorphic behavior is really a behavior of the target. When it's the behavior of the observer, you need runtime typing.”
— From When Polymorphism Fails, August 2004
Read the essay

© 2004 Steve Yegge. Originally published at Drunken Blog Rants.

AI Notes

Steve picks a fight with the orthodoxy. The textbook line — if you reach for instanceof you are doing OO wrong — is true most of the time, and he says so up front. His piece is about the exception, demonstrated by the OpinionatedElf: a user-contributed extensible-system creature whose entire purpose is to announce which other monsters it hates. The polymorphic move is obviously absurd (add a doesMrOpinionatedElfHateYou() method to all 150 monsters), and even Ruby's open-classes trick — which can patch the method onto each monster from inside the elf's own file — fails the moment a new monster appears that the elf has never seen. The thesis: polymorphism only makes sense when the polymorphic behavior is really a behavior of the target; when it's the behavior of the observer, you need runtime typing. The security-guard analogy seals it — you don't ask each person entering the building to implement their own doYouHaveAccess() method; the guard does the check.

Steve also flags in a footnote (and follows through on for years afterward) that type is better represented by properties than by classes. The piece pairs with Execution in the Kingdom of Nouns as the design-essay foundation of Steve's long-running argument with class-based OO orthodoxy — Polymorphism Fails is the technical case, Kingdom of Nouns the same case as comedy. The "Opinionated Elf" makes appearances in the archive for years afterward as Steve's recurring stand-in for the bad-OO-fit case.

Related listings