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).

8

u/din-9 Aug 11 '15

You are right. For all the bits of C that did get copied, at least they didn't make a non-zero int into a true condition. None of those compile in Java.