Early-outs for n00bs

Sometimes I see people code something up like the following:

This situation has numerous problems.

  1. It’s difficult to read.
  2. The cohesion is terrible. If you trace a debug log to one of the debug statements, it is no where near the failure. So you have to sloppily figure out which if failed.
  3. It can get complicated.

At first it may seem that you can just pull all of the if statements together like this:

It’s pretty clear what the problem is. We simplified the statement, but we lost all our debugging information.
If one of the ANDed statements fails, we still have to check which one in the “else” clause.

Enter “Early-out”. The concept of an early-out is simple. Just check for negative conditions instead of positive ones.

  1. It keeps the errors together with the failure check.
  2. It makes the code easier to read
  3. Its easy to tell if you forgot something
  4. Use this method to check input arguments passed to the function

It’s simply a matter of reorganizing the code.

So all we did was reorganize the code, got rid of the “elses,” and changed the boolean logic to != instead of == on all if statements. This is a good way to make sure you’re testing all of your parameters for valid input before you actually execute any code… They’re called early-outs because they attempt to exit out of the function as early as possible. This avoids any unnecessary processing (that’s the theory any ways.)

Leave a Reply

You must be logged in to post a comment.