5 ms·
So every shape now has to reference every other shape? If I want to add a new shape I not only have to define the shape function, def Triangle(a,b,c): re
by mdoms 6y ago
So every shape now has to reference every other shape? If I want to add a new shape I not only have to define the shape function,
def Triangle(a,b,c):
return (lambda visitCircle, visitRectangle, visitTriangle : visitTriangle(a, b, c))
and update the area function, I also need to update every existing type like
def Rectangle(x, y, w, h):
return (lambda visitCircle, visitRectangle, visitTriangle : visitRectangle(x, y, w, h))
Am I understanding this correctly? How is this a win? What if I have a hundred different shapes, now every shape definition is just a list of a hundred parameters and hopefully I called the correct one in my copy&paste-fest.
- Twisol 6y agoThat's why we usually group all of these handlers into a single Visitor interface. Then you only add one class and one extra method to the Visitor, and all the other variants stay the same. You're brushing up against the so-called "expression problem", though, where you can choose between adding types easily or adding algorithms easily, but not usually both.
- h_anna_h 6y agoHere you go import math def Circle(x, y, r): return (lambda d : d['visitCircle'](x, y, r)) def Rectangle(x, y, w, h): return (lambda d : d['visitRectangle'](x, y, w, h)) def area(shape): return shape({ 'visitCircle': lambda x, y, r : math.pi * r * r, 'visitRectangle': lambda x, y, w, h : w * h }) exampleCircle = Circle(2, 1.4, 4.5) exampleRectangle = Rectangle(1.3, 3.1, 10.3, 7.7) print(area(exampleCircle)) print(area(exampleRectangle)) # 63.61725123519331 # 79.31