DEV Community

joacoabrego
joacoabrego

Posted on

Guard clauses & Magic numbers

These two simple, language-agnostic concepts helped me significantly improve the readability of my code. I'll give you a quick definition for each and a few examples to illustrate why they're pretty cool. Let's go.

Guard Clauses

Guard clauses are basically checks that immediately exit a function if its conditions are met. There's a few reasons to use them, but I mainly like them for the improvement to code readability.

You can think of them as little bouncers or guardians for the rest of your code. Let's look at an example:

Starting with this function:

public void party(Person dancer, Song song) {

  if(dancer.isCool) {
    if(dancer.likes(song) {
       dancer.dance();
    } else {
      throw new DancerDislikesSongException();
    }
  } else {
    throw new DancerIsntCoolException();
  }
}
Enter fullscreen mode Exit fullscreen mode

We can use guard clauses to make the function much easier to read:

public void party(Person dancer, Song song) {

  //Cool people only!
  if(!dancer.isCool) {
    throw new DancerIsntCoolException();
  }

  //I'm not moving if I ain't groovin'
  if(!dancer.likes(song)) {
    throw new DancerDislikesSongException();
  }

  dancer.dance();
}
Enter fullscreen mode Exit fullscreen mode

See how the conditional statements are "protecting" the rest of the code? Those are our guard clauses! Easy, right? Let's move on to our next concept.

Magic numbers and strings

We call a number or string "magic" because we are unsure of their meaning in a certain context. They are there, doing something, but we don't really know what they're doing.

The solution to these is to replace them with constants, using a name that accurately describes their meaning.

Here's an example:

public void pay(Double subtotal, PaymentMethod pm) {
   if(pm.getId() == 1){
      throw new NotImplementedException();
   }

   Double total = subtotal * 1.10D * 1.37D;
   pm.pay(total);
}
Enter fullscreen mode Exit fullscreen mode

The numbers Mason! What do they mean??

To help with code readability and as a favor to the rest of your team (and yourself), we can replace these magic numbers with constants:

//You would usually put these in an Enum
public static final Double TAXES = 1.10D;
public static final Double SHIPPING_FEE = 1.37D;
public static final Long DEBIT = 1L;

public void pay(Double subtotal, PaymentMethod pm) {
   if(pm.getId() == DEBIT){
      throw new NotImplementedException();
   }

   Double total = subtotal * TAXES * SHIPPING_FEE;
   pm.pay(total);
}
Enter fullscreen mode Exit fullscreen mode

Now, our code speaks for itself and the meaning of those pesky magic numbers is evident.

And that's it! Two concepts to help you write cleaner code.

Do you have any techniques like these that you'd like to share with me? Leave them in the comments and let's help each other improve!

Top comments (0)