HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMajor

Return explicitly or implicitly?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
returnimplicitlyexplicitly

Problem

Consider the following two code examples:

1.

void foo(boolean cake) {
    if (!cake)
        return;

    // TODO some work.
}


2.

void bar(boolean cake) {
    if (cake)
        //TODO some work.
}


Which one is the most readable/ semantic correct? With the first example you avoid additional indentation on the below code.

Should one return right away when there is no cake or not?

Solution

It depends on your intent. Your code should use idioms to match what its actually trying to do.

void foo(boolean cake) {
    if (!cake)
        return;

    // TODO some work.
}


Indicates that !cake is a precondition and as such is insignificant to what the function is doing.

void bar(boolean cake) {
    if (cake)
        //TODO some work.
}


Indicates that cake is an important part of what the function is doing.

Code Snippets

void foo(boolean cake) {
    if (!cake)
        return;

    // TODO some work.
}
void bar(boolean cake) {
    if (cake)
        //TODO some work.
}

Context

StackExchange Code Review Q#2541, answer score: 20

Revisions (0)

No revisions yet.