views:

289

answers:

4

I came across some tests that included code like this:

if (this != null) {
    do something
}

Is this if clause of any use? Is there a purpose I don't get that makes this useful?

+13  A: 

this can never be null in Java so this kind of code is never useful.

Jesper
Heh, because of the general badness of the question I hadn't even noticed he was using <code>this</code>.
Bart van Heukelom
Well, in theory it would be null in a static context, but the compiler will prevent you from ever doing that :-)
kasperjj
@kasperjj `this` doesn't exist in a static context (i.e. it simply isn't there) - it's a bit strange to say that something that doesn't exist would "in theory be `null`"...
Jesper
+2  A: 

In Java the this keyword can only be used in a non-static method of a class.

Thus, if you are ever running code in the method, this cannot ever be null because you are guaranteed to have an instance of that object, otherwise the method would have never been able to be called.

jjnguy
Disappointment: With if (this == null) { a(); }, the compiler does not recognize a() as dead code.
Bart van Heukelom
A: 

You can't use "this" in a static environment that is the only place where "this" could be null.

You can call a static method or variable without an object, without an instance. "this" points to the current instance of the class. You can only use "this" if you have an object, so it will never be null.

luizbag
+1  A: 

I'm a pretty clueless programmer, so don't believe a word I say (and correct me if I'm wrong!), but it calls to mind cogito ergo sum -- I think, therefore I am. Descartes called it "the first and the most certain which presents itself to whoever conducts his thoughts in order." Similarly, that this != null seems to be (in Java, anyway, from the sound of it) among the most trivial conclusions code can reach. Neat!

Toph