如果满足某些条件,我想要一种只执行函数的优雅方法。我知道的两个选项是条件和第三级运算符。
如果
if(headerExists($listview) === false)
addHeader($listview, template);
叔
headerExists($listview) ? null : addHeader($listview);
对我来说,当你把整个函数看作时,if会使逻辑变得更难理解。第三级函数似乎很聪明,但你永远不会在任何地方看到它,并且必须声明null是明确浪费的空间。
答案 0 :(得分:2)
第三个选项是(ab)使用short-circuit behaviour的logical operators:
!headerExists($listview) && addHeader($listview, template);
// or
headerExists($listview) || addHeader($listview, template);
然而,这只是一种缩小技术(甚至不会使代码缩短很多)。出于可读性的原因,使用if语句,如果您想要没有块并且在一行中:
if (!headerExists($listview)) addHeader($listview, template);