开发者

Is it good practice to check for null and check object properties in the same if statement

Is it good practice to check for nu开发者_开发百科ll and check object properties in the same if statement?

Consider the following code:

if (jamesBlunt != null && jamesBlunt.isReallyBad()) {
   // Don't buy his records
}

This particular code is in java and I know the expression is evaluated from left to right so technically it won't throw a NullPointerException but in general is this good practice in any language?


As you are using an OR statement there will be a NullPointerException if jamesBlunt is null. You should use and, because if the left statement is false, the whole expression will be false.

Use:

if (jamesBlunt != null && jamesBlunt.isReallyBad()) {
   // Don't buy his records
}

When Java 7 is out, you could use the shortcut

if(jamesBlunt?.isReallyBad() {
       // Don't buy his records
}

But until then the explicit check for null would be best practice. (In fact it would be best practice to not use jamesBlunt objects...)


I'll assume the || is a typo and you meant && :)

To answer your question: it depends.

Does it make sense for jamesBlunt to ever be null? If not, then it would be better practice to have something like this:

void buyARecord(Artist jamesBlunt) {
    if (jamesBlunt == null) {
        throw new IllegalArgumentException("James should never be null!");
    }
}

If it does make sense for jamesBlunt to be null then your approach is fine, assuming null and isReallyBad mean the same thing semantically. If they mean different things semantically then you should probably not be combining them on one line.

You do need to be careful in other languages. Many (Java, C++, C# etc) will behave the same way, but some may evaluate from right-to-left or evaluate lazily. Take particular care with functional languages like Lisp and Scheme as they tend to behave differently to object oriented languages like Java and C#.


You want to use && instead of OR.

Yes, it is good practice to check for null in the same if statement, the alternative (nesting two ifs) is ugly because adds more indentation.

But checking before is also OK: specially if you want to do some error checking.


Personally, I would separate these. Null checking is the kind of thing one would do at the beginning of a function and is usually done to verify function parameters and are generally called "guard clauses". These checks will often raise an exception or return an error code as defined by the function.

These can lead to cleaner code below, avoiding multiple levels of nesting. It also prevents the need to repeat the null checks if there are other things you wish to test for on the object in question.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜