There’s a coding pattern that I like to use which I picked up from the InDesign 
SDK. When there’s some code which needs a lot of conditions to be executed, 
it’s hard to write the conditions in a way that’s easily human readable.

You can either do:
if(conditiona && conditionb && conditionc &&conditiond(
{
//do something
}

or:
if(conditiona){
  if(conditionb){
    if(conditionc){
      if(conditiond){
        // do something
      }
    }
  }
}

Both of these are kind of hard on the eyes and make fixes error-prone.

The do-while-false solution is much more ledgible than both of these and it 
goes like this:

do{
if(!conditiona){break};
if(!conditionb){break};
if(!conditionc){break};
if(!conditiond){break};
//do something
}while(false);

The reason it works is that do-while-false executes exactly once, and break 
leaves the “loop”.

The pattern reverses the logic and instead of checking when you *should* 
execute the code, it checks when you should bail out. The reason I like this 
pattern is because it makes for much flatter code and each condition stands on 
its own. That makes it easy to read and fix conditions at a later point.

How do folks feel about trying to use this pattern?

What prompted this post is commit b29975c which attempts to make a mess of 
conditions for invalidateSkinState() a bit clearer.

Thoughts?
Harbs

Reply via email to