Brevity in Conditionals

Posted by Cory Petosky Tue, 09 Sep 2008 21:26:00 GMT

I see a lot of constructs in code that are just wordier than they need to be. All of these examples are in ActionScript 3, though most of them apply in other languages as well.

Many of these are also marginally faster than their wordier counterpart.

Testing booleans against true or false

var b:Boolean = isSomethingTrue();
if (b == true)
   doSomething();
else if (b == false)
   doSomethingElse();

Booleans are, by definition, either true or false, so you don’t need to check if they equal true or false in a conditional.

if (isSomethingTrue())
   doSomething();
else
   doSomethingElse();

Assigning boolean to literal based on conditional

var b:Boolean;
if (isSomethingTrue() && isSomethingElseTrue())
   b = true;
else
   b = false;

Same as above – the result of the expression is itself either true or false, so just use that result.

var b:Boolean = isSomethingTrue() && isSomethingElseTrue();

Explicit null testing

var o:Object = findObjectOrReturnNull();
if (o != null)
   useObject(o);

null implicitly casts to false when necessary, so you don’t need to check for null-ness – just toss the object itself in the conditional.

var o:Object = findObjectOrReturnNull();
if (o)
   useObject(o);

Using else if when only two states exist

var x:int = getRandomInt();
var y:int = getRandomInt();
if (x >= y)
   trace("X is bigger");
else if (y > x)
   trace ("Y is bigger");

If x is not greater than or equal to y, there’s only one option – y is greater than x. You don’t need to test for this in an else-if – just use else.

var x:int = getRandomInt();
var y:int = getRandomInt();
if (x >= y)
   trace("X is bigger");
else
   trace("Y is bigger");

Personally, I’d probably go one step further and use the ternary conditional operator in this case:

trace((x >= y ? "X" : "Y") + " is bigger");