Anti-pattern: Pyramid of Doom

Here is a good 7 minute read about one of the most common anti-patterns I encounter: the pyramid of doom. This is one of the first things I write about when creating a coding guideline in a company.

It increases the complexity of the code and thus it decreases maintainability and testability. All the details about why most projects have at least one pyramid of doom are in the article. Here is the link again: https://itnext.io/pyramid-of-doom-the-signs-and-symptoms-of-a-common-anti-pattern-c716838e1819

Below, you can find the example pyramid of doom written in the article and how I would fix it. I added some numbers to “//some code here” lines so that we can understand what moves where.

function login(){ 
    if(user == null){ 
        //some code here 1 
        if(userName != null){ 
            //some code here 2
            if(passwordMatch == true){ 
                //some code here 3
                if(returnedval != 'no_match'){    
                    //some code here 4
                    if(returnedval != 'incorrect_password'){ 
                        //some code here 5
                    } else{ 
                        //some code here 6
                    }         
                } else { 
                    //some code here 7
                }
            } else { 
                //some code here 8
            }
        } else { 
            //some code here 9
        }
    }
}

// How to write it better:
function login(){
    if(user != null)
        return
    //some code here 1
    if(userName == null){
        //some code here 9
        return
    }
    //some code here 2
    if(!passwordMatch){
        //some code here 8
        return
    }
    //some code here 3
    if(returnedVal == 'no_match'){
        //some code here 7
        return
    }
    //some code here 4
    if(returnedval == 'incorrect_password'){
        //some code here 6
        return
    }

    //some code here 5
}

As you can see, there is no more pyramid and there are no else clauses anymore. You just read the code in a straight line and you’re done! Happy refactoring the pyramids of doom everyone.

Leave a Reply

Your email address will not be published. Required fields are marked *