Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Long if statements and PSR-2

I'm about to migrate some code to the PSR-2 standard. In my code i have if statements with multiple lines as expression:

if (    $field->getBlockMode() == FieldInterface::BLOCK_MODE_HIDEVAR &&
        !isset($this->enabledBlocks[$field->getBlock()])
) {

}

What's the best practice to write such expressions?

like image 878
Johni Avatar asked Feb 19 '13 14:02

Johni


2 Answers

How about making it a one-liner to avoid that problem and make the statement more readable:

$blockModeIsHidevar = $field->getBlockMode() == FieldInterface::BLOCK_MODE_HIDEVAR;
$blockNotEnabled = !isset($this->enabledBlocks[$field->getBlock()]);

if ($blockModeIsHidevar && $blockNotEnabled) {

}

Alternative:

I usually do it with methods, this could looke like that:

if ($this->blockModeIsHidevar($field) && $this->blockNotEnabled($field)) {

}
// ...
private function blockModeIsHidevar($field)
{
    return $field->getBlockMode() == FieldInterface::BLOCK_MODE_HIDEVAR
}
private function blockNotEnabled($field)
{
    return !isset($this->enabledBlocks[$field->getBlock()])
}

This way, the optimization of && still takes place.

like image 188
Fabian Schmengler Avatar answered Sep 21 '22 15:09

Fabian Schmengler


Extract it into shorter boolean expressions first, then use those variables in your if() statement.

ie:

$hideVarMode = $field->getBlockMode() === FieldInterface::BLOCK_MODE_HIDEVAR;
$enabledBlock = !isset($this->enabledBlocks[$field->getBlock()];
if($hideVarMode && $enabledBlock) {
    ....
}

(note, I also turned your first test into a triple-equal, since this is likely to be better; feel free to change it back if that doesn't work for you)

like image 29
SDC Avatar answered Sep 23 '22 15:09

SDC