开发者

Dealing with big IF statements in PHP

开发者 https://www.devze.com 2022-12-30 03:22 出处:网络
Is there any good alternative for the plain if statements in PHP? I know about switch, but I\'ll g开发者_Python百科uess that there\'s some more refined alternative out there that comes handy when work

Is there any good alternative for the plain if statements in PHP? I know about switch, but I'll g开发者_Python百科uess that there's some more refined alternative out there that comes handy when working with really big if statements.

Thanks a lot,


If you can't read your algorithm on one screen fold, there's a 99.9% chance you need to refactor your code toward more readability.

Change

if ($isHappening) {
  // ... millions of lines of code
} else {
  // .. another million lines of code
} 

into

if ($isHappening) {
  happen();
} else {
  didntHappen();
}

function happen() {
  // millions of lines of code
}

function didntHappen() {
  // another million lines of code
}


There really is no magic hammer out there. Your best bet to making them manageable is to break nested ifs into their own functions to make them more readable.

Also, don't forget about array_filter. That can save you from having to write a for loop to filter out items.

Also, you can eliminate nesting by using guard statements. You basically invert your if and do a return instead (another reason to break conditions into functions).


If you want to improve readability only, then you can always split up the expressions inside the if statement:

$exp1 = is_array($var) && isset($var['key']);
$exp2 = is_object($var) && isset($var->key);
$exp3 = substr($string, 0, 4) == 'foo';
$exp4 = ($exp1 || $exp2) && $exp3;
if ($exp4) {}

instead of

if (((is_array($var) && isset($var['key'])) || (is_object($var) && isset($var->key))) && substr($string, 0, 4) == 'foo') {}

Obviously, these are simplified examples, but you get the idea...


Welcome to the world of Object Orientation :)

class Case1 {
   function do() { echo "case 1"; }
}

class Case2 {
   function do() { echo "case 2"; }
}


$object = new Case1();

$object->do();

And then, there is dispatching using an array:

$choices = array( "case1" => new Case1(), "case2" => new Case2(), ... );

$choices[ $_GET["case"] ]->do();


Well if is if, there is not much else out there. Of course switch is an alternative but depending on the conditions it might not be applicable.

If you are doing OOP, the state design pattern might be what you need.

Otherwise you have to give more information...


If by "big" you mean large, highly nested "ifs", this is a clear sign of code smell, and you should be looking at OOP and design patterns.

0

精彩评论

暂无评论...
验证码 换一张
取 消