Mid-Function Returns are STILL Controversial

… and nobody is yielding ground

Chris Fox
Chris Fox
Apr 26 · 5 min read

Introduction

Long introductions are bad for reader retention.

Canonical Examples

A typical function or method performs a series of parameter checks or setup operations such as allocating a buffer, opening a file or network connection, each of which must be undone before exiting. These pseudocode examples are based on a C-like language, while much of the code shown here would be handled now by destructors and garbage collection. But it was looking at code like this that led me to abandoning early returns.

  1. allocate a buffer
  2. seek to a file offset
  3. read from the file into the buffer

Returns anywhere

Single Return

return code;
}

Discussion

Early Returns

In the early return layout most of the code visible in one screen is error-handling. To follow the path of correct execution the reader must skip over increasingly larger blocks of error-path code and locating the line that does the method’s nominal purpose takes some work. Each setup condition needs cleanup calls in each error handling block.

Single Return

In the one-return layout the order is reversed and a successful setup operation enters a new scope, with the accompanying cleanup operation invoked only once at the end of that scope.

But Wait, There’s More

This is more than just a function architecture, it is a different way of thinking. Please consider this carefully, this is important. When I realized I was doing things backwards with mid-function returns my bug count dropped very sharply immediately. I found that it changed not just how I laid out my work but how I thought about it

“Just Get Out”

I’d seen comments like this hundreds of times

if (malloc(cb) == NULL)
{
// could not allocate so JUST GET OUT
return;
}

Follow the Path of Goodness, Not the Path of Failure

Always check for errors but write in a “positive-going” manner in which successful operation is the presumption and errors are the exceptions. This is easier to read because the upper part is always the path of successful execution instead of separating the actual steps with error-checking.

CodeX

Everything connected with Tech & Code

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store