【问题标题】:Best way to comment on if/else statement with PHP PSR-2使用 PHP PSR-2 评论 if/else 语句的最佳方式
【发布时间】:2018-03-26 22:04:53
【问题描述】:

在我看来,sample #2 似乎是更易读的评论方式。

但是如果我将 PSR-2 应用于两个样本,sample #1 不会改变,但 sample #2 的结果会发生如下变化,这不是正确的评论。

在这种情况下最好的评论方式是什么?

样品 #1
/* Read cached data */
if ($useCache == true){
    // do something
/* Download and cache data */
} else {
    // do something
}
样品 #2
/* Read cached data */
if ($useCache == true){
    // do something
}
/* Download and cache data */
else {
    // do something
}
样品 #2 的 PSR-2 结果
/* Read cached data */
if ($useCache == true){
    // do something
} /* Download and cache data */
else {
    // do something
}

结论 2017/12/13

到目前为止,最好的方法似乎如下: 标记它们在括号内

if ($useCache == true){
    /* Read cached data */
    // do something
}
else {
    /* Download and cache data */
    // do something
}

【问题讨论】:

  • 我认为评论会在 else 括号内。
  • 在我看来,您应该尝试将变量和函数命名为足够好的名称,而不必使用 cmets。通常,当代码更新时,cmets 不会更新。例如,您是否记得在修复拼写错误并将代码从 $useCash 更改为 $useCache 时更新 cmets?
  • >For instance would you remember to update the comments when you fix the spelling error and change the code from "$useCash" to "$useCache"? @rypskar Gee ...感谢您指出这一点!我已经修好了。正如您所提到的,变量和函数的命名确实足够好,因此不使用 cmets,但我必须在重构之前将前人留下的代码去意大利面,然后学习正确的方法。

标签: php comments psr-2


【解决方案1】:

PSR-2 没有说明如何制作 cmets 或故意阻止 cmets,所以你可以随心所欲。

有许多风格和实践元素被故意省略 本指南。这些包括但不限于:

  • 全局变量和全局常量的声明
  • 函数声明运算符和赋值
  • 行间对齐
  • 评论和文档块
  • 类名前缀和后缀

参考:http://www.php-fig.org/psr/psr-2/#conclusion

但是,根据 PSR-2,左大括号应与 if() 条件用空格字符分隔,else 应位于同一行并紧邻前一个右大括号,如下所示:

<?php
if ($expr1) {
    // if body
} elseif ($expr2) {
    // elseif body
} else {
    // else body;
}

参考:http://www.php-fig.org/psr/psr-2/#51-if-elseif-else


恕我直言,您的评论与 else 块内所做的事情有关,这是一个很好的理由,为什么应该将它放在 inside 该块内(只有函数、类和顶级构造具有在它们之上提取 docblock 的特权),所以我倾向于同意 Ibu 在这方面的评论(如果您要在某个时候编辑或删除 else 块,也应该更新块评论)。

【讨论】:

    【解决方案2】:

    @Ibu 确实。正如@Calimero所说,可能是这样的?

    if ($useCache == true){
        /* Read cached data */
        // do something
    } else {
        /* Download and cache data */
        // do something
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-07
      • 2015-11-01
      • 1970-01-01
      • 2015-01-31
      • 1970-01-01
      相关资源
      最近更新 更多