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/Jon_Hanson Aug 11 '15

Even in C, with all warnings on (which should be the default), the first conditional should generate a "conditional is always true" warning.

5

u/okmkz Aug 12 '15

Blessed -wall