CS 541 Lecture -*- Outline -*- * the binary method problem background: this is motivational for multi-methods ** what it is really not just binary, but anything more than 1 arg is a problem. ------------------------------------------ BINARY METHODS def: a *binary method* is a method e.g., +, =, <, subset: ------------------------------------------ ... whose argument should have the same class as the receiver (or a superclass of the receiver's class). ** the problems ------------------------------------------ EXAMPLE class: Point superclass: Object instance variables: xValue yValue "instance methods" x: aNumber xValue := aNumber y: aNumber yValue := aNumber x ^xValue y ^yValue equal: p ^(xValue = p x) and: [yValue = p y] ------------------------------------------ Q: Anything problematic about the equal method? can't access instance variables of p no big deal for this example isn't symmetric ------------------------------------------ A USE OF THE POINT CLASS class: Procedure superclass: Object instance variables: "instance methods" breakit: p. | nuPt | nuPt := Point new x: 3.2. nuPt y: 4.5. ^p equal: nuPt ------------------------------------------ the only point about the above is that it should work fine, when p is a Point object. ------------------------------------------ A SUBCLASS class: ColorPoint superclass: Point instance variables: cValue "instance methods" c: aString cValue := aString c ^cValue equal: p ^(cValue = p c) and: [super equal: p] ------------------------------------------ Q: does that seem reasonable? but this causes the problems *** breaks subtyping ------------------------------------------ COLORPOINT IS NOT A SUBTYPE OF POINT | nuCPt | nuCPt := ColorPoint new. ((nuCpt x: 8.7) y: 9.1) c: 'red'. (Procedure new) breakit: nuCPt ------------------------------------------ Q: what happens? this produces "message not understood" explain why conclusion: ColorPoint is not a subtype of Point this is a type problem, not just a behavioral problem Q: How could this be patched? double dispatching, ad hoc tests, use of "pair" classes and the problems of each *** need for privileged access If didn't have any binary methods, can treat ColorPoint as subtype of Point. But then when add equal, old code breaks. ------------------------------------------ NEED FOR PRIVILEGED ACCESS class: IntSet superclass: Object instance variables: elts "instance methods" new elts := OrderedCollection new add: anInt elts addFirst: anInt includes: anInt elts includes: anInt superSetOf: anIntSet "???" ------------------------------------------ The problem is there aren't enough methods to do this, can't access the argument anIntSet This wasn't a problem with point example It's solved by extending the methods, but might have other reasons for keeping the interface small, and might be inefficient (might want to use a balanced binary tree internally) ** summary Q: Is there just one "binary method" problem?