Interesting Code

Subverting Large If Blocks To Do Your Bidding

Posted by jon on October 22, 2008
Interesting Code, Software Engineering / 3 Comments

I came across some “interesting” code today at work, and while I can’t share the actual code snippet I can share something similar. This is what I call 1337h4×0r code, because it works by basically subverting the intended use of the control structure.

1
2
3
4
5
6
7
8
9
10
11
if(($ok = $obj->Check1()) !== true) {
} else if(($ok = $obj->Check2()) !== true) {
} else if(($ok = $obj->Check3()) !== true) {
} else if(($ok = $obj->Check4()) !== true) {
} else if(($ok = $obj->Check5()) !== true) {
} else if(($ok = $obj->Check6()) !== true) {
}
 
if($ok === true) {
  //then do some stuff.
}

Upon first looking at it, I wanted to cry because of how unreadable it was, but after some code review I had a basic understanding of what was trying to be accomplished. Quite clever, but here is how I would have achieved the same result, and a bit more down the 1337h4×0r lines.

1
2
3
4
5
6
7
8
9
10
11
12
13
$ok = true
$methods = Array("Check1","Check2","Check3",
                 "Check4","Check5","Check6");
foreach($methods as $method_call) {
    $ok = $ok & $obj->{$method_call}();
    if($ok !== true) {
      break;
    }
}
 
if($ok === true) {
   //then do some stuff.
}

Why do I get that feeling that in PHP 6, this will all stop working?

Tags: , ,