formate JAVA_spring-javaformat

Tips

Formatting and Checkstyle alone are not enough to produce truly consistent code.

Here are some tips that we’ve found useful when developing Spring Boot.

Excluding specific checks

If you want most SpringChecks but need to exclude one or two, you can do something like this in your checkstyle.xml:

/p>

"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"

"https://checkstyle.org/dtds/configuration_1_3.dtd">

Disabling formatting for blocks of code

Some code isn’t particularly amenable to automatic formatting.

For example, Spring Security configurations often work better when manually formatted.

If you need to disable formatting for a specific block of code you can enclose it in a @formatter:off / @formatter:on set:

// @formatter:off

... code not be formatted

// @formatter:on

Wrapping

The source formatter uses 120 chars for wrapping. This aims to strike a balance between

making use of available horizontal space in your IDE and avoiding unwanted additional

wrapping when viewing code on GitHub and the like.

If you’re used to longer lines, 120 chars can take some getting used to. Specifically, if

you have many nesting levels things can start to look quite bad. Generally, if you see

code bunched up to the right of your screen you should take that as a signal to use the

“extract method” refactor. Extracting small private methods will improve formatting and

it helps when reading the code and debugging.

Whitespace

Keeping whitespace lines out of method bodies can help make the code easier to scan.

If blank lines are only included between methods it becomes easier to see the overall structure of the class.

If you find you need whitespace inside your method, consider if extracting a private method might give a better result.

Comments

Try to add javadoc for each public method and constant.

Private methods shouldn’t generally need javadoc, unless it provides a natural place to document unusual behavior.

The checkstyle rules will enforce that all public classes have javadoc.

They will also ensure that @author tags are well formed.

Final

Private members should be final whenever possible.

Local variable and parameters should generally not be explicitly declared as final since it adds so much noise.

Read-down methods, fields and parameters

Methods don’t need to be organized by scope.

There’s no need to group all private, protected and public methods together.

Instead try to make your code easy to read when scanning the file from top to bottom.

In other words, try to have methods only reference method further down in the file.

Keep private methods as close to the thing that calls them as possible.

It’s also recommend that you try to keep consistent ordering with fields and constructor parameters.

For example:

class Name {

private final String first;

private final String last;

public Name(String first, String last) {

this.first = first;

this.last = last;

}

}

你可能感兴趣的:(formate,JAVA)