Remembering to Return and Keeping It Readable
00:00 Let’s take a look at a couple more best practices, starting with remembering to return the return value. A common error in writing functions is to actually forget to return a value for when the function finishes.
00:15 This can be solved by making considerations for a return value when you are first defining your function. This makes sense because when you’re starting your function definition, you’re already thinking about what parameters it should take and what it should return.
00:31 So make a little template for yourself, like this one, to write code which uses a return result before you start writing the body of your function. Start with the function header, where of course you would write a suitable function name and indicate parameter variables it will actually use. Then write statements to account for the return value, leaving blank space for the body of the function.
Once you have this written, you can then fill in the body with what the function will actually do to compute a meaningful result. Be prepared to change the variable name
result to something meaningful as well.
Another best practice is to not write complicated expressions for the return value. Using a complex expression in a
return statement makes debugging more difficult. It’s hard to keep track of what’s being computed.
Make use of temporary variables to store intermediate values as the computation progresses. Here’s that same function broken down into smaller parts. First, we store the size of the data in the variable
n. Then we compute the mean, as before.
Become a Member to join the conversation.