Php 如何将CleanCode的原则应用于我的代码中的else表达式?
如何删除代码下面不必要的else条件我们也保留了else语句中的代码,但我不想使用else语句Php 如何将CleanCode的原则应用于我的代码中的else表达式?,php,if-statement,Php,If Statement,如何删除代码下面不必要的else条件我们也保留了else语句中的代码,但我不想使用else语句 public function execute(array $responses) { foreach ($responses as $response) { if (!$response) { $this->callbackSBDL = $this->taskSchema; $this->generateTas
public function execute(array $responses)
{
foreach ($responses as $response) {
if (!$response) {
$this->callbackSBDL = $this->taskSchema;
$this->generateTask();
} else {
$this->queueHandler->findCompleted($this->taskSchema['tag']);
}
}
}
你可以使用三元运算符。试试这里 我不太明白你为什么要省略你的else,但是你可以按照这些思路做一些事情,用
就我个人而言,从干净代码的角度来看,我认为if/else更为冗长,任何阅读代码的人都很容易明白目标和目的是什么,而三元运算符或类似于上述代码的东西要求读者实际阅读代码中的所有步骤,尽管理解目的仍然相当简单,与初始的if/else相比,阅读和理解需要付出更多的努力。您可以根据$response变量中所有可能的值来确定要采取的行动,并编写一个“if”语句来涵盖每个值。在您的示例中,看起来您只需要确定$response是否为“false”,这样您就可以
public function execute(array $responses)
{
foreach ($responses as $response) {
if (!$response) {
$this->callbackSBDL = $this->taskSchema;
$this->generateTask();
}
if ($response) {
$this->queueHandler->findCompleted($this->taskSchema['tag']);
}
}
}
就我个人而言,我更愿意明确说明在什么情况下应该执行第一个“if”语句,大致如下
public function execute(array $responses)
{
foreach ($responses as $response) {
if (false === $response || null === $response || 0 === $response) {
$this->callbackSBDL = $this->taskSchema;
$this->generateTask();
}
if ($response) {
$this->queueHandler->findCompleted($this->taskSchema['tag']);
}
}
}
当然,这样做意味着您必须确保您的“如果”语句涵盖$response的所有可能值。如果您需要使用
else
code,那么为什么else
没有必要?当然,您在问这个问题的同一天收到了两个答案,但我看不出你对帮助过你的善良的志愿者做出了回应。请提供链接页面相关部分的摘要。人们应该能够使用您的答案,而无需遵循链接。有关更多信息,请阅读,特别是关于为链接提供上下文的部分。
public function execute(array $responses)
{
foreach ($responses as $response) {
if (false === $response || null === $response || 0 === $response) {
$this->callbackSBDL = $this->taskSchema;
$this->generateTask();
}
if ($response) {
$this->queueHandler->findCompleted($this->taskSchema['tag']);
}
}
}