我即将将一些代码迁移到PSR-2标准.在我的代码中,我有if多个行的语句作为表达式:
if ( $field->getBlockMode() == FieldInterface::BLOCK_MODE_HIDEVAR && !isset($this->enabledBlocks[$field->getBlock()]) ) { }
写这样的表达式的最佳做法是什么?
如何使它成为单行代码以避免该问题并使语句更具可读性:
$blockModeIsHidevar = $field->getBlockMode() == FieldInterface::BLOCK_MODE_HIDEVAR; $blockNotEnabled = !isset($this->enabledBlocks[$field->getBlock()]); if ($blockModeIsHidevar && $blockNotEnabled) { }
替代方案:
我通常用方法来做,这可以像这样说:
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()]) }
这样,优化&&仍然发生.