Why can't we override `||` and `&&`?

蹲街弑〆低调 提交于 2019-12-19 14:04:43

问题


David A. Black stated in his book:

[T]he conditional assignment operator ||=, as well as its rarely spotted cousin &&=, both of which provide the same kind of shortcut as the pseudooperator methods but are based on operators, namely || and &&, which you can’t override.

Why did he specifically mention that we can't override || and &&?


回答1:


Unlike some other operators on objects, who's behavior logically can depend on class, the boolean operators are part of the language. When you have an operator like, say, ==, it is logical to say that the behavior of this operator depends on the type of object. A string should check character by character, a Hash key-value tuple by key-value tuple, etc. However, the behavior of && and || are based on the language's definition of true and false, not anything object specific. If the language allowed you to override these operators, there could be no consistent boolean model, and these operators would become completely useless.

Additionally, there is a performance consideration too. Because && and || are short circut operators, which means that if the first argument to, say, &&, evaluates to false, the second one is never even evaluated. With ||, if the first evaluates to true, the second is never evaluated. This behavior would not be possible if you could override these operators, as in Ruby operators are overloaded as methods. And all parameters must be evaluated, by definition, before the method is called. So, the performance boost, and programming convenience of a short circuit operator is lost.



来源:https://stackoverflow.com/questions/15311349/why-cant-we-override-and

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!