Reducing Nested Ifs

Having deeply nested ifs can make your code harder to read. If you have a function which doesn’t do anything unless all your tests succeed, you might be able to refactor it. Imagine we start with this function:

float(entity targ) BlessTarget =
{
   if(targ.takedamage)
   {
      if(targ.health > 0)
      {
         targ.health = targ.health + 50;
         if(targ.flags & FL_MONSTER)
            FindNewCommander(targ);
         return TRUE;
      }
   }
   return FALSE;
}

Notice all we do is return FALSE if either of the first two tests fail. We can turn the tests round, and return straight away:

float(entity targ) BlessTarget =
{
   if(!targ.takedamage)
      return FALSE;

   if(targ.health <= 0)
      return FALSE;

   targ.health = targ.health + 50;
   if(targ.flags & FL_MONSTER)
      FindNewCommander(targ);
   return TRUE;
}

Just by doing that our function now has no braces in it and much less indentation, which makes it easier to get to grips with.

Advertisements

One thought on “Reducing Nested Ifs

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s