Home  >  Article  >  Java  >  What are Java naming styles, constant definitions and code formats?

What are Java naming styles, constant definitions and code formats?

王林
王林forward
2023-04-25 14:28:06782browse

Naming style

1. [Mandatory] The names in the code cannot start with an underscore or dollar sign, nor can they end with an underscore or dollar sign.

Counterexample: _name / __name / $name / name_ / name$ / name__

2. [Mandatory] It is strictly prohibited to use a mixture of Pinyin and English for naming in the code , and direct use of Chinese is not allowed.

Note: Correct English spelling and grammar can make it easy for readers to understand and avoid ambiguity. Note that pure pinyin naming should be avoided.

Positive example: Renminbi / alibaba / taobao / youku / hangzhou and other internationally common names can be regarded as the same as English.

Counterexample: DaZhePromotion [Discount] / getPingfenByName() [Rating] / int A certain variable = 3

3, [Mandatory] The class name uses UpperCamelCase style, but the following Exceptions: DO/BO/DTO/VO/AO/PO/UID, etc.

Positive example: JavaServerlessPlatform / UserDO / #】Method names, parameter names, member variables, and local variables all use lowerCamelCase style and must follow camel case.

Positive example: localValue / getHttpMessage() / inputUserId

5. [MANDATORY] Constant names are all in capital letters, and words are separated by underscores to ensure complete and clear semantic expression. , don’t think the name is too long.

Positive example: MAX_STOCK_COUNT / CACHE_EXPIRED_TIME

Counter example: MAX_COUNT / EXPIRED_TIME6, [

Mandatory

] The abstract class name starts with Abstract or Base; exception The class name ends with Exception; the test class name starts with the name of the class it is to test and ends with Test.

7. The [

mandatory

] type is closely connected with square brackets to represent an array. Positive example: Define an integer array int[] arrayDemo;

Counter example: In the main parameter, use String args[] to define. 8. [

Mandatory

] Do not add the is prefix to Boolean type variables in the POJO class, otherwise some framework parsing will cause serialization errors.

Note: In the first table creation agreement in the MySQL specification of this article, the value expressing yes or no adopts the naming method of is_xxx. Therefore, it is necessary to set the mapping relationship from is_xxx to xxx in .

Counter example: An attribute defined as the basic data type Boolean isDeleted, and its method is also isDeleted(). When the RPC framework performs reverse parsing, it "mistakes" that the corresponding attribute name is deleted, resulting in failure to obtain the attribute. to, and an exception is thrown. 9. [

Mandatory

] Package names must be in lowercase, and there must be one and only one English word with natural semantics between dot separators. Package names always use the singular form, but if the class name has a plural meaning, the class name can use the plural form.

Positive example: The application tool class package name is com.alibaba.ai.util, and the class name is MessageUtils (this rule refers to the spring framework structure)

10, [Mandatory] Avoid using exactly the same names between member variables of child and parent classes, or between local variables in different code blocks, which will reduce readability.

Note: The subclass and parent class member variable names are the same. Even public type variables can be compiled. Local variables with the same name in different code blocks within the same method are also legal, but avoid using them. . For non-setter/getter parameter names, avoid being the same as member variable names.

Counter example: public class ConfusingName { public int age; // Non-setter/getter parameter names are not allowed to have the same name as member variables of this class public void getData(String alibaba) { if( condition) { final int money = 531; // ... } for (int i = 0; i < 10; i ) { // In the same method body, the same name as money in other code blocks is not allowed final int money = 615; // ... } } } class Son extends ConfusingName { // The same name as the member variable of the parent class is not allowed public int age; }

11, [

Mandatory

】Put an end to completely irregular abbreviations to avoid misunderstanding the meaning of the text.

Counterexample: The "abbreviation" of AbstractClass is named AbsClass; the "abbreviation" of condition is named condi. Such arbitrary abbreviation seriously reduces the readability of the code.

12. [Recommendation] In order to achieve the goal of self-explanation of the code, when naming any custom programming elements, use as complete a combination of words as possible to express its meaning.

Positive example: In JDK, the class name that expresses atomic updates is: AtomicReferenceFieldUpdater.

Counterexample: random naming of int a. 13. [

Recommendation

] When naming constants and variables, put the noun indicating the type at the end of the word to improve recognition.

Positive example: startTime / workQueue / nameList / TERMINATED_THREAD_COUNT

Counter example: startedAt / QueueOfWork / listName / COUNT_TERMINATED_THREAD

14. [Recommendation] If modules, interfaces, classes, and methods use design patterns, the specific patterns must be reflected in the naming.

Note: Reflecting the design pattern in the name will help readers quickly understand the architectural design concept.

Positive example:

public class OrderFactory; public class LoginProxy; public class ResourceObserver;

15. [Recommendation] Methods and Do not add any modifiers to the properties (nor public), keep the code concise, and add valid Javadoc comments. Try not to define variables in the interface. If you must define variables, they must be related to interface methods and are basic constants for the entire application.

Positive example: interface method signature void commit(); interface basic constant String COMPANY = "alibaba";

Counter example: interface method definition public abstract void f();

Note: Interfaces in JDK8 allow default implementations, so this default method is a valuable default implementation for all implementation classes.

16. There are two sets of rules for naming interfaces and implementation classes:

1) [Mandatory] For Service and DAO classes, based on the concept of SOA, exposed The service must be an interface, and the internal implementation class is distinguished from the interface by using the suffix

Impl.

Positive example: CacheServiceImpl implements the CacheService interface.

2) [Recommendation] If it is an interface name that describes capabilities, use the corresponding adjective as the interface name (usually the adjective of –able).

Positive example: AbstractTranslator implements the Translatable interface.

17. [Reference] The enumeration class name must be suffixed with Enum. The names of enumeration members must be in all uppercase letters and separated by underscores.

Note: Enumerations are actually special classes. Domain members are all constants, and the constructor is forced to be private by default.

Positive example: The member name of the enumeration named ProcessStatusEnum: SUCCESS / UNKNOWN_REASON.

18. [Reference] Naming convention for each layer:

A) Service/DAO layer method naming convention

1) Method to obtain a single object Use get as prefix.

2) Methods to obtain multiple objects are prefixed with list, and the plural form ends in: listObjects.

3) The method of obtaining statistical values ​​is prefixed with count.

4) The insertion method is prefixed with save/insert.

5) The deletion method is prefixed with remove/delete.

6) The modification method is prefixed with update.

B) Domain model naming convention

1) Data object: xxxDO, xxx is the name of the data table.

2) Data transfer object: xxxDTO, xxx is the name related to the business field.

3) Display object: xxxVO, xxx is generally the name of the web page.

4) POJO is the collective name of DO/DTO/BO/VO, and it is forbidden to name it xxxPOJO.

Constant definition

1. [Mandatory] does not allow any magic values ​​(i.e. constants that are not predefined) to appear directly in the code .

Counter example:

String key = "Id#taobao_" tradeId;cache.put(key, value);//When caching get, the underline is missed when copying the code, resulting in Problems caused by cache breakdown

2. [Mandatory] When assigning long or Long, use an uppercase L after the value, not a lowercase l. Lowercase is easily confused with the number 1. cause misunderstanding.

Explanation: Long a = 2l; Is it writing 21 as a number or 2 as a Long type.

3. [Recommendation] Do not use one constant class to maintain all constants. Classify them according to their functions and maintain them separately.

Note: The large and comprehensive constant class is disorganized. Only the search function can be used to locate the modified constants, which is not conducive to understanding and maintenance.

Positive example: Cache-related constants are placed under the class CacheConsts; system configuration-related constants are placed under the class ConfigConsts.

4. [Recommendation] There are five levels of constant reuse: cross-application shared constants, intra-application shared constants, intra-subproject shared constants,

in-package constants Shared constants, shared constants within classes.

1) Share constants across applications: placed in a second-party library, usually in the constant directory in client.jar.

2) In-application shared constants: placed in a library, usually in the constant directory in a submodule.

Counterexample: Easy-to-understand variables must also be uniformly defined as shared constants within the application. Two engineers defined "YES" variables in two classes:

In class A: public static final String YES = "yes";

In class B: public static final String YES = "y";

A.YES.equals(B.YES), expected to be true, but The actual return is false, causing online problems.

3) Shared constants within subprojects: that is, in the constant directory of the current subproject.

4) Shared constants within the package: that is, in a separate constant directory under the current package.

5) Shared constants within the class: defined directly inside the class private static final.

5【Recommendation】If the variable value only changes within a fixed range, use the enum type to define it.

Note: If there are extended attributes other than names, the enum type should be used. The numbers in the following example are extended information, indicating the

th season of the year.

Positive example:

public enum SeasonEnum { SPRING(1), SUMMER(2), AUTUMN(3), WINTER(4); private int seq; SeasonEnum(int seq) {this.seq = seq;} public int getSeq() { return seq;} }

Code format

1. [Mandatory] If the curly brackets are empty, simply write {} That’s it, there is no need for line breaks and spaces between the braces; if it is a non-empty code block:

1) There is no line break before the left brace.

2) Newline after the opening brace.

3) Line break before the right brace.

4) If there is else code after the right brace, there will be no line break; the line break must be after the right brace indicating termination.

2. There is no space between the left parenthesis and the character; similarly, there is no space between the right parenthesis and the character; and a space is required before the left brace. For details, see the correct example tips below Article 5.

Counterexample: if (space a == b space)

3. [Mandatory] If/for/while/switch/do and other reserved words and brackets Spaces must be added.

4. [Mandatory] Any binary or ternary operator requires a space on the left and right sides.

Description: Operators include assignment operator =, logical operator &&, addition, subtraction, multiplication and division signs, etc.

5. [Mandatory] Use 4 spaces for indentation and tab characters are prohibited.

Note: If you use tab indentation, you must set 1 tab to 4 spaces. When IDEA sets tabs to 4 spaces, do not check Use tab character; in eclipse, you must check insert spaces for tabs.

Positive example: (involving points 1-5)

public static void main(String[] args) {//Indent 4 spaces String say = "hello";//Operation There must be a space on the left and right side of the symbol int flag = 0;// There must be a space between the keyword if and the bracket. There is no need for a space between the f in the bracket and the left bracket, 0 and the right bracket if (flag == 0) {System .out.println(say); }// Add a space before the left curly bracket and do not break the line; wrap the line after the left curly brace if (flag == 1) { System.out.println("world");// Right curly brace Line break before, else after the right brace, no line break} else {System.out.println("ok");//End directly after the right brace, you must break the line}}

6, [ Mandatory】There must be exactly one space between the double slash of the comment and the comment content.

Positive example:

// This is an example comment, please note that there is a space after the double slash String param = new String();

The above is the detailed content of What are Java naming styles, constant definitions and code formats?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete