How to write better code with Guard Clauses
technology·@themarkymark·
0.000 HBDHow to write better code with Guard Clauses
 In the spirit of the [10,000+ Hive Hackathon](https://peakd.com/stem/@themarkymark/stemgeek-s-first-hackathon) I am running, I am going to try to put out some tips and tricks over the next few days. I also have a long-running Python Tips Series you can find [here](https://peakd.com/hive-163521/@themarkymark/python-tips-easy-serialization-with-pickle). *Look at the footer for links to the previous entries*. # What is a Guard Clause A guard clause a programming idiom that you are likely already using but are not aware there is a name for it. It is also something you are not likely using effectively. A guard clause exits a loop or function when certain conditions are met early on. #### Example 1 ``` let inventory = 1 let cart = [] function addToCart(item){ if (inventory > 0) { cart.push(item) } } addToCart('Book') console.log(cart) ``` This simple code creates a variable to simulate an inventory and a shopping cart. There is an addToCart() function to add items to the cart. Before adding an item to the cart, it checks to see if the inventory is empty. This code works perfectly fine and is easy to read. The problem comes in when the business rules become more complex and you start expanding the if statement. #### Example 2 ``` let inventory = 1 let cart = [] let userIsLoggedIn = true function addToCart(item){ if (userIsLoggedIn) { if (inventory > 0) { cart.push(item) } } } addToCart('Book') console.log(cart) ``` While this is still relatively simple, you have likely coded far more complex examples many times. These types of nested if structures become very difficult to manage and change in the future. # Introducing the guard clause A guard clause will exit your loop or function immediately. This avoids additional indents to your core condition statements making them far easier to read and maintain. ``` let inventory = 1 let cart = [] let userIsLoggedIn = true function addToCart(item){ if (!userIsLoggedIn || !inventory) return cart.push(item) } addToCart('Book') console.log(cart) ``` By extracting the initial sanity checks into a dedicated if statement that exits immediately, your code is cleaner and far easier to maintain. These examples are oversimplified, and real-life examples are far more difficult to work with. Here's an example of an if cluster bomb from Reddit ``` const returnLinesRequiredData = (lineObj, id, key) => { if (id) { if (id < lineObj.stations.length) { if (key) { if (lineObj.stations[id].hasOwnProperty(key)) { return lineObj.stations[id][key]; } return errorMsg; } return lineObj.stations[id]; } return errorMsg; } return lineObj; }; ``` <sub>[Source](https://stackoverflow.com/questions/42347068/callback-hell-in-multiple-if-else-if-statements)</sub> Try to look over your existing code and see where you can implement guard clauses to improve the readability of your code. --- <center>Securely chat with me on [Keybase](https://keybase.io/officialmarky) <center>https://steemitimages.com/DQmcWxV1dpA1eAtw2ipwZiWZkydyVNU5LaLa2Ak1GUnbGmS/The-Marky-Mark.png </center> # <center> [Why you should vote me as witness](https://peakd.com/witness-category/@themarkymark/why-you-should-vote-for-themarkymark-as-witness) </center> #
👍 stemd, tonimontana.neo, toni.pal, dtrade, noobster, arctis, moeenali, mango-ag, potplucker, socialmediaseo, sam99, dalz4, dein-problem, techslut, blind-spot, dfacademy, c4cristi3, ctime, dappcoder, goodreader, staryao, aivote, gerber, nealmcspadden, huaren.news, steemcityrewards, deathwing, emrebeyler, daan, someguy123, shitsignals, roleerob, pataty69, cadawg, bestboom, freddio, gallerani, dlike, triptolemus, bobby.madagascar, creativeblue, merlin7, determine, permaculturedude, vxc, steem.leo, leo.voter, freddio.sport, asteroids, leo.syndication, one.life, maxuvd, privex, jphamer1, mys, julialee66, g4fun, gerbo, accelerator, scaredycatguide, whiterosecoffee, star.lord, xyz004, imisstheoldkanye, sidwrites, ew-and-patterns, taifkhan, erikah, dalz, simply2koool, tipsybosphorus, mirkon86, ronaldoavelino, rem-steem, enforcer48, cryptoandcoffee, tarazkp, maxer27, chintya, nokodemion, philnewton, monsterjamgold, dfacademy-pal, marlians.token, netaterra, kromtar, daath, moneytron, cpt-sparrow, beggars, slobberchops, rishi556, therealyme, vxn666, kevmcc, anthonyadavisii, steemflagrewards, bozz, goblinknackers, giftgiver, claudio83, lookplz, bilpcoinrecords, flagawhale, sfr-treasury, trump3t, steemychicken1, yoshiko, sn0n, cryptopie, chorock, thegoldencobra, savagebits, admiralbot, steemhistorian, sfr-mod-fund, nullandvoid, neutralizer, randohealer, magicmonk, blokz, chronocrypto, steddyman, blewitt, schlunior, anonsteve, broxi, bruneo, angelinafx, yeaho, d0zer, satren, raorac, yaraha, suonghuynh, smartvote, steemfriends, schlank, wallvater, thranax, mvanhauten, apoloo1, tubcat, fucanglong, drew0, bynarikode, lovenfreedom, onepercentbetter, a-bot, donbeano, debtfreein2, urtrailer, lacking, yggdrasil.laguna, enjar, otom, drorion, faustofraser, jlsplatts, steemusa, cst90, homeginkit, sugandhaseth, diabonua, nfaith, lil-splatts, kuku-splatts, szf, pal-isaria, splatts, greatnorthcrypto, arcticgypsy, worldbuilder, garrok, pleadthefifth, chemicalhecks, isaria, bmonakken, nuthman, howiemac, leilafrangie, fun2learn, iamstan, fcbarcelonafans, merlion, themightysquid, tigerrkg, hungrybear, babschnae, kggymlife, banvie, stemisaria, papetti, geekgirl, offoodandart, ciuoto, librarian, flibbertigibbet, nailyourhome, the4thmusketeer, german.news, schlees, kayoko, hungryhustle, properfraction, paragism, stevescoins, freebornsociety, deniskj, cooperfelix, ma1neevent, espoem, alinalazareva, anttn, mytechtrail, mahyulmaulana, morellys2004, elmauza, cryptonik, teamashen, kosimoos, adamada, bestofph, kendallron, pinas, tadstrange, cervisia, gerdtrudroepke, render-obsolete, the.circle, smartmeme, keepinitsteem, calimeatwagon, rcshad0w, markus.light, sonius94, iamtom, gerusan, i-c-e, hyborian-strain, tiffany4ever, reinhard-schmid, letsplaywhatelse, emitste, abdulwajid1978, vaansteam, necio, phusionphil, pdc, vikisecrets, retard-gamer-de, voxmortis, acromott, ilias.fragment, steemcenterwiki, leslierevales, earthworld, commonlaw, yulem, dylanhobalart, suntree, cryptogee, davinsh, nasel, spederson, hivewatchers, anyx, kushed, complexring, aizensou, b0y2k, stoner19, sock, josephcraig289, igl00, hagie, coinbar, steemcleaners, platinum-blue, steemizen, bigdaddy, kingsmind, pboc, papadimos, romedog, spg, sammosk, dream-o, tushy, logic, light-hearted, bilpcoinbpc, richman, razvanelulmarin, fabio, shawnamawna, caesarion, thebluepanda, thisisbenbrick, einsteinpotsdam, tejma, allesgruen, dannystravels, jerryblanceton, ssekulji, timbernana, sherlockcupid, dougkarr, dark.horse, toyman, i-gordan, buzzbeergeek, sunshinetraveler, biancajapan, horsepower, teneiced, sumayyahsaidso, teslaman, blondephysics, magictoni, amos811, da-dawn, tdogvoid, luminaryhmo, daree23, steemvpn, zelegations, tattoodjay, dream.trip, indayclara, jim888, culgin, mrshev, steem.ens, hope-on-fire, steem0, steem-oracle, cryptojiang, kristves, dreamingirwin, jkramer, broncnutz, sepracore, pibara, astrizak, asgarth, grider123, condeas, mr-mooch, ibc, linuxbot, stuntman.mike, teacherpearline, steemik, edkarnie, tomhall.leo, nainaztengra, inertia, zorg67, stem.curate, balticbadger, samuel.steem, paolo.senegal, quantumdeveloper, maruskina, nalacanecorso, alby2, riccc96, pecoshop, hjmarseille, boomalex, machete9595, oakshieldholding, katrin-lux, voter000, gitplait, ank8216, abachon, febrirmd, hackrelentless, stemgeeks, stemcuration, abh12345.stem, fersher, saboin,