0

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!

4
Contributors
4
Replies
5
Views
6 Years
Discussion Span
Last Post by Narue
0

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..:)

Edited by harinath_2007: n/a

0

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 :)

Edited by bondo: n/a

0

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.

0

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.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.