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.

Hello world!

Hello world! This is my new blog. It will be about anything related to software development and I hope to keep it active and share whatever I know. Currently I’m really interested in clean coding and refactoring so I’ll probably write some posts about these subjects first.

I decided to write the blog in English hoping it can reach more people and maybe English is more easily translatable to any other language, I don’t know, I’ll try to translate it to Turkish and Italian and see what happens.

Sometime in the future I’ll also add the obligatory “about me”, “past experiences” pages.