Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the programming styles of Java

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "what are the Java programming styles?". In the operation of actual cases, many people will encounter such a dilemma. Next, let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1.1 terminology description

In this document, unless otherwise stated:

The term class can refer to a normal class, enumerated class, interface, or annotation type (@ interface)

The term comment is only used to refer to the implementation comments of the implementation. Instead of the word "documentation comments", we use Javadoc.

Other terminology descriptions will occasionally appear in later documents.

1.2 Guide description

The sample code in this document is not a specification. That is, although the sample code follows the Google programming style, it doesn't mean that this is the only way to present the code. The format selection in the example should not be enforced as a rule.

Source file basis

2.1 File name

The source file is named after its topmost class name, is case-sensitive, and has a .java file extension.

2.2 File Encoding: UTF-8

The source file is encoded in UTF-8.

2.3 Special characters

2.3.1 White space character

Except for the line Terminator sequence, the ASCII horizontal space character (0 × 20, that is, space) is the only white space character allowed in the source file, which means:

White space characters in all other strings are escaped.

Tabs are not used for indentation.

2.3.2 Special escape sequence

For any character (\ b,\ t,\ n,\ f,\ r,\ ",\ 'and $$) with a special escape sequence, we use its escape sequence instead of the corresponding octal (such as 12) or Unicode (such as\ u000a) escape.

2.3.3 non-ASCII characters

For the remaining non-ASCII characters, whether to use the actual Unicode character (such as ∞) or the equivalent Unicode escape character (such as\ u221e) depends on which makes the code easier to read and understand.

Tip: when using Unicode escape characters or some actual Unicode characters, it is recommended to make some comments to explain, which is helpful for others to read and understand.

For example:

String unitAbbrev = "μ s"; | Yes, it is very clear even without comments.

String unitAbbrev = "\ u03bcs"; / / "μ s" | allowed, but there is no reason to do so

String unitAbbrev = "\ u03bcs"; / / Greek letter mu, "s" | allowed, but it is clumsy and error-prone.

String unitAbbrev = "\ u03bcs"; | it's too bad for the reader to see what it is.

Return'\ ufeff' + content; / / byte order mark | Good, for non-print characters, use escape and write comments if necessary

Tip: never make your code less readable for fear that some programs may not handle non-ASCII characters correctly. When the program cannot handle non-ASCII characters correctly, it will not run correctly, and you will fix these problems. (the implication is to boldly use non-ASCII characters, if really necessary)

Source file structure

A source file contains (sequentially):

License or copyright information (if necessary)

Package statement

Import statement

One * class (only one)

Each of the above parts is separated by a blank line.

3.1 license or copyright Information

If a file contains license or copyright information, it should be placed at the front of the file.

3.2 package statement

Package statements do not wrap, and column restrictions (Section 4. 4) do not apply to package statements. (that is, the package statement is written on one line)

3.3 import statement

3.3.1 import do not use wildcards

That is, do not appear an import statement like this: import java.util.*

3.3.2 do not change lines

Import statements do not wrap, and column restrictions (Section 4. 4) do not apply to import statements. (each import statement is a separate line)

3.3.3 sequence and spacing

Import statements can be divided into the following groups, each separated by a blank line in this order:

All static imports are grouped separately

Com.google imports (only if the source file is under the com.google package)

A third-party bag. Each package is in a group, in lexicographic order. For example: android, com, junit, org, sun

Java imports

Javax imports

There are no blank lines in the group and are arranged in dictionary order.

3.4 Class declaration

3.4.1 there is only one * class declaration

Each * class is in a source file with the same name (and, of course, the .java suffix).

Exception: package-info.java, there is no package-info class in this file.

3.4.2 Class member order

The order of members of a class has a great influence on ease of learning, but there is no only general rule. Members may be sorted differently by different classes. Most importantly, each class should sort its members by some logic, and the maintainer should be able to explain this sort logic. For example, new methods cannot always be habitually added to the end of the class, because they are sorted in chronological order rather than some kind of logic.

3.4.2.1 overload: never part

When a class has multiple constructors, or multiple methods of the same name, these functions / methods should appear together in order, without putting other functions / methods in the middle.

Format

Term description: a block-like construct refers to the body of a class, method, or constructor. It is important to note that the initial values in array initialization can be selectively treated as block structures (Section 4.8.3.1).

4.1 curly braces

4.1.1 use curly braces (even if optional)

Curly braces are used with if, else, for, do, while statements. Even if there is only one statement (or empty), you should write curly braces.

4.1.2 non-empty blocks: K & R style

For non-empty blocks and block structures, curly braces follow the Kernighan and Ritchie styles (Egyptian brackets):

Do not wrap before the opening curly brace

Wrap the line after the opening brace

Line wrap before closing curly braces

If the closing curly braces are the termination of a statement, function body, or class, wrap the line after the closing curly braces; otherwise, do not wrap. For example, if the closing curly brace is followed by an else or a comma, there is no line wrap.

Example:

Return new MyClass () {

@ Override public void method () {

If (condition ()) {

Try {

Something ()

} catch (ProblemException e) {

Recover ()

}

}

}

}

Section 4.8.1 gives some exceptions to the enum class.

4.1.3 empty blocks: you can use a concise version

An empty block structure contains nothing, and curly braces can be written succinctly as {} without the need for line breaks. Exception: if it is part of a multi-block statement (if/else or try/catch/finally), the closing braces wrap even if there is nothing inside them.

Example:

Void doNothing () {}

4.2 block indent: 2 spaces

Each time you start a new block, indent adds 2 spaces, and when the block ends, indentation returns to the previous indentation level. Indentation levels apply to code and comments. (see the code example in Section 4.1.2)

4.3 one statement at a time

Wrap the line after each statement.

4.4 column limit: 80 or 100

An item can choose a column limit of 80 characters or 100 characters, and with the exception of the following, any line that exceeds this character limit must automatically wrap.

Exception:

Rows that cannot satisfy column restrictions (for example, a long URL in Javadoc, or a long JSNI method reference).

Package and import statements (see sections 3.2 and 3.3).

The command lines in the comments that may have been cut and pasted into shell.

4.5 automatic line wrapping

Terminology description: in general, a long code is divided into multiple lines in order to avoid exceeding the column limit (80 or 100 characters), which we call line-wrapping.

We do not have a comprehensive, deterministic criterion to determine how to automatically break lines in each case. In many cases, there are several effective automatic line wrapping for the same piece of code.

Tip: extraction methods or local variables can solve the problem of long code without line wrapping (reasonably shorten the naming length)

4.5.1 where to disconnect

The basic rule of line wrapping is that you are more likely to break at a higher syntax level.

If you break at a non-assignment operator, break before the symbol (for example, +, which will be on the next line). Note: this is different from the programming style of other Google languages (such as C++ and JavaScript). This rule also applies to the following "class operator" symbols: dot separator (.), & () in type bounds, and pipe symbols in catch blocks (catch (FooException | BarException e))

If you break at the assignment operator, the usual practice is to break after the symbol (for example, =, it stays on the same line as the previous content). This rule also applies to semicolons in foreach statements.

The method name or constructor name is left on the same line as the left parenthesis.

The comma (,) is left on the same line as the content preceding it.

4.5.2 indent at least + 4 spaces when wrapping

When wrapping lines automatically, each line after the * * line is indented by at least 4 more spaces than the * * line (note: tabs are not used for indentation. See section 2.3.1).

When there is continuous automatic line wrapping, indentation may indent more than 4 spaces (when there are multiple levels of syntax elements). In general, two consecutive lines use the same indentation if and only if they start at the same level syntax element.

As noted in the section 4.6.3 horizontal alignment, the use of a variable number of spaces to align the symbols of the preceding lines is not encouraged.

4.6 Blank

4.6.1 Vertical Blank

A blank line is required in the following cases:

Between consecutive members within a class: fields, constructors, methods, nested classes, static initialization blocks, instance initialization blocks.

Exception: the blank line between two consecutive fields is optional, and the blank line used for the field is mainly used to logically group the field.

In the body of a function, blank lines are used between logical groups of statements.

Blank lines before or after a member in a class are optional (neither encouraged nor opposed, depending on individual preference).

To meet the blank line requirements of other sections in this document (for example, Section 3.3: import statement)

Multiple consecutive blank lines are allowed, but there is no need to do so (and we do not encourage it).

4.6.2 horizontal Blank

In addition to language requirements and other rules, and in addition to text, comments, and Javadoc using a single space, a single ASCII space also appears in the following places:

Separate any reserved word from the following left parenthesis ((), such as if, for catch, etc.).

Separate any reserved word from the closing curly braces (}) that precede it (such as else, catch).

Before any opening curly braces ({), there are two exceptions:

@ SomeAnnotation ({a, b}) (no spaces are used).

String [] [] x = foo; (no spaces between curly braces, see Note below).

On both sides of any binary or ternary operator. This also applies to the following class operator symbols:

& () in the type boundary.

The pipe symbol (catch (FooException | BarException e) in the catch block.

The semicolon in the foreach statement.

After,:; and closing parenthesis ()

If you comment after a statement, there are spaces on both sides of the double slash (/ /). Multiple spaces can be allowed here, but it is not necessary.

Between types and variables: List list.

In array initialization, the spaces in curly braces are optional, that is, both new int [] {5,6} and new int [] {5,6} are allowed.

Note: this rule does not require or prohibit the switch of a line or the need for extra spaces at the end of a line, only internal spaces.

4.6.3 horizontal alignment: no requirement

Term description: horizontal alignment refers to aligning the characters of a line with the corresponding characters of the previous line by adding a variable number of spaces.

This is allowed (and you can see such code in many places), but the Google programming style does not require it. Even for code that already uses horizontal alignment, we don't need to maintain this style.

The following example shows the unaligned code, followed by the aligned code:

Private int x; / / this is fine

Private Color color; / / this too

Private int x; / / permitted, but future edits

Private Color color; / / may leave it unaligned

Tip: alignment increases code readability, but it creates problems for future maintenance. Consider that at some point in the future, we need to modify a line in a bunch of aligned code. This may cause the otherwise beautiful alignment code to become misaligned. It is likely that it will prompt you to adjust the white space around the code to realign the pile of code horizontally (for example, the programmer wants to maintain this horizontal alignment style), which will make you do a lot of useless work, increase the work of reviewer and may lead to more merge conflicts.

4.7 limit groups with parentheses: recommended

We should not remove parentheses unless the author and reviewer agree that removing parentheses will not make the code misunderstood, or that removing parentheses will make the code easier to read. There is no reason to assume that the reader can remember the entire Java operator priority list.

4.8 specific structure

4.8.1 enumeration class

Enumeration constants are separated by commas, with optional line breaks.

Enumerated classes without methods and documents can be written in an array initialized format:

Private enum Suit {CLUBS, HEARTS, SPADES, DIAMONDS}

Because an enumerated class is also a class, all formatting rules that apply to other classes also apply to enumerated classes.

4.8.2 variable declaration

4.8.2.1 declare only one variable at a time

Do not use combination declarations, such as int a, b;.

4.8.2.2 declare when needed and initialize as soon as possible

Do not declare local variables all at once at the beginning of a code block (this is the practice of the c language), but only declare it when you need to use it * * times. Local variables are initialized when they are declared, or as soon as they are declared.

4.8.3 array

4.8.3.1 array initialization: can be written as a block structure

Array initialization can be written as a block structure, for example, the following are written in OK:

New int [] {

0, 1, 2, 3

}

New int [] {

0

one,

two,

three

}

New int [] {

0, 1

2, 3

}

New int []

{0, 1, 2, 3}

4.8.3.2 non-C style array declaration

Square brackets are part of the type: String [] args, not String args [].

4.8.4 switch statement

Term description: within the curly braces of the switch block is one or more statement groups. Each statement group contains one or more switch tags (case FOO: or default:), followed by one or more statements.

4.8.4.1 indent

In line with other block structures, the content in the switch block is indented to 2 spaces.

Start a new line after each switch tag, indent two more spaces, and write one or more statements.

4.8.4.2 Fall-through: comment

Within a switch block, each statement group is either terminated by break, continue, return or throwing an exception, or by a comment indicating that the program will continue to execute to the next statement group. Any comment that can express this meaning is OK (typically with / / fall through). This particular comment does not need to appear in a statement group (usually default). Example:

Switch (input) {

Case 1:

Case 2:

PrepareOneOrTwo ()

/ / fall through

Case 3:

HandleOneTwoOrThree ()

Break

Default:

HandleLargeNumber (input)

}

4.8.4.3 default should be written out.

Each switch statement contains a group of default statements, even if it contains no code.

4.8.5 Notes (Annotations)

Comments immediately follow the document block and are applied to classes, methods, and constructors, with a single comment on a single line. These line breaks are not automatic (Section 4.5, automatic line wrapping), so the indentation level remains the same. For example:

@ Override

@ Nullable

Public String getNameIfPresent () {...}

Exception: a single comment can appear on the same line as the signature line. For example:

@ Override public int hashCode () {.}

Comments applied to the field follow the document block, and multiple comments applied to the field are allowed to appear on the same line as the field. For example:

@ Partial @ Mock DataLoader loader

Parameters and local variable annotations have no specific rules.

4.8.6 comments

4.8.6.1 Block comment style

Block comments are at the same indentation level as the code around them. They can be /. / / style, or / /. style. For multi-line / *. / comments, subsequent lines must start with * and align with the * of the previous line. The following example comments are all OK.

/ *

* This is / / And so / * Or you can

* okay. / / is this. * even do this. , /

, /

Comments should not be enclosed in frames drawn by asterisks or other characters.

Tip: when writing multiline comments, if you want to wrap them again if necessary (that is, comments are like paragraph style), use / *. * /.

4.8.7 Modifiers

The modifiers for classes and members, if present, appears in the order recommended in the Java language specification.

Public protected private abstract static final transient volatile synchronized native strictfp

Naming convention

5.1 rules common to all identifiers

Identifiers can only use ASCII letters and numbers, so every valid identifier name matches the regular expression\ w +.

Special prefixes or suffixes used in other Google programming language styles, such as name_, mName, s_name, and kName, are no longer used in Java programming styles.

5.2 rules for identifier types

5.2.1 package name

Package names are all lowercase, and consecutive words are simply concatenated without underscores.

5.2.2 Class name

The class names are all written in UpperCamelCase style.

The class name is usually a noun or noun phrase, and the interface name may sometimes be an adjective or adjective phrase. There are no specific rules or established conventions for naming annotation types.

The naming of the test class starts with the name of the class it is testing and ends with Test. For example, HashTest or HashIntegrationTest.

5.2.3 method name

The method names are all written in lowerCamelCase style.

The method name is usually a verb or phrasal verb.

An underscore may appear in the JUnit test method name to separate the logical components of the name. A typical pattern is: test_, such as testPop_emptyStack. There is no only correct way to name the test method.

5.2.4 constant name

The constant name pattern is CONSTANT_CASE, with all uppercase letters and words separated by underscores. So, what exactly is a constant?

Each constant is a static final field, but not all static final fields are constant. When deciding whether a field is a constant, consider whether it really feels like a constant. For example, if the observed state of any of this instance is variable, it will almost certainly not be a constant. It is generally not enough to never plan to change the object, it has to be true all the time before it can be shown as a constant.

/ / Constants

Static final int NUMBER = 5

Static final ImmutableList NAMES = ImmutableList.of ("Ed", "Ann")

Static final Joiner COMMA_JOINER = Joiner.on (','); / / because Joiner is immutable

Static final SomeMutableType [] EMPTY_ARRAY = {}

Enum SomeEnum {ENUM_CONSTANT}

/ / Not constants

Static String nonFinal = "non-final"

Final String nonStatic = "non-static"

Static final Set mutableCollection = new HashSet ()

Static final ImmutableSet mutableElements = ImmutableSet.of (mutable)

Static final Logger logger = Logger.getLogger (MyClass.getName ())

Static final String [] nonEmptyArray = {"these", "can", "change"}

These names are usually nouns or noun phrases.

5.2.5 non-constant field name

Non-constant field names are written in lowerCamelCase style.

These names are usually nouns or noun phrases.

5.2.6 Parameter name

Parameter names are written in lowerCamelCase style.

Parameters should avoid being named with a single character.

5.2.7 Local variable name

Local variable names are written in lowerCamelCase style and can have looser abbreviations than other types of names.

Although the abbreviations are looser, you should avoid naming with a single character, except for temporary and circular variables.

Even if a local variable is final and immutable, it should not be shown as a constant, and naturally it cannot be named with the rules of a constant.

5.2.8 Type variable name

Type variables can be named in one of two styles:

A single capital letter that can be followed by a number (e, T, X, T2).

Named after the class (Section 5.2.2), followed by an uppercase T (e.g. RequestT, FooBarT).

5.3 Camel Nomenclature (CamelCase)

Hump nomenclature is divided into big hump nomenclature (UpperCamelCase) and small hump nomenclature (lowerCamelCase). Sometimes we have more than one reasonable way to convert an English phrase into a hump form, such as an acronym or an unusual structure (such as "IPv6" or "iOS"). Google specifies the following conversion scheme.

The name begins with the prose form (prose form):

Convert the phrase to a pure ASCII code and remove any single quotation marks. For example, "M ü ller's algorithm" will become "Muellers algorithm".

The result is divided into words and separated by spaces or other punctuation marks (usually hyphens).

Recommendation: if a word already has a common hump representation, divide it according to its composition (for example, "AdWords" will be divided into "ad words"). It is important to note that "iOS" is not a true hump representation, so this recommendation does not apply to it.

Now lowercase all letters (including abbreviations), and then capitalize the letters of the word:

The letters of each word are capitalized to get a big hump name.

Except for * words, the * letters of each word are capitalized to get a small hump name.

* concatenate all the words to get an identifier.

Example:

Prose form Correct Incorrect

-

"XMLHTTP request" XmlHttpRequest XMLHTTPRequest

"new customer ID" newCustomerId newCustomerID

"inner stopwatch" innerStopwatch innerStopWatch

"supports IPv6 on iOS?" SupportsIpv6OnIos supportsIPv6OnIOS

"YouTube importer" YouTubeImporter

YoutubeImporter*

An asterisk means yes, but it is not recommended.

Note: in English, some hyphen words are not unique in form. For example, "nonempty" and "non-empty" are both correct, so the method names checkNonempty and checkNonEmpty are also correct.

Programming practice

6.1@ Override: use if you can

Use the @ Override annotation as long as it is legal.

6.2 exceptions caught: cannot be ignored

With the exception of the following example, it is rarely correct not to respond to caught exceptions. (the typical response is to print the log, or if it is considered impossible, re-throw it as an AssertionError.)

If it really doesn't need any response in the catch block, it needs to be annotated (as in the example below).

Try {

Int I = Integer.parseInt (response)

Return handleNumericResponse (I)

} catch (NumberFormatException ok) {

/ / it's not numeric; that's fine, just continue

}

Return handleTextResponse (response)

Exception: in testing, if a caught exception is named expected, it can be ignored without comments. The following is a very common situation to ensure that the method being tested throws an expected exception, so there is no need to comment here.

Try {

EmptyStack.pop ()

Fail ()

} catch (NoSuchElementException expected) {

}

6.3 static members: calling using classes

Use the class name to call a static class member instead of specifying an object or expression.

Foo aFoo =...

Foo.aStaticMethod (); / / good

AFoo.aStaticMethod (); / / bad

SomethingThatYieldsAFoo () .aStaticMethod (); / / very bad

6.4 Finalizers: disabled

It is rare to reload Object.finalize.

Tip: do not use finalize. If you must use it, please read and understand Effective Java Section 7: "Avoid Finalizers" carefully, and then do not use it.

Javadoc

7.1 format

7.1.1 General form

The basic format of the Javadoc block is as follows:

/ * *

* Multiple lines of Javadoc text are written here

* wrapped normally...

, /

Public int method (String p1) {...}

Or in the following single-line form:

/ * An especially short bit of Javadoc. , /

The basic format is always OK. When the entire Javadoc block can fit on one line (and there is no Javadoc tag @ XXX), you can use a single line form.

7.1.2 paragraph

Blank lines (that is, lines that contain only the leftmost asterisk) appear between paragraphs and before the Javadoc tag (@ XXX), if any. Except for * paragraphs, each paragraph has a label in front of * words.

And there is no space between it and the words.

7.1.3 Javadoc Marker

Standard Javadoc tags appear in the following order: @ param, @ return, @ throws, @ deprecated. If these four tags appear, the description cannot be empty. When the description cannot fit on a line, consecutive lines need to be indented by at least four more spaces.

7.2 Abstract fragment

The Javadoc of each class or member begins with a short summary fragment. This fragment is very important, and in some cases, it is the only text that appears, such as in class and method indexes.

This is just a small fragment, which can be a noun phrase or a verb phrase, but not a complete sentence. It will not use A {@ code Foo} is a. Or This method returns... At the beginning, it will not be a complete imperative, such as Save the record.... However, because the beginning is capitalized and punctuated, it looks like a complete sentence.

Tip: a common mistake is to write a simple Javadoc as / * * @ return the customer ID * /, which is incorrect. It should be written as / * Returns the customer ID. * /

7.3 where do I need to use Javadoc

Using Javadoc at least at every public class and each of its public and protected members, here are some exceptions:

7.3.1 exception: a self-evident approach

It is optional for simple and obvious methods such as getFoo,Javadoc (that is, you don't have to write). In this case, there is really nothing worth writing but "Returns the foo".

Test methods in unit test classes are probably the most self-evident examples, and we usually know what they do from their descriptive naming, so no additional documentation is required.

Tip: if there is some relevant information that the reader needs to know, then the above exception should not be used as an excuse to ignore this information. For example, for the method name getCanonicalName, you shouldn't ignore the documentation, because the reader probably doesn't know what the word canonical name refers to.

7.3.2 exception: overload

If a method overloads a method in a superclass, Javadoc is not required.

7.3.3 optional Javadoc

Javadoc is also used for classes and methods that are not visible outside the package, if necessary. If a comment is used to define the overall purpose or behavior of a class, method, or field, then the comment should be written as Javadoc, which is more uniform and friendly.

This is the end of the content of "what are the programming styles of Java". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report