为什么要使用短路代码? [英] Why use short-circuit code?

查看:452
本文介绍了为什么要使用短路代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

相关问题使用短路评估的好处为什么语言不使用短路评估?有人可以解释这行代码请吗? (逻辑和赋值运算符)

有关使用短路代码的语言的好处有些问题,但我想知道什么是好处为程序员?它只是它可以使代码更简洁吗?或者有性能原因吗?

There are questions about the benefits of a language using short-circuit code, but I'm wondering what are the benefits for a programmer? Is it just that it can make code a little more concise? Or are there performance reasons?

我不是问两个实体需要评估的情况,例如:

I'm not asking about situations where two entities need to be evaluated anyway, for example:

if($user->auth() AND $model->valid()){
  $model->save();
}

对我来说,推理是明确的 - 因为两者都需要是真的如果用户不能保存数据,可以跳过更昂贵的模型验证。

To me the reasoning there is clear - since both need to be true, you can skip the more costly model validation if the user can't save the data.

这也有一个明显的目的:

This also has a (to me) obvious purpose:

if(is_string($userid) AND strlen($userid) > 10){
  //do something
};

因为调用 strlen c $ c>使用非字符串值。

Because it wouldn't be wise to call strlen() with a non-string value.

我想知道的是使用短路代码,当它不影响任何其他语句。例如,从Zend应用程序默认索引页面:

What I'm wondering about is the use of short-circuit code when it doesn't effect any other statements. For example, from the Zend Application default index page:

defined('APPLICATION_PATH')
 || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));

这可能是:

if(!defined('APPLICATION_PATH')){
  define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));
}

或者甚至作为单个语句:

Or even as a single statement:

if(!defined('APPLICATION_PATH'))
  define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));

那么为什么要使用短路代码呢?只是为了使用逻辑运算符代替控制结构的凉爽因素吗?合并嵌套if语句?因为它更快?

So why use the short-circuit code? Just for the 'coolness' factor of using logic operators in place of control structures? To consolidate nested if statements? Because it's faster?

推荐答案

对于程序员,较少冗长的语法比另一个更详细的语法的好处是:

For programmers, the benefit of a less verbose syntax over another more verbose syntax can be:


  • 更少的类型,因此更高的编码效率


  • less to type, therefore higher coding efficiency
  • less to read, therefore better maintainability.

现在我只是说,不那么冗长的语法没有棘手或聪明的方式,只是同样公认的做法,但在更少的字符。

Now I'm only talking about when the less verbose syntax is not tricky or clever in any way, just the same recognized way of doing, but in fewer characters.

这通常是当你看到一种语言的特定结构,你希望你所使用的语言,但是没有必要意识到。一些例子在我的头顶:

It's often when you see specific constructs in one language that you wish the language you use could have, but didn't even necessarily realize it before. Some examples off the top of my head:


  • 在Java中的匿名内部类,而不是传递一个指针到一个函数)。

  • 在Ruby中,|| =运算符,用于计算表达式,如果计算结果为false或为null,则分配给它。当然,你可以通过3行代码实现同样的事情,但是为什么?

  • 还有更多...

这篇关于为什么要使用短路代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆