Subverting Large If Blocks To Do Your Bidding

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

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: , ,

4 Comments to Subverting Large If Blocks To Do Your Bidding

Colin Dean
October 22, 2008

Neat. I often forget that PHP can do things like that.

Zack Douglas
October 25, 2008

Two things,

1) Did you intend to put a bitwise AND instead of logical AND in this line:

$ok = $ok & $obj->{$method_call}();

2) I’ve never been a fan of

$obj->{$method_call}();

, probably because it requires the context of the

for

loop to understand just what’s happening. Granted, this can shorten long

if

s, but the fact that PHP can handle

new $obj_name()

is a little absurd.

Eval

may seem a bit old-fashioned, but you can’t be more explicit. Other than that, I like your method better; to me,

break

has always been an underused instruction.

Zack Douglas
October 25, 2008

Wow, I apologize for the horrid formatting of that comment. Dang Wordpress for not being explicit about <pre> and <code>!

Zack Z.
December 17, 2008

Thats a pretty good refactoring because you’re reducing the likelihood of error and enhancing maintainability. What if you need to add $obj->Check7? That requires yet another nested if. Good job on that!

Leave a comment

WP_Big_City