CodeTalk
CodeTalk

Reputation: 3667

Null =! Object vs Object =! Null

This question is merely a comparison between doing:

if(Null != Object){
   /// code here.
}


if(Object != Null ){
   /// code here.
}

Can anyone chime in if one conditional statement if superior to the other? Is it case dependent?

I've always used Object != Null , but I heard about Null != Object today and wondered its differences?

Language agnostic.

-- Thank you to all for chiming in!

Upvotes: 0

Views: 88

Answers (4)

Jonathan Sternberg
Jonathan Sternberg

Reputation: 6647

The reason is really because of C, and usually deals with the equality operator rather than the inequality operator. It's because in C, you have = and ==, which both do completely different things. The problem is it's very easy to mistake one for the other, so you might end up with the following code:

int *i = malloc(sizeof(int));
if (i=NULL) {
    ... do nothing?
} else {
    free(i);
}

It's a very hard to miss bug, but this code should use the == operator. The problem is the compiler sees this as correct, and you've got a bug in your code.

I don't know a reason to do this with the inequality operator though other than style.

Upvotes: 1

adpalumbo
adpalumbo

Reputation: 3031

Some people like to use Null != Object because it's safer against typos. With the other form, you have a slightly higher risk of writing Object = Null, which might be a serious and hard-to-notice error.

Others prefer Object != Null because it reads more naturally in English.

But it's completely stylistic -- the two forms are functionally equivalent.

Upvotes: 1

David
David

Reputation: 218847

They are logically identical.

I've known people who prefer Null != Object and the most common reasons they give are:

  • It's less likely to have a bug by using = instead of == because Null = <anything> will result in a compiler error.
  • It's unique and cool.

The first reason sort of flies (though I don't think it's worth the hit to code readability), but I'm very much opposed to the second reason. I personally prefer Object != Null for readability. It's considerably closer to the actual spoken form of the logic being expressed. (Keep in mind that code is written primarily to be read by humans, and only has a minor secondary purpose of being executed by machines.)

Upvotes: 2

Jiminion
Jiminion

Reputation: 5168

Two things still have to be compared.

Upvotes: 0

Related Questions