Error Handling with the Single Input Single Output Pattern

From RidgeRun Developer Connection
Revision as of 12:04, 28 August 2020 by Mgruner (talk | contribs)
Jump to: navigation, search

Introduction

The single-input single-output is a simple pattern for procedural C code that eases:

  • Graceful error handling
  • Avoid code duplication
  • Improve readability.

Despite this, it is quite controversial among de developer's community due to the use of the infamous goto operator. The idea in single-input single-output is simple:

Every function should have a single entry point and a single output point.

The single entry point is natural for most of us, and probably (hopefully) de 100% of the cases. It is breakable though. In some old non-standard C compilers you could jump (using a goto) to a line in another function. Other more day-to-day examples include the use of setjump or longjump.

The single output point is way more common but gladly less harmful. The simplest example being having multiple returns in a single function. This is very typical during error handling or short-circuiting based on certain conditions.

Examples of different amounts of entry and output points.

GoTo Disclaimers

First of all, this is my personal opinion. Having said that:

  • I do not encourage the arbitrary use of goto jumps.
  • The single-input single-output is one of the few cases in which I believe is acceptable, even beneficial.
  • Yes, you can achieve the same with nested if/else structures. No, it won't be as readable and clean.
  • No, you shouldn't be applying this to C++. Instead I recommend the use of smart pointers or any other RAII.

The Problem

Consider the following hypothetical example.