Avoid becomes

From CSSEMediaWiki
Jump to: navigation, search
Do not model the dynamic semantics of a class through the use of the inheritance relationship. An attempt to model dynamic semantics with a static semantic relationship will lead to a toggling of types at runtime. --Riel's Heuristic 5.14, Arthur Riel 1996

Because inheritance is traditionally viewed as an "IS A" relationship, it's tempting to use it to model changing aspects of code as subclasses, for instance, subclassing Frog into Tadpole and Adult.

As with Design by contract though, the "IS A" concept proves too vague and general. Certainly a Tadpole is indeed a frog, but we run into problems when the Tadpole changes to a Adult. While real-world objects can change their type, OO objects cannot. Thus to change a Tadpole into an Adult requires copying all required data from a Tadpole instance into a newly created Adult instance. This is terrible for both performance and code simplicity.

The accepted way to model dynamic classes is through the use of the State pattern. This allows us to store the unchanging attributes of a class in one object, while using a separate class to encapsulate that which varies.

Personal tools