Pyramid of Doom says that the code nesting level is too deep, too much code indentation, causing the code to grow more horizontally than vertically. Very much affects the readability of the code, because we can not see the nested relationship, it is easy to mistake the scope of the variable, curly braces or less problems.
Code 1:if level too deep
BOOL Conditiona = Executestepa (); if (Conditiona) { bool conditionb = EXECUTESTEPB (); if (CONDITIONB) { bool Conditionc = EXECUTESTEPC (); if (conditionc) { bool Conditiond = EXECUTESTEPD (); if (Conditiond) {...}}}}
Code Listing 2: Complex Ajax
$.ajax ({ url:url1, success:function (data) { $.ajax ({ url:url2, data:data, success: function (data) { $.ajax ({ //...});});} );
Code Listing 3: Too many jquery callbacks
Code uses JQuery to illustrate the Pyramid of Doom (function ($) { $ (function () { $ ("button"). Click (Function (E { $.get ("/test.json", function (data, textstatus, JQXHR) { $ (". List"). each (the function () { $ (this). Click (function (e) { setTimeout () (function () { alert ("Hello world!"); };}) ;}); }); });}) (JQuery);
obviously the above 3 pieces of code look very ugly, by some means can remove the bad taste of this code. "The Pyramid of doom:a JavaScript Style Trap" This article optimizes code 3 to look like this:
Code uses JQuery (function ($) { function init () { //Add OnClick to buttons $ ("button"). Click (getData);
} function GetData () { $.get ("/test.json", onsuccess); } function onsuccess (data, Textstatus, JQXHR) { $ (". List"). each (Addlistonclick); } function Addlistonclick (e) { $ (this). Click (helloworldtimeout); } function Helloworldtimeout () { setTimeout (Helloworldalert, +); } function Helloworldalert () { alert ("Hello world!"); } $ (init);}) (JQuery);
you can see the optimized code: There are not so many indentation and hierarchy nesting, although the code grows vertically, but readability is improved.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
A common code in JavaScript programming bad taste: Pyramid of Doom (Pyramid Doom)