I've never had much need to write recursive functions in my programming career; I've written one perhaps two or three times, all told. Hence, I haven't paid them much attention, and still don't really know much about them.
It turns out that interviewers are quite keen on asking questions about recursion; perhaps this is because there's a heavier focus on them in CS classes than there is a use for them in reality?
The first time I encountered a question about recursive functions during an interview, it kind of threw me. Why ask a question about something so rarely used? My response was that, yes, I've written them, but rarely, and I try to avoid it when possible because I find them confusing - I have a fear of writing something that will result in an infinite recursion in some subtle case. It was during this interview that I learned that recursive functions can lead to stack overflows. Thereby proving that interviews can be useful, at least as learning experiences.
Well, today I caused my very own stack overflow by creating a recursive function, albeit unknowingly! I had created a Java class which extended another class, which mostly had getters and setters. The intention was to eventually implement these methods in the child class, but meantime I had the child class override the parent's methods, and just had them return the results of the super class methods. For example, I had the
getFoo()
method call the superclass method, super.getFoo()
, and so on. Only, in one case, I inadvertantly left out super
and had the getBar
method return getBar
- so the method called itself recursively. When I ran the code, I immediately saw this huge stack trace in the output. At the top it said "Exception in thread ... java.lang.StackOverflowError
. This was followed by 1024 repeated lines giving the method which had generated the error.I don't recall ever experiencing this in my entire career, and I could immediately see what had gone wrong, so I found it very entertaining (perhaps I am too easily amused).
No comments:
Post a Comment