On Friday, March 7, 2020 at 05:47:54 UTC-8, Chad wrote:
...
> Inverting the expression I mean having
>
> if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED"))
>
> as
>
> if ("android.intent.action.BOOT_COMPLETED").equals(intent.getAction())
>
> Is a bad practice. Because in the above case, the first catches the
> error at runtime while the other doesn't. While this might be okay in
> C++, carry this kind of practice over to other programming languages
> has some really really bad consequences.
No, this kind of practice would not be OK in C++. But when I say "this
kind of practice", I'm not referring to performing the comparison in the
"wrong" order. There shouldn't be a "wrong" order for an inherently
symmetric operator like equals() (or != in the C++ code you were
originally complaining about). The thing that is not OK about this code
is defining equals() in such a way that the order makes a difference.
Thanks to Jorgen, I now understand that this behavior depends upon the
fact that, unlike C++, Java supports null references. In C++, in order
for getAction() to indicate that there was no action to be gotten, it
would have to return a pointer, not a reference (or possibly
std::optional<> - but I'm not sufficiently familiar with std::optional<>
to be sure of that). Null pointers ARE supported in C++. You certainly
could define a comparison that takes pointer arguments, and compares the
things pointed at, rather than the pointers themselves. You could define
the function to either throw or return false when one of the pointers is
null - either behavior might make sense, in different contexts.
However, it is bad design to define equals() in such a way that, when pB
is null, equals(pA, pB) throws while equals(pB, pA) returns false. And
that's what's not OK about the java code you've shown. The C++ code you
claimed had undefined behavior displays no such problem.