martes, 14 de septiembre de 2010

Transforming If Conditions

I feel that breaking logic operations into several 'if' statements are easy to read and follow. But, from time to time I want to transpose them from single 'if' statement to multiple 'ifs' and vice versa. These are some patterns I use.

if(a==1) {
if(b==2{
f1();
}
}
/*AND*/ if (a==1 && b==2) { f1(); }

It looks a nice way to decompose a 'conjunction' (and); but it's not so well with 'disjunction' (or):

if(a==1) { f1(); }
if(b==2) { f1(); }
/*OR*/ if (a==1 || b==2) { f1(); }

But, if you have different conditions that execute the same statements, it's nice to know that you can join them with 'or'.

And now, there's one that annoyed me way too much, the empty 'if' block.

if(a==1) { /*nothing*/ }
else { f1(); }
/*NOT*/ if ( !(a==1) ) { f1(); }

I can remove that 'empty' block by negating the condition; but that extra parenthesis in NOT example looks odd. We can erase it by inverting that condition to:

if (a!=1) { f1(); }

And now, some other inversions of boolean operators:

if(a > b) ... if( !(a <= b) )
if(a >= b) ... if( !(a < b) )
if(a != b) ... if( !(a == b) )

It's fun to see that, if a number is not greater than another, it can, not be only lesser, but also equal; and that, if a number is neither less nor equal than another, then it's greater. Never forget the equal when inverting a less-than and greater-than operators.

Now I understand why the word NOT is never used in boolean variables. Which API method looks good: is_not_good() or !is_good()? Sorry for english language! ;-P

¿NOT is good? -vs- ¿NO está bien?

No hay comentarios:

Publicar un comentario