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!

Dani AI

Generated

Short summary and practical guidance.

Guard clauses (early return) are fine and often clearer—they reduce nesting and make the "happy path" easier to read, which is what was getting at. The old rule against multiple returns comes from an era when manual cleanup dominated: single-exit simplified freeing resources and reasoning about control flow. Modern practice depends on the language and how resources are managed.

In C++ prefer types that encode intent: take a reference when nullptr must not occur, use std::optional for optional values, and prefer smart pointers or gsl::not_null for pointer semantics. With RAII, destructors run on every exit path, so early returns do not leak properly-managed resources:

void process(const Widget& w) {
    // caller guarantees a valid Widget; no null checks here
    w.perform();
}

void maybeProcess(const std::optional<Widget>& maybe) {
    if (!maybe) return;   // guard for optional presence
    maybe->perform();
}

In plain C (or any code that does manual allocation), multiple returns easily cause leaks unless cleanup is centralized. The standard idiom is a cleanup label so all exits pass through the same cleanup block:

int do_work(...) {
    FILE* f = fopen(...);
    void* buf = NULL;
    int err = -1;
    if (!f) return err;
    buf = malloc(...);
    if (!buf) goto cleanup;
    // work...
    err = 0;
cleanup:
    free(buf);
    if (f) fclose(f);
    return err;
}

Recommendation: for modern C++ favor guard clauses + expressive types + RAII; for C, use a single cleanup path. Be explicit about preconditions (assert or document), keep functions small, and adopt a consistent style for the project. and raised the readability/invariant points—both matter; choose the pattern that makes correctness and resource safety easiest to verify.

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.