Current location - Quotes Website - Personality signature - What are the established naming rules and specifications in jdk?
What are the established naming rules and specifications in jdk?
20 17 version of Ali java development manual: a lot, only a part can be copied, details can go to Baidu.

First, the programming convention?

( 1)? Naming convention?

1.? Mandatory? Naming in code cannot start or end with an underscore or dollar sign. ?

Counterexample:? _name? /? _ _ Name? /? $Object? /? Name _? /? Name $? /? Object $?

2.? Mandatory? It is forbidden to use English mixed pinyin for naming in the code, and it is not allowed to use Chinese directly. ?

Note: Correct English spelling and grammar can make readers easy to understand and avoid ambiguity. Note that even pure pinyin nomenclature

Also avoid using it. ?

Counterexample:? DaZhePromotion? [discount]? /? getPingfenByName()? [score]? /? int? A variable? =? 3?

Positive example:? Alibaba? /? Taobao? /? Youku? /? Hangzhou? Other international names can be regarded as English. ?

3.? Enforce class names? Capital letters? Style, must follow the hump form, but the following exceptions: (domain model

What do you do? /? Bo? /? DTO? /? VO? Wait a minute. ?

Positive example: Kyle Poirot? /? UserDO? /? XmlService? /? TcpUdpDeal? /? TaPromotion?

Counterexample: Humboldt? /? UserDo? /? XMLService? /? TCPUDPDeal? /? TAPromotion?

4.? Enforce the uniform use of method names, parameter names, member variables and local variables? lowerCamelCase? Must follow the style.

Hump form. ?

Positive example:? localValue? /? getHttpMessage()? /? inputUserId?

5.? Force constant names to be capitalized and words to be separated by underscores, so that the semantic expression is complete and clear, not too long. ?

Positive example:? Maximum inventory quantity?

Counterexample:? MAX_COUNT?

6.? Enforce abstract class naming? Abstract? Or? Base? Start; Use exception class name? Exceptions? The ending; Test class

Naming begins with the class name being tested and ends with. Testing? The ending. ?

7.? Mandatory brackets are part of the array type, and the array is defined as follows: String[]? args?

Counterexample: use? String? Args[]。 ?

8.? Forced POJO? Do not add any variables of Boolean type to the class. Otherwise, partial frame parsing will lead to serialization errors. ?

Counterexample: defined as basic data type? Bull? Published successfully; The nature of its method is also? isSuccess(),RPC

What is the attribute name corresponding to "Wei" when parsing the framework in reverse? Success, causing the property to be unavailable, and then throwing an exception.

Often. ?

9.? Force the package name to use lowercase English words, with only one natural meaning between dot separators. Unified use of package names

Singular form, but if the class name has plural meaning, the class name can be plural. ?

Positive example:? The utility class package is called. Com.alibaba.open.util, class name? MessageUtils (this rule refers to

Spring? Frame structure)?

10.? Forcibly put an end to completely irregular abbreviations to avoid ignorance. ?

Counterexample:? AbstractClass "abbreviation" naming? AbsClass condition "abbreviation" naming? Condi, this kind

Casual abbreviations seriously reduce the readability of the code. ?

1 1.? It is suggested that if design patterns are used, specific patterns should be embodied in the class names. ?

Description: Embodying the design pattern in the name helps readers to quickly understand the architectural design idea. ?

Positive example: public? Class? Order factory; ?

Public? Class? LoginProxy?

Public? Class? Resource observer; ?

12.? It is suggested that methods and properties in interface classes should not be decorated with any symbols (public? No), keep the code simple.

Sex, plus effectiveness Javadoc? Notes. Try not to define variables in the interface. If you have to define variables, you must.

It is related to the interface method and is the basic constant of the whole application. ?

Positive example: interface method signature: void? f(); ?

Interface basic constant representation: string? Company? =? Alibaba; ?

Counterexample: interface method definition: public? Abstract? Invalid? f(); ?

Description: JDK8? The default implementation is allowed in the interface, so this? Default? Method, which is valuable for all implementation classes.

Realize. ?

13.? There are two sets of rules for naming interfaces and implementing classes:?

1) forced to? Service? And then what? Tao? Class, based on? SOA? Exposed services must be interface and internal.

What is the implementation class of? Impl? The suffix of is different from the interface. ?

Positive example: CacheServiceImpl? Realize? CacheService? Interface. ?

2)? Recommended? If it is the name of the interface that describes the function. Take the corresponding adjective as the interface name? (usually-can? The form of)? . ?

Positive example: AbstractTranslator? Realize? Translatable.?

14.? Refer to the enumeration class name. Enum? Suffixes and enumeration member names need to be capitalized, and words are separated by underscores. ?

Note: Enumeration is actually a special constant class, and the constructor is forced to be private by default. ?

Positive example: enumeration name: DealStatusEnum, member name: SUCCESS? /? Unknown reason.

15.? Refer to the naming convention of each layer:?

a)? Business/road? Layer method naming convention?

1)? How to get a single object? Get? Make a prefix. ?

2)? How to get multiple objects? List? Make a prefix. ?

3)? How to get statistics? Count? Make a prefix. ?

4)? What is the insertion method? Save (recommended) or? Insert? Make a prefix. ?

5)? What is the method of deletion? Remove (recommended) or? Delete? Make a prefix. ?

6)? How to modify it? Update? Make a prefix. ?

b)? Domain model naming convention?

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

2)? Data transmission object: xxxDTO, xxx? Is a name related to the business field. ?

3)? Exhibition object: xxxVO, xxx? Usually the name of the web page. ?

4)? POJO? what's up DO/DTO/BO/VO? It is forbidden to be named? xxxPOJO .?

(2)? Constant definition?

1.? Force magic values (that is, undefined constants) not to appear directly in the code. ?

Counterexample:? String? Keys? =? " Id # Taobao _ "+tradeId; ?

Cache.put(key, value); ?

2.? Forcibly long? Or? Dragon? When making the initial assignment, you must use uppercase. L, can't it be lowercase l? lowercase is easy to follow numbers

1? Confuse and cause misunderstanding. ?

Caption: Dragon? Answer? =? 2l; ? Is it written in numbers? 2 1, or? Dragon? Type? 2?

3.? It is suggested not to use a constant class to maintain all constants, but to classify and maintain them separately according to constant functions. Such as: cache

Related constants are placed in the class: CacheConsts? Downward; Constants related to system configuration are placed in the class: ConfigConsts? Go down. ?

Note: For large and complete constant classes, you must use the search function to locate the modified constant, which is not conducive to understanding and maintenance. ?

4.? There are five levels of recommended constant reuse: sharing constants across applications, sharing constants within applications, and sharing constants within subprojects and packages.

* * * Enjoy in-class constants, * * * Enjoy in-class constants. ?

1)? Cross-application * * * shared constants: put them in the second party library, usually? client.jar? Are you online? Constant? Under the directory. ?

2)? In-app * * * Enjoy constants: put them in a library? Module? Are you online? Constant? Under the directory. ?

Counterexample: Easy-to-understand variables should also be defined as * * * shared constants in the application, and two siege engineers defined the representations in two classes respectively.

"Yes" variable:?

Class? Answer? China people: Gong? Static electricity Final? String? what's up =? "yes"; ?

Class? b? China people: Gong? Static electricity Final? String? what's up =? “y”; ?

A.yes. Equal to (B. Yes), what do you expect? Yes, but what is the actual return? False, causing online problems. ?

3)? * * * Shared constants within subprojects: that is, in the current subproject? Constant? Under the directory. ?

4)? * * * Enjoy the same package: that is, alone under the current package? Constant? Under the directory. ?

5)? Within-class * * * Shared Constant: Directly within the class? Private? Static electricity Final? Definition. ?

5.? It is suggested that if the variable value changes only within a range? Enum? Class. If you have extended properties other than the name, you must

Use? Enum? Class, the number in the following example is extended information, indicating the day of the week. ?

Positive example: public? Enum? {? Monday (1), Tuesday (2)? Wednesday (3)? Thursday (4)? Friday (5)? Saturday (6th)?

Sunday (7); }?

(3)? Format convention?

1.? Convention on the use of mandatory braces. If the braces are empty, write them directly as {} without line breaks; if

Non-empty code block:?

1)? Don't break a line before the opening brace. ?

2)? Wrap a line after the left parenthesis. ?

3)? Wrap a line before the closing brace. ?

4)? What else is after the right parenthesis? Or what? Code like this does not wrap; Indicates that a line break is required after the closing brace is terminated. ?

2.? Mandatory? There is no space between the left parenthesis and the last character; Similarly, there is no space between the right parenthesis and the previous character.

Grid. For more information, see section. 5? A positive example is indicated under the column. ?

3.? Force if/for/while/switch/do? Spaces must be placed between the equal sign reserved word and the left and right brackets. ?

4.? Force any operator to add a space around it. ?

Description: Operators include assignment operator =, logical operator &; &, symbols of addition, subtraction, multiplication and division, operators of three eyes, etc. ?

5.? Use forced indentation? 4? Space, forbidden to use? tab? Characters. ?

Description: If used? tab? Indentation, must be set? 1? Answer? tab? For what? 4? A space. Ideas? Settings? tab? For what? 4? When there is a vacancy,

Please don't tick? Use? tab? Character; What about now? Eclipse? , you must check? Insert? Space? For what? Tab.?

Positive example:? (involved? 1-5? Point)?

Public? Static electricity Invalid? main(String[]? args)? {?

//? Indent? 4? A space?

String? Say? =? "hello"; ?

//? There must be a space around the operator?

int? Flag? =? 0; ?

//? Key words? What if? There must be a space between and parentheses. f? With left parenthesis, 0? Don't need spaces with right brackets?

What if? (Flag? ==? 0)? {?

System.out.println (say); ?

}?

//? Add a space before the opening brace and do not wrap; Wrap after the left parenthesis?

What if? (Flag? ==? 1)? {?

system . out . println(" world "); ?

//? Line break before closing brace, followed by? Otherwise, don't break the line, okay?

Alibaba? Java? Development manual?

It is forbidden to be used for commercial purposes, and offenders will be prosecuted. 6? /? 37?

}? Or what? {

system . out . println(" ok "); ?

//? If it ends directly after the closing brace, it must be wrapped?

}?

}?

6.? Force not to exceed the limit of single-line characters? 120? A. If the line is broken beyond the need, the line shall be broken according to the following principles:?

1)? The second line is indented relative to the first line? 4? Spaces, starting from the third line, do not continue to indent, refer to the example. ?

2)? The operator is wrapped in the following. ?

3)? The dot symbol of the method call is wrapped in the following. ?

4)? The line break after multiple parameters is too long, comma. ?

5)? Don't wrap lines before parentheses. See counterexample. ?

Positive example:?

StringBuffer? sb? =? New? string buffer(); ?

//More than? 120? In the case of characters, line breaks are indented? 4? Spaces and periods are put together.

Sb addition ("child"). Additional ("xin") ...

. Additional ("yellow") ...?

. Additional ("yellow") ...?

. Add ("yellow"); ?

Counterexample:?

StringBuffer? sb? =? New? string buffer(); ?

//More than? 120? Do not wrap before parentheses in the case of characters?

Sb addition ("child"). Append ("xin") ... Append?

(Yellow);

//Method calls with many parameters may exceed? 120? Don't wrap characters before commas?

Method (args 1,? args2,? args3,? ...?

,? argsX); ?

7.? When defining and passing in mandatory method parameters, multiple parameter commas must be followed by spaces. ?

Positive example: The independent variable "A" in the following example must be followed by a space. ?

Method ("a", "b",? “c”); ?

8.? Mandatory IDE? what's up Words? Documents? Coding? Set to? UTF-8; ? IDE? Use line breaks in files? Unix? Format,

Don't use it windows? Format. ?

9.? It is suggested that there is no need to add some spaces to align the characters in one line with the corresponding characters in the previous line. ?

Positive example:?

int? Answer? =? 3; ?

Dragon? b? =? 4L; ?

Floating? c? =? 5F; ?

StringBuffer? sb? =? New? string buffer(); ?

Caption: Increase? sb? This variable, if it needs to be aligned, gives? a、b、c? Add a few spaces and there will be many variables.

In this case, this is a troublesome thing. ?

Alibaba? Java? Development manual?

It is forbidden to be used for commercial purposes, and offenders will be prosecuted. 7? /? 37?

10.? Recommend execution statement group, variable definition statement group, different business logic or different semantics in the method body.

Insert a blank line between. There is no need to insert blank lines between the same business logic and semantics. ?

Note: there is no need to insert multiple lines of spaces for separation. ?

(4)? OOP? Decree?

1.? Forcibly avoid accessing static variables or static methods of a class through its object references, which unnecessarily increases the compiler's access to.

Ben, just use the class name to access it. ?

2.? Force all override methods and must add @Override? Notes. ?

Counterexamples: getObject () and? The problem of get0bject (). One is a letter? Oh, one is a number? 0 plus @Override

It can accurately judge whether the coverage is successful. In addition, if the method signature is modified in the abstract class, its implementation class will be compiled immediately.

Translation error. ?

3.? Force the same parameter type and the same business meaning? Java? Variable parameters of, avoid using? Object.?

Note: Variable parameters must be placed at the end of the parameter list. Encourage students to try not to program with variable parameters?

Positive example: public? User? GetUsers (string? Type,? Integer ... ids)?

4.? Force an interface that is being called externally or relied on by a second-party library, and it is not allowed to modify the method signature to avoid the interface caller.

Influence. Interface must be @Deprecated? Annotate and clearly explain what the new interface or service is. ?

5.? Enforce that obsolete classes or methods cannot be used. ?

Description: java.net.URLDecoder? The method in? Decoding (string? encodeStr)? This method is outdated and should be eliminated.

Should I use two parameters? Decoding (string? Source? String? Coding). Because the interface provider is obviously an outdated interface,

Then it is obliged to provide new interfaces at the same time; As a caller, it is an obligation to verify what the new implementation of the outdated method is. ?

6.? Mandatory object? what's up Equal to? Methods are prone to null pointer exceptions, so they should be called with constants or objects with definite values.

Equal to 100.

Positive example:? "test" Equals (object); ?

Counterexample:? object . equals(" test "); ?

Description: Recommended? java.util.Objects#equals? (JDK7? Introduced tool classes)?

7.? Force value comparison between all packaging class objects of the same type and use them all? Equal to? Method comparison. ?

Description: used for? Integer? var? =? At - 128? Where to? 127? Assignment between integers? The object is in the

IntegerCache.cache? Produce,? Will existing objects be reused? In this range? Integer? This value can be directly used as = =

Judge? But all data outside this interval will be generated on the heap. Do not reuse existing objects? This is a big pit,

Recommended use? Equal to? Method to judge.

8.? The usage standards of basic data types and packaged data types are as follows:?

1)? Forcing everyone? POJO? Class attributes must use the wrapper data type. ?

2)? Mandatory RPC? The return value and parameters of this method must use the wrapper data type. ?

3)? It is recommended that all local variables use basic data types. ?

Caption: POJO? Class properties have no initial values to remind users that they must be explicitly assigned when they need to be used. any

NPE? The problem, or warehousing inspection, is guaranteed by the user. ?

Positive example: What might be the query result of the database? Empty, because it is automatically unpacked and received with basic data type? NPE? Risk. ?

Counterexample: for example, show the rise and fall of the total turnover, that is, positive and negative? x%,x? Called for the basic data type. RPC? Service, call

If it is not successful, return to the default value, and the page displays: 0%, which is unreasonable and should be displayed as a dash-. So packaging

Data type? null? Value, which can represent additional information, such as: remote call failed, abnormal exit. ?

9.? Mandatory definition? DO/DTO/VO? Wait? POJO? Class, do not set any property default values. ?

Counterexample: POJO? A little? gmtCreate? What is the default value? New? date(); However, this attribute is not embedded in data extraction.

Body value, when other fields are updated, the field will also be updated, resulting in the creation time being modified to the current time. ?

10.? Do not modify when adding properties to a forced serialization class. serialVersionUID? Field to avoid reverse sequence failure; such as

If it is completely incompatible with upgrade and avoids the confusion of deserialization, please modify it. serialVersionUID? Value. ?

Explanation: Attention? serialVersionUID? Inconsistency raises a serialization runtime exception. ?

1 1.? It is forbidden to add any business logic to the mandatory constructor. If there is initialization logic, please put it in? Initialize? Method. ?

12.? Forced POJO? Class must be written? toString? Method. Use? IDE? Intermediate tool: source & gt? Generation? toString

If you inherit someone else. POJO? Class, notice the prefix? Super toString.?

Description: When a method execution throws an exception, it can be directly called? POJO? what's up The toString () method prints its attribute values for easy arrangement.

Check the problem. ?

13.? Recommend index access? String? what's up Split? Method, what you need to do is whether there is a after the last delimiter.

Check the content, or you will lose it? IndexOutOfBoundsException? Risk. ?

Description:?

String? str? =? "A, B, C,,"; ?

String[]? ary? =? str.split(","); ?

//Expected greater than? 3. What was the result? 3?

system . out . println(ary . length); ?

14.? It is suggested that when a class has multiple constructors or methods with the same name, these methods should be put together in order.

Easy to read. ?

15.? Recommended? Is the definition order of methods within a class: public methods or protected methods? & gt? Private law? & gt? getter/setter

Method. ?

Note: public methods are the most concerned methods for class callers and maintainers, and the first screen display is the best; Although the protection method is only a subclass,

Attention may also be the core method under the "template design mode"; The private method generally does not need special attention from the outside world, and it is a

Black box implementation; Because of the low value of method information, all? Service? And then what? Tao? what's up getter/setter? Method is placed at the end of the class.

After that. ?

16.? Recommend a setter? In the method, the parameter name is the same as the name of the class member variable. Member name? =? Parameter name. exist

getter/setter? In terms of methods, try not to increase business logic and increase the difficulty of troubleshooting. ?

Counterexample:?

Public? Integer? getData()? {?

What if? (really)? {?

Return? Data? +? 100; ?

}? Or what? {?

Return? Data? -? 100; ?

}?

}?

17.? Recommend the connection method of strings in the loop body, and use? StringBuilder? what's up Additional? Method to extend the. ?

Counterexample:?

String? str? =? "start"; ?

For what? (int? Me? =? 0; ? Me? & lt? 100; ? i++)? {?

str? =? str? +? "hello"; ?

}?

Description: The decompiled bytecode file shows that every cycle will be? New? One? StringBuilder? Object and continue.

Additional? Operation, finally passed? toString? Method returns? String? Object, resulting in a waste of memory resources. ?

18.? The following situations are recommended and declared as follows. Final? Will be more suggestive:?

1)? Variables that do not need to be re-assigned, including class attributes and local variables. ?

2)? Add before object parameters? Final, indicating that it is not allowed to modify the pointing of the reference. ?

3)? The class method determines that it is not allowed to be overridden. ?

19.? Recommended for careful use? Object? what's up Cloning? Method to copy an object. ?

Description: Object's? Cloning? By default, this method is shallow replication. If you want to achieve deep replication, you need to rewrite it. Cloning? Method to implement the property object.

A copy of. ?

20.? The recommended class members and methods have strict access control:?

1)? What if the outside is not allowed to pass directly? New? To create an object, the construction method must be? Private.

2)? Tool classes are not allowed. Public? Or? Default? Construction method. ?

3)? Class is not? Static electricity Member variables are merged with subclasses * * *, which must be? Protected.?

4)? Class is not? Static electricity Member variable, and used only in this class, must be. Private.

5)? Class? Static electricity If a member variable is used only in this class, it must be. Private.

6)? If so? Static electricity Member variable, you must consider whether it is. Final.?

7)? Class member methods can only be used for class internal calls and must be. Private.

8)? Class member methods are only exposed to inherited classes, so what is the restriction? Protected.?

Description: Strictly control any class, method, parameter and variable. Too wide access range is not conducive to module decoupling. think

Test: What if it's one? Private? Method, want to delete it, but a? Public? what's up Service? Method, or

Answer? Public? Member variable, delete it, palms don't sweat? Variables are like your own children. Try to see them with your own eyes.

Within the line, the variable range is too large. If you run around without restrictions, then you will be worried.