简体   繁体   中英

Should we have a newline after method name in Java?

This is one doubt regarding best practice in Java. Is it good idea to leave a blank line after method name. Eg. say I have following code

public void print(String str) {
    System.out.println("Hello word" + str);
}

So, here is it good practice to leave a blank line before Print statement? I checked Java doc regarding that. http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-141388.html

It says, Blank should be :- Between the local variables in a method and its first statement

I am not sure if it means the same thing that I am asking or it is something else.

Anything you can tell would be great.

The standard doesn't apply in your case because you have no local variables. So I'd say

// YES
public void print(String str) {
    System.out.println("Hello word" + str);
}

is just fine. Much better than:

// NO
public void print(String str) {
                                      // This blank line is unnecessary
    System.out.println("Hello word" + str);
}

The standard is talking about something like this:

// YES
public void print(String str) {
    double rand = Math.random(100);
                                        // A blank here is good
    System.out.println("Hello word" + str + "; today's number is " + rand);
}

being preferred over

// NO
public void print(String str) {
    double rand = Math.random(100);
    System.out.println("Hello word" + str + "; today's number is " + rand);
}

Short answer: No. That piece of the standard is meaning that you should leave a gap between the local variables and the first statement inside the method.

ie:

String someText = "text";
String moreText = "more text";
// gap here
System.out.println(someText + " " + anotherText);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM