Level Up Coding

Coding tutorials and news. The developer homepage gitconnected.com && skilled.dev && levelup.dev

Follow publication

Escape the Pyramid of Doom

One of the most important aspects of code is readability, since it’s directly related to maintainability. You can have a very performant code that does what it needs to do, but if it is not readable, I personally can’t consider it as good code.

It is better to spend 5 minutes more when you are writing your code to make it more readable than forcing everyone to spend 5–10 minutes more to understand it every time someone else needs to work on it.

One of the things that hurts readability and is not that hard to solve is the "Pyramid of Doom", so let’s talk a bit about it.

Definition

In computer programming, the pyramid of doom is a common problem that arises when a program uses many levels of nested indentation to control access to a function. It is commonly seen when checking for null pointers or handling callbacks.
(Source: Wikipedia)

Pyramid of Doom, or “Haduken Code”

IF statements

Consider the code below:

How can we avoid this?

  • Using guard statements
  • Comparing optionals to exact values (Tip #1 from my last article)
  • Extracting validations to variables with a contextual name
  • Code formatting / organization

Some possible refactors

Example 1
Example 2

Closures

Or, the so-called "callback hell".

Consider the code below:

How can we fix this?

  • Dispatch Groups
  • Semaphores

Some possible refactors

Dispatch Groups
Semaphores

Note: I suggest reading more about Semaphores and Dispatch Groups, since the examples shown here are just simple and use their basic functions.

Suggested learning sources:
- Grand Central Dispatch Tutorial for Swift 4: Part 2/2
- A deep dive into Grand Central Dispatch in Swift
- Advanced Swift: Callback Hell Network Calls — Async Await Style Fix
- When to Semaphore vs Dispatch Group! Careful Multithreaded Shared Resource

Conclusion

We can see that it is not that hard to escape the Pyramid of Doom pattern. With just simple improvements, your code can become more readable and the next person to see your code won't have to spend a lot of time to understand it.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Written by Eduardo Sanches Bocato

iOS Engineer, AI enthusiast, Crossfit/Gymnastics. Currently working as iOS Lead @adidas

No responses yet

Write a response