OverviewWhen you employ inheritance polymorphism—a feature of object-oriented languages that allows you to override methods—in combination with static overloading—a feature that allows you to overload methods based on the static types of the arguments—and an untouched method breaks, you may have come upon a Broken Dispatch. We discuss argument mismatches and practical and conceptual ways to eliminate the problem. Remember this adage: "The whole is greater than the sum of its parts." When single events are combined as an interacting unit, that unit can demonstrate many more results than the sum of results from each event on its own. Programs follow this rule. With each new method added to a program, the set of possible flows of control through the program grows dramatically. In large programs, it can quickly grow out of control. And like a perverse magic trick, sometimes the direction you expect is not where you go—it is similar to what can happen when you overload or override methods. Before we continue, notice that I am distinguishing method overriding (where a subclass redefines an inherited method) from method overloading (where a class defines two or more methods using the same name but different argument types). Method dispatch in an object-oriented language such as Java, in which methods can be overloaded and overridden, can cause difficulties of code management even in moderately complex programs.
We will discuss the Broken Dispatch bug pattern, one of the more prominent patterns caused by these difficulties, outlining the symptoms that appear when argument mismatches cause the wrong method to be invoked, and offering a few solutions to combat the problem. Here's a summary of this bug pattern:
One of the most powerful features of an object-oriented language is inheritance polymorphism. This feature allows us to override methods depending on the run-time type of the receiver. Another powerful feature is static overloading, which allows us to overload methods depending on the static types of the arguments. However, these two language features can introduce problems when used together. It can be easy in a large program to overload a method in one class and in the process break code that previously worked in another class.
|