【问题标题】:Best practice for > < and == in a function> < 和 == 在函数中的最佳实践
【发布时间】:2015-09-04 13:53:24
【问题描述】:

我遇到了一个难题,我通常只使用一堆 if 或 switch。

为了说明这一点,我目前正在进行的项目涉及比较图像的宽度和高度以获取一个数字,以确定宽度是否比高度长或相同。

到目前为止,这是我的代码:

private function compare($width, $height)
{
    return $width - $height;
}

这正如您所料。

我想知道是否有更好的方法来做到这一点:

    if($this->compare($this->width, $this->height) == 0)
    {

    }
    if($this->compare($this->width, $this->height) < 0)
    {

    }
    if($this->compare($this->width, $this->height) > 0)
    {

    }

谢谢

【问题讨论】:

  • 为什么要麻烦进行第三次测试?只有 3 种可能性,所以只需使用 else. if (equal) else if (greater) else (...)`。一旦你消除了前两个可能性,它必须是 else,它小于。
  • 这里的正常做法不是使用if else else if,如if ($this-&gt;width &gt; $this-&gt;height) 等吗?不需要compare 函数。
  • 如果我有一个功能,我想知道“肖像”、“风景”或“正方形”。它会在代码 imo 中更好地阅读。只有我。
  • PHP7 将添加到您的选项中,并通过 spaceship (&lt;=&gt;) 运算符为您提供更多选择
  • 有时我发现已经引入了一些东西来让这样的事情变得更容易(比如@MarkBaker 即将发表的评论)。由于目前没有更好的解决方案,我会找到一种使用 ifs 和可能 elses 的方法,尽管我讨厌使用它们。

标签: php if-statement integer comparison


【解决方案1】:

对于 compare() 方法返回的值,你只有三个可能,所以我们只需要做两个条件就可以忽略一个:

$recievedValue = $this->compare($this->width, $this->height);
if( $recievedValue == 0 )
{
     // The value is equal to 0
}
else if( $recievedValue < 0 )
{
    // The value is less than 0
}
else
{
    // The value is more than 0
}

【讨论】:

  • 你好。 Este sito es en inglés, y desgraciadamente no se aceptan respuestas en otros idiomas。 Editaré tu respuesta a inglés, pero para el futuro, deberías publicar en inglés
  • 我知道,但是正在扩展到其他语言:有一个Portugese site 和一个Russian site。祈祷很快就会有一个西班牙人
  • 很好,但我来自哥伦比亚,我只会说西班牙语,下次我会用英语回答。谢谢。
【解决方案2】:

你可以让它成为 psr2 投诉者:

if ($this->compare($this->width, $this->height) == 0) {

} elseif ($this->compare($this->width, $this->height) < 0) {

} else {

}

阅读更多: PSR-2 Coding Style Guide

【讨论】:

  • 谢谢,您建议的方法在样式上与 3 ifs 选项相似,但我真的不喜欢 PSR-2 中 if 括号的样式。这是一个个人项目,所以会坚持保持开放。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-17
  • 2018-04-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多