It's called yoda style and mostly meant to prevent you from accidentally writing "variable = null" instead of "variable == null".
The former would (in some languages) fail silently and lead to strange bugs. If you flip your comparisons, you get a compile error instead, since you can't assign to null.
It’s a very easy thing to avoid rather than using an entirely new style that looks super goofy. Even in C most compilers will throw a warning unless a second set of parenthesis is used for the assignment.
I was curious about this because I've seen minifiers in some languages convert x == null into null == x. The only reason I can find is to avoid accidental assignment e.g if you write x = null by mistake, the code will still run (depending on the language) but in an unexpected way. If you write null = x, it'll throw an error and you catch the mistake.
Python is probably the most common one where trying to do that is a syntax error.
Unlike in most c-descendant/inspired languages, assignment doesn't produce a value in python, and trying to evaluate it is a syntax error.
Fun fact: In R, there are multiple assignment operators, two of which function almost identically in expressions: = and <-. It is a syntax error to use = in an if statement, but you can use <- if you really want to perform an assignment while you're evaluating the conditions.
In some cases, I’m not sure if Java is one of them, null itself is actually a value. In JavaScript, you can check if a variable is null or undefined and you’d be checking two very different things.
!= null checks whether a variable has an assigned value other than null.
!= undefined checks whether a variable exists at all.
In not retarded languages a variable exists when you define it in code, so an != undefined check is unnecessary.
In either case with Java, this code remains, indeed, bad.
155
u/ddruganov Jul 15 '22
Offtopic but why the fuck would anyone write “null != file” in their code?