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?
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With