Tuesday, May 13, 2014

[Programming] #1: Accidental assignment to constants in conditions

Since I'm programming like...ALL THE TIME, might as well share some cool/stupid/retarded/awesome stuff along the way right? 

So let's start with something simple. You should have seen this at least once in your programming career. You want to write a simple statement like so:
bool isHappy = true; // I AM HAPPY!
if ( hello == false ) {   // WHEE~~
  // Awesome stuff happens
}

And you end up writing this:
bool isHappy = true; // I AM HAPPY!
if ( hello = false ) { // WAIT WHAT ARE YOU DOING?!
// Unintentional crap happens
}

Nobody I know does this on purpose, so it's usually an accident of forgetting the extra '=' to turn it into the comparative '==' operator. If you DO write code like this, please don't. For saving 1 extra line (basically placing it outside), you are confusing everyone including and potentially your future self when you revisit the code.

There is a surprisingly elegant way to handle this though. Basically flip the values like so!
bool isHappy = true; // I AM HAPPY!
if ( false = hello ) {   // compile ERROR
  // nothing happens!
}

This will force an error because you are trying to assign the boolean 'hello' to a constant value. If you write it correctly like so:
bool isHappy = true; // I AM HAPPY!
if ( false == hello ) { // YAY!!  
   // Awesome stuff happens
}

It is the same as the original intent! And you won't go wrong this time! Now you can rest assured that all your conditional statements involving constants are safe.

No comments:

Post a Comment