Nested function calls
About this video
The video traces what happens when a function calls another function: a new stack frame is pushed on top while the outer call waits, and it's popped when the inner call returns. Using a stealth game's is_detected function, it shows why one giant function is hard to read, test and reuse, and refactors it into small single-task functions like a movement adjustment, an environment adjustment, get_footstep_volume and is_detected, which are then reused for a new voice feature.
You'll be able to
- trace how stack frames are pushed and popped during nested function calls.
- explain why a function that does many tasks is harder to read, test and reuse.
- break a large function into smaller functions and combine them with a wrapper function.
Key words
- nested function call
- A function call made from inside another function's body.
- stack frame
- The memory for one function call; new ones go on top and are popped off when the call returns.
- wrapper function
- A function that combines other function calls to perform a bigger task.
- self-documenting
- Code whose names clearly describe what it does, so extra comments aren't needed.
- reusability
- How easily code can be used again for new features without rewriting it.
Transcript
- [Instructor] Can I call a function from inside another function? Let's trace what happens, and explore why we might wanna organize our code this way. When we call a function from the top level of a program, we create a new stack frame and store all our local variables there.
When we later return from that function call, we pop off our stack frame and pass our return value back to the caller. If a function calls another function within its function body, we just do the same thing, but we're going one level deeper. When execution reaches that inner function call, the computer pauses what it's doing, loads that function's instructions, and then goes off to execute them.
This creates a new stack frame on top of our existing stack frame. Our existing stack frame stays where it is because we're not done executing that function yet. It hasn't returned. The computer needs to preserve that state so we can go back and finish executing the function later.
Any parameters or variables that are a part of this function gets stored on that new top stack frame. When we reach this function's return statement, we exit out, pop off that top stack frame, and return back to where that function was called, which in this case, was inside another function.
Notice that the top stack frame now, which is the one that's accessible, is the one that has the state for this function call. And then, the computer picks up execution of this function where it left off. We can, in theory, go as many levels deep as we want. Every time the computer calls a function, it creates a new stack frame on the very top.
And every time the computer returns from a function call, it pops off the top stack frame. That way, each stack frame is keeping track of the variables local to a specific function call. If we need to pass information through that pipeline of function calls, we can just use the function parameters.
We can pass it as an argument to the first function call, which can then pass it as an argument to the inner function call. Okay, but why might we nest a function call in the first place? Let's set the scene. Imagine a video game where players try to sneak into a building without being detected by the guards.
Your chance of detection depends on the volume of your footsteps and the volume of your footsteps depends on how fast you're moving and the environment you're in. You can be super quiet crouching in the grass, or you can be super loud running on metal. Now here's one way to solve that problem.
I have one giant function that takes in as parameters the player's movement type and environment. And then, it turns out a Boolean that tells us whether the player has been detected. I can now call this function across my game anytime a player is sneaking around.
So what's the problem then? Well, it's true that I technically have a function, but this function body is huge. Within one function, I'm performing several different tasks. First, I calculate the player's footstep volume based on their movement. Then, I adjust that volume based on the environment they're in.
And then, I compare that volume against a random detection threshold. When a function does a lot of different things, it makes the program harder to read because it's not always obvious from the function name all of the things that that giant function does. Two, it makes it harder to test.
If I pass in as arguments walk and metal and the function returns true, well, did it work? I don't know what that final value of volume was that it compared against the threshold. So it's hard to say whether that return value true makes sense, or there's some bug hiding in my function body.
And three, it makes the code harder to reuse. If every function performs only one task, then I can mix and match the functionality as I need. So how do we fix this? We just break it down into several smaller functions. So first, let's separate out this movement task.
We wanna take in a base volume and movement type and return out the adjusted volume. So we'll copy this conditional into our function body and return the volume. Then, inside this wrapper is_detected function, we can delete this conditional and replace it with a function call.
Notice that this smaller function is very easy to test now. Because my function is doing one specific task, it's easy for me to gut check that my return values make sense. If I call it with the argument crouch, I should get a smaller volume. And if I call it with the argument run, I should get a bigger volume.
Then, I can just do that same thing with the environment conditional. I separate it out into a smaller function that takes in a volume and an environment type, and then returns out the adjusted volume. Then, I can come back here and nest that function call. Notice that these function names describe the tasks that they perform.
So we don't really need these comments anymore. Our function names are self-documenting. Now for the detection check: I could nest a third function call here, but in this case, I think it might actually be better to separate out this functionality entirely. There's really no reason why this volume calculation needs to be tied to this threshold check.
So I can instead have a wrapper get_footstep_volume function that takes in the movement and environment and returns out the volume. That now lets me have a nice reusable, independent is_detected function that takes in a volume and returns out a Boolean. Okay, we've seen how this makes our program easier to test and easier to read.
But how about this reusability benefit? If I wanna now add a feature where say the player's voice can also give them away, I have these functions in place to make that really easy. A voice would also be modified by the environment, so I can reuse my environment function without having to think twice about it.
And then, since I decoupled that detection threshold check, I can calculate my voice volume and then conveniently just plug it in to the is_detected function. To build that whole feature, I had to do very little work because I solved most of those problems already.
So the next time you're writing a program, think about breaking it down into small functions that each perform a specific task. Then, when you need to combine functionality to perform a bigger task, you can always nest those function calls in a wrapper function.
Video © Khan Academy, used under CC BY-NC-SA. Watch on Khan Academy. Puzzicle is not affiliated with Khan Academy.