Why is short-circuiting not the default behavior in VB?

情到浓时终转凉″ 提交于 2019-12-01 15:06:19

Because the VB team had to maintain backward-compatibility with older code (and programmers!)

If short-circuiting was the default behavior, bitwise operations would get incorrectly interpreted by the compiler.

Why did we introduce AndAlso and OrElse? by Panopticon Central

Our first thought was that logical operations are much more common than bitwise operations, so we should make And and Or be logical operators and add new bitwise operators named BitAnd, BitOr, BitXor and BitNot (the last two being for completeness). However, during one of the betas it became obvious that this was a pretty bad idea. A VB user who forgets that the new operators exist and uses And when he means BitAnd and Or when he means BitOr would get code that compiles but produces "bad" results.

I do not find short-circuiting to be useful in every case. I use it only when required. For instance, when checking two different and unconnected variables, it would not be required:

  If x > y And y > z Then

  End If

As the article by Paul Vick illustrates (see link provided by Ken Browning above), the perfect scenario in which short-circuiting is useful is when an object has be checked for existence first and then one of its properties is to be evaluated.

  If x IsNot Nothing AndAlso x.Someproperty > 0 Then

  End If

So, in my opinion both syntactical options are very much required.

Explicit short-circuit makes sure that the left operand is evaluated first.

In some languages other than VB, logical operators may perform an implicit short circuit but may evaluate the right operator first (depending for instance on the complexity of the expressions at left and at right of the logical operator).

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