Fan Jia
Fan Jia

Reputation: 117

Should I always check return value fro something is null

If in one class A:

Class A
    public List<string> getValues

If i want to invoke the method, should I always check if the return value is null? although I don't think it could be null (should be an empty list). i.e.

Class B
    public void GetSomething
        foreach (var thing in A.getValues)
            //do something....

or

Class B
    public void GetSomething
        var things = A.getValues;
        if (things != null)
        foreach (var thing in things)
            //then doing something....

The reason for asking this question is that when I wrote unit test, I made the method in class A return null instead of empty list, however I dont know in real life if it happens, since if it could be null then it is always good to check rather than try catch the exception, Which one is more appropriate?

Upvotes: 2

Views: 641

Answers (2)

GermanK
GermanK

Reputation: 1686

In short, no, you shouldn't always check. The specification of the methods you use should always be clear in terms of what are the semantics for the possible results you expect. So, for example if you expect getValues to return an empty list when there are no values, and by mistake, you write it so it returns a null object, then a NullPointerException is a perfectly sane thing to happen. It is warninig you that you messed up the specification of your method or the implementation of it. On the other hand, it can be also the case that getValues return a null object because some condition hasn't been met. In that case, you should check, because it actually means something.

Upvotes: 6

tariq
tariq

Reputation: 2258

if you have made your method return null then you must always check for null before doing any operations.

in your case if you dont check for null and A.GetValues happens to be null , then it will throw an exception

Upvotes: 0

Related Questions