Another Great Example of Recursion

Remember how I told you that Joe Marshall was really good at coming up with elegant examples of recursion? He’s back with another. This time it’s not one he thought up but it’s too good not to share.

Here’s the problem: You have a server that you can query for time-stamped records by specifying a begin and end date. The problem is that the server will return (only) an error if the number of records you request is too large. There’s no way to tell, a priori, how many records exist between any two dates. How do you write the client?

Marshall offers a beautiful recursive solution that solves the problem in 10 lines of—I guess—Java (I’m not a Java maven so I’m not sure). It’s very much worthwhile reading and understanding the example so you can add the trick to your toolkit.

Marshall’s larger point is that often people are afraid of and resist recursive algorithms but they shouldn’t be. It’s not always the right solution but it is for many problems and usually results in a simple and easy-to-understand solution. As Marshall says, one can imagine solving the above problem without recursion but that solution would be more complicated and probably harder to maintain.

I learned to use and appreciate recursion from reading Paul Graham and it’s amazing how often I’ve been able to amaze my colleagues with a nice recursive solution to some problem. If you’re not comfortable with recursion, you should try to fix that.

This entry was posted in General and tagged . Bookmark the permalink.