I’m still flabbergasted after going through the analysis of PHP ==
operator, posted by my infosec friend Gynvael Coldwind. Up until recently, I knew two things about PHP: (1) it tries to be weakly typed and (2) it is not a stellar example of language design. Now I can confidently assert a third one…
It’s completely insane.
However, pondering the specific case of equality checks, I realized it’s not actually uncommon for programming languages to confuse the heck out of developers with their single, double or even triple “equals”. Among the popular ones, it seems to be a rule rather than exception.
Just consider that:
==
and ===
, exactly like PHP does. And the former is just slightly less crazy than its PHP counterpart. For both languages, it just seems like a weak typing failure.=
(assignment) in lieu of ==
(equality), because the former is perfectly allowed inside conditions for if
, while
or for
statements.String.equals
method rather than ==
(like in case of other fundamental data types). Many, many programmers have been bitten by that. (The fact that under certain conditions you can compare strings char-by-char with ==
doesn’t exactly help either).Equals
and overload ==
operator. It also introduces ReferenceEquals
which usually works like ==
, except when the latter is overloaded. Oh, and it also has two different kinds of types (value and reference types) which by default compare in two different ways… Joy!The list could likely go on and include most of the mainstream languages but one of them would be curiously absent: Python.
You see, Python got the ==
operator right:
is
operator.int
, long
, float
) compare to each other just fine, but there is clear distinction between 42
(number) and "42"
(string).==
but there are no magical tricks that instantly turn your class into wannabe fundamental type (like in C#). If you really want value semantics, you need to write that yourself.In retrospect, all of this looks like basic sanity. Getting it right two decades ago, however… That’s work of genius, streak of luck – or likely both.