An Anti-Pattern

Patterns in programming are short solutions to common problems, combining an idea with a way to program it. The lesser known anti-pattern is a common solution to a problem which is less than optimal, or even harmful. Today I’ve just got a few lines on a pet peeve which might just be called an anti-pattern.

The anti-pattern looks like:

   if( > 20)
      return TRUE;
   return FALSE;

This pattern can be seen even in the original quake source. To see why this is a bit daft, we can unpack it like the compiler does:

   float a = ( > 20);
   if(a) // means if(a == TRUE)
      return TRUE;
   return FALSE;

We return TRUE if a is TRUE, and FALSE if a is FALSE. The obvious simplification is

   float a = ( > 20);
   return a;

If we repack it we get the whole chunck of code down to one line:

  return ( > 20);

In tried and tested compilers for c and c++, both the anti-pattern and the fix result in the same output due to optimisations. QuakeC compilers are not so advanced, which means the final version is not just more concise, it’s also faster!


2 thoughts on “An Anti-Pattern

  1. It’s not a easy optimisation to implement correctly, there are probably lower-hanging fruit. I do think this change can improve how comprehensible a longer function is: you can see straight away “at this point we return something”, and work out what the something is later.

Leave a Reply

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

You are commenting using your 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