Object-Oriented Programming and Recursion
Object-oriented programming is based on objects. Objects are software entities that contain both data attributes and methods. Objects are created from abstract data types that encapsulate data and functions together. Object-oriented programming is useful because data attributes can be hidden, and access to the data attributes is restricted to the object's methods. Thus they are protected from accidental corruption. Also outside code only interacts with the object's methods. Another benefit of object-oriented programming is object reusability: objects can be used by other programs that need its services.
A recursive function is a function that calls itself. Recursion is a powerful tool for solving repetitive problems. However, recursive calls are less efficient than loops. Each time a recursive function is called, the system must perform several actions (e.g. allocating the memory for parameters and local variables, storing the address of the program location) that are not necessary with a loop. On the other hand, some problems are more easily solved with recursion: if recursion does not slow system performance too much, recursion can be a good design choice.
Reference: Tony Gaddis, Starting Out With Python, 2nd Ed.
Good insights. Some compilers and interpreters automatically transform recursion to loops, where possible, so there is no penalty for using this technique if it helps the programmer express a solution. Python, lamentably, didn't make this choice, although several "pythonistas" have written code that makes this conversion.
ReplyDelete