Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should methods with return type void use a return statement?

I know that there are times when using return; can serve a useful purpose in Java, such as in guarding:

public void foo(Bar bar) {
    if(bar == null)
        return;

    // bar is not null, go ahead and do stuff with it
}

But what about just reaching the end of a method with return type void? For example,

public void printMenu() {
    System.out.println("Print out some boilerplate info here, line 1.");
    System.out.println("Print out some boilerplate info here, line 2.");
    System.out.println("Print out some boilerplate info here, line 3.");

    return;
}

Other than pure style preferences, are there any reasons for or against including that return;? If so, what are they?

EDIT: Well, that got answered quickly. To summarize the 15 answers posted below: "No."

like image 685
Pops Avatar asked Dec 15 '09 19:12

Pops


People also ask

Does void need a return statement?

A function that does not return a value is called a non-value returning function (or a void function). A void function will automatically return to the caller at the end of the function. No return statement is required.

Do methods need a return statement?

A return statement is used to exit from a method, with or without a value. For methods that define a return type, the return statement must be immediately followed by a return value. For methods that don't return a value, the return statement can be used without a return value to exit a method.

When a method has a return type of void What does that mean?

A void return type simply means nothing is returned. System. out. println does not return anything as it simply prints out the string passed to it as a parameter.

What happens when a return statement is executed in a void function?

When a return statement contains an expression in functions that have a void return type, the compiler generates a warning, and the expression isn't evaluated.


2 Answers

Perhaps you're paid by line of code?

Other then that there's really no reason to put an empty return in the end.

like image 154
ChssPly76 Avatar answered Nov 10 '22 08:11

ChssPly76


I avoid them, myself. It's just a useless line of code. In fact, PMD has a rule that checks for such useless return statements.

like image 37
Thomas Owens Avatar answered Nov 10 '22 08:11

Thomas Owens