One of the first techniques developers learn is the if/else statement. For obvious reasons if/else statements are a primary way to create logic trees. This is where we handle calculations differently depending on the input variables. However, complex and nested if/else statements become a cognitive burden to reason about. Therefore, it can be hard for the next developer to understand quickly. Guard Clauses Guard Clauses are a way to leverage the ability to return early from a function (or break/continue through a loop) to make nested conditionals more one-dimensional. I'm primarily a . The way errors are handled in go naturally encourage the developer to make use of guard clauses. When I started writing more javascript, I was disappointed to see how many nested conditionals existed in the code I was working on. go developer Go is the shit Let's take a look at the following fake javascripty example: { let amount; (! .hasInsurance()){ amount = ; } { ( .isTotaled()){ amount = ; } { ( .isDented()){ amount = ; ( .isBigDent()){ amount = ; } } } } amount; } function getInsuranceAmount (status) if status 1 else if status 10000 else if status 160 if status 270 return Could be written with guard clauses instead: { (! .hasInsurance()){ ; } ( .isTotaled()){ ; } ( .isDented() && .isBigDent()){ ; } ( .isDented()){ ; } ; } function getInsuranceAmount (status) if status return 1 if status return 10000 if status status return 270 if status return 160 return 0 The example above still probably isn't the best way to approach this function. It is much easier to read and understand, however. When writing code, it is important to try to reduce cognitive load on the reader by reducing the amount of things they need to think about at any given time. In the first example, if the developer is tying to figure out when is returned, they need to think about each branch in the logic tree and try to remember which cases matter and which cases don't. With a more one dimensional structure, its as simple as stepping through each case in order. 270 I hope this helps us to create more readable code! I think it's great to learn the patterns and best practices that exist in programming languages we aren't familiar with, because many times those techniques can be applied to programming in general. | | Download RSS Feed Github ( ) Disclaimer: The author is the Founder at qVault (Originally published ) here