# Understanding Recursion in Apex

It’s likely that a significant number of people in the Salesforce ecosystem first encounter the idea of “recursion” when they are studying for the Platform Developer 1 exam. This was certainly the case for me, and if you don’t have a computer science background, it’s unlikely that you’ve encountered the concept before.

In my experience, this led to a very limited understanding of recursion. In fact, I only understood it as it applied to unwanted trigger re-entry or an endless loop – I was under the impression that recursion = bad. But in reality, it is a powerful and fundamental concept in software development. Even those of us working with languages that are not particularly friendly to recursion (like Apex) need to understand it.

## What is Recursion and How Do We Use It?

A recursive method is simply a method that calls itself. Any time a method is called, it goes on the top of something known as the “call stack”. Methods are executed from the top of the call stack to the bottom.

In the case of Apex we have a limit to our stack depth of 1000 – if you have a recursive method, it can never call itself more than 1000 times. This is useful in preventing an endless loop and ensuring the fair use of resources when dealing with the multi-tenant architecture of the Salesforce cloud.

This great article from Free Code Camp provides useful details about the call stack and recursion. And here’s a shameless plug for one of my YouTube videos: Salesforce Getting Started With Apex: Understanding the Call Stack.

Any problem that can be solved as a successively smaller version of itself is a use case for recursion. Let’s look at a simple example of a method in Apex that calculates a factorial.

This is probably the classic introduction to recursive code. If you are rusty on your high school math, a factorial is the product of an integer and all the integers below it. The factorial of 4 or 4! = 4 * 3 * 2 *1 or 24. The code below is an implementation of a recursive factorial calculator in Apex.

We can see our base case on line nine.

If the value referenced by the parameter numberToCheck is equal to 0, we exit the method call and return a value of 1. Without it we create infinite recursion.

If we pass in the number 3, the method would execute as follows: 3 is greater than 0, so the method calls itself with a return value of 3 multiplied by the return value of our method, but now the value of our argument is reduced to 2.

The method calls keep getting placed on the call stack until the value of num = 0. When that happens, we exit out of our recursive loop and return the value of 1. Now all the previous method calls that we were waiting on the call stack, get popped off and executed in reverse order. We multiply 1 by 2, and then 2 by 3 for the result of 6.

If we take a look at our debug log, we can see the recursive method in action (and that the correct result was returned).

However, if we try with a larger number, we can see that we will hit the Apex stack depth limit.

## What’s the Alternative to Recursion?

I wanted to leave you with an example of solving this same problem iteratively. Any problem that can be solved with recursion can also be solved with iteration:

## Summary

Recursion is just one more tool for your toolbox. Although it has fairly limited uses in Apex, it is a concept that every developer should understand. The advantage of recursive methods is that they can result in more concise and readable code. But it’s important to note that they are less performant than the iterative solution.

If we look at the profiling results using Illuminated Cloud and IntelliJ, we can see that our iterative method calculated the result of !500 in 30 milliseconds, while our recursive method took 148 milliseconds.

## One thought on “Understanding Recursion in Apex”

1. Great article!