Pyramid of doom (programming)

In computer programming, a common challenge facing systems programmers is that before an operation can be performed, a number of conditions must first be checked to confirm that the operation can be successfully performed. For example, before data can be written to a file, it must be confirmed that 1) the program has the file open for writing; 2) the program has the necessary permissions to write the data; 3) the program has provided the data to be written; 4) the data to be written is of a valid size. A failure at any of these steps means that the write operation cannot be completed and an error should be returned to the calling program.

There are several ways that these multiple required tests can be written in the source code. One way is to check each condition in turn and if a condition fails, return from the subroutine at that point, indicating an error condition exists. This style of coding has the disadvantage that the subroutine returns from multiple (possibly many) points and some coding standards discourage having multiple return points.

Another way to is to check each condition and if the condition succeeds, enter a deeper block of code that checks the next condition and so on. The deepest enclosing block of code is only reached if all of the precondition tests are successful. This style of coding has the disadvantage that the indentation level increases with every test performed. If many tests are required, the enclosed blocks of code can march off the page to the right margin. This typographical effect is referred to as the pyramid of doom.

For example, the pyramid of doom is commonly seen when checking for null pointers or handling callbacks.[1] Two examples of the term are related to a particular programming style in early versions of JavaScript,[2] and the nesting of if statements that occurs in object-oriented programming languages when one of the objects may be a null pointer.[3][4]

  1. ^ Dave Herman (14 December 2011). "Why coroutines won't work on the web". The Little Calculist. Archived from the original on 2016-03-06.
  2. ^ "The Pyramid of Doom: A javaScript Style Trap". 27 November 2012. Archived from the original on 2015-12-09.
  3. ^ Eberhardt, Colin (8 December 2014). "Tearing Down Swift's Optional Pyramid Of Doom". Archived from the original on 2016-07-31.
  4. ^ "New Language Features in Visual Basic 14". 9 December 2014. Archived from the original on 2014-12-25.