Hey everyone. I've been contemplating something lately and I haven't been able to come to a conclusion, so I thought I'd see what you all thought about it.

When checking for null (nevermind that we should try to not make something null in the first place), would it be better to check that something is not null and continue, or to check if it is null and exit the method early? ie:

A)

void method()
{
  if(object != null)
  {
     dostuff;
  }
}

or:

2)

void method()
{
  if(object == null)
    return;

  dostuff;
}

I tend to like option 2 better because it removes a level of indentation and it's just nicer to look at. On the other hand, I think remember hearing someplace that returning in the middle of a method is bad for some reason. I don't remember why, just that it is. So, if anyone has any ideas/thoughts/input I'd like to hear them!

Recommended Answers

All 4 Replies

As i am from java background ,generallly you'll get a NullPointerException when you try to access the object if it is null.
So whether you go for 1st option or 2nd option , one and the same and has same meaning.

I think remember hearing someplace that returning in the middle of a method is bad for some reason.

Your compiler will not feel anything bad about you whether you go for ist option or 2nd option because both will be equivalent to it..:)
So dont be sentimental..:)

Hehe, I know my compiler's feelings aren't gonna be hurt either way. I think the problem was something along the lines of that when a method is called, the loader does it's job and spends the time putting everything where it belongs and if you just exit from a method like that it has spend extra cleaning up from stopping early... or something like that. My assembly instructor told us this in college, but he was crazy, so maybe it doesn't matter anyways :)

If it's supposed to be impossible for a value to be null, don't check if it's null. But if it's possible and all you want to do is exit the function, either way is fine. Do what you want.

I think remember hearing someplace that returning in the middle of a method is bad for some reason.

The "some reason" is it's been argued that having multiple returns from a function makes the function harder to read, reason about, and verify for correctness. It's not a universal opinion; the other perspective is that such an argument takes structured programming to an unreasonable extreme.

So, if anyone has any ideas/thoughts/input I'd like to hear them!

They're both perfectly valid. I'd say use whichever option makes the most sense on a case-by-case basis.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.