Hacker News new | ask | show | jobs
by mikeash 3410 days ago
It's unnatural, confusing to read, and won't save you anyway in cases where you're comparing two variables.

It's OK if your tools absolutely can't diagnose accidental if(a = b), but it should be the last resort.

3 comments

In some languages it's better to use it, eg. in Java you can go with:

   mString != null && mString.equals("test")
or

   "test".equals(mString)
They do the same, but the second one adds hidden `defensive programming` to prevent NPE in `equals`. Saves time AND code.

Intended usage of if(a=b) should be written as if((a=b)). Don't know what tool you use at work or at home, but most static code analysers will point you that. Try SonarQube at least.

> It's unnatural, confusing to read ...

I feel as if that can rephrased "Don't do it because it is not done." A left-hand side constant is a convention that can have practical benefits in limited cases. Which at least should merit consideration.

"Don't do it because it is not done" is a good reason unless you're working solo and are sure your code will never be seen by others. And even then, it's a good idea to stick to what's done so you don't accumulate bad habits for projects that do have others looking at the code.
how would you write a yoda conditional with two variables? which is the yoda conditional (a == b), or (b == a)?
You can't if they're both mutable, since the whole idea of a yoda conditional is to put an immutable thing on the left side. What I meant was that you can't use them in that case, so it's a technique you can't use with 100% consistency.