r/java • • Aug 11 '15

Top 10 Useful, Yet Paranoid Java Programming Techniques

http://blog.jooq.org/2015/08/11/top-10-useful-yet-paranoid-java-programming-techniques/
181 Upvotes

76 comments sorted by

View all comments

17

u/galaktos Aug 11 '15

4. Avoid the accidental assignment

Yep. It happens to the best (although, not to me. See #7).

(Assume this is JavaScript, but let’s be paranoid about the language as well)

// Ooops
if (variable = 5) { ... }

// Better (because causes an error)
if (5 = variable) { ... }

// Intent (remember. Paranoid JavaScript: ===)
if (5 === variable) { ... }

Again. If you have a literal in your expression, put it to the left side. You can’t accidentally go wrong here, when you meant to add another = sign.

Does this make sense in Java? variable = 5 is only legal if variable is int (or Integer or a supertype), and then the expression is illegal as an if condition. AFAICT this is only legal if you’re comparing with true or false, and then you can just omit the comparison anyways and use either the expression (true) or its negation (false).

4

u/ExplosiveNutsack69 Aug 12 '15

I agree with you here. If you happen to be using an IDE that's making sure you don't slip up, it's impossible to mess this up. Quite honestly, it fucks with my head to think of something as "if 5 equals x" instead of as "if x equals 5", and just seems plain wrong.