What is open recursion?

前端 未结 4 491
青春惊慌失措
青春惊慌失措 2021-02-01 16:34

What is open recursion? Is it specific to OOP?

(I came across this term in this tweet by Daniel Spiewak.)

4条回答
  •  隐瞒了意图╮
    2021-02-01 17:18

    The name "open recursion" is a bit misleading at first, because it has nothing to do with the recursion that normally is used (a function calling itself); and to that extent, there is no closed recursion. It basically means, that a thing is referring to itself. I can only guess, but I do think that the term "open" comes from open as in "open for extension". In that sense an object is open to extension, but still referring to itself.

    Perhaps a small example can shed some light on the concept.

    Imaging you write a Python class like this one:

    class SuperClass:
       def method1(self):
           self.method2()
       def method2(self):
           print(self.__class__.__name__)
    

    If you ran this by

    s = SuperClass()
    s.method1()
    

    It will print "SuperClass".

    Now we create a subclass from SuperClass and override method2:

    class SubClass(SuperClass):
    def method2(self):
        print(self.__class__.__name__)
    

    and run it:

    sub = SubClass()
    sub.method1()
    

    Now "SubClass" will be printed.

    Still, we only call method1() as before. Inside method1() the method2() is called, but both are bound to the same reference (self in Python, this in Java). During sub-classing SuperClass method2() is changed, which means that an object of SubClass refers to a different version of this method.

    That is open recursion.

    In most cases, you override methods and call the overridden methods directly. This scheme here is using an indirection over self-reference.

    P.S.: I don't think this has been invented but discovered and then explained.

提交回复
热议问题