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 is the naming style, constant definition and code format of Java

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

What are the knowledge points of this article "Java naming style, constant definition and code format?" most people do not understand, so the editor summarizes the following contents, detailed contents, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "Java naming style, constant definition and code format" article.

Naming style

1. [mandatory] naming in the code cannot begin with an underscore or a dollar sign, nor can it end with an underscore or a dollar sign.

Counterexample: _ name / _ name / $name / name_ / name$ / name__

2. [mandatory] naming in the code is strictly forbidden to mix Pinyin with English, let alone directly use Chinese.

Explanation: 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: international names such as renminbi / alibaba / taobao / youku / hangzhou, which can be regarded as English.

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

3. [force] the class name to use UpperCamelCase style, with the following exceptions: DO / BO / DTO / VO / AO/ PO / UID, etc.

Positive example: JavaServerlessPlatform / UserDO / XmlService / TcpUdpDeal / TaPromotion

Counterexample: javaserverlessplatform / UserDo / XMLService / TCPUDPDeal / TAPromotion

4. [force] the method name, parameter name, member variable and local variable all use lowerCamelCase style and must follow the hump form.

Positive example: localValue / getHttpMessage () / inputUserId

5. [force] constant names are all capitalized, words are separated by underscores, and the semantic expression is complete and clear, so that the names are not too long.

Positive example: MAX_STOCK_COUNT / CACHE_EXPIRED_TIME

Counterexample: MAX_COUNT / EXPIRED_TIME

6. [force] abstract class naming starts with Abstract or Base; exception class naming ends with Exception; test class naming starts with the name of the class it wants to test and ends with Test.

7. The mandatory type is closely linked to the square brackets to represent the array.

Positive example: define the integer array int [] arrayDemo

Counterexample: in the main parameter, use String args [] to define it.

8. [force] Boolean variables in the POJO class are not prefixed with is, otherwise some frame parsing will cause serialization errors.

Note: in the first article of the table-building convention in this MySQL specification, the value of whether it is expressed or not is named by is_xxx, so it is necessary to set the mapping relationship from is_xxx to xxx.

Counterexample: the property defined as the basic data type Boolean isDeleted, and its method is also isDeleted (). When the RPC framework parses in the reverse direction, it "mistakenly thinks" that the corresponding attribute name is deleted, resulting in that the attribute cannot be obtained, and then an exception is thrown.

9. [force] English words with only one natural meaning between the dot separators and lowercase package names. The package name is uniformly singular, but if the class name is plural, the class name can be in the plural.

Positive example: the utility class package is named com.alibaba.ai.util and the class is named MessageUtils (this rule refers to the framework structure of spring)

10. [force] avoid using exactly the same naming between member variables of child parent classes, or between local variables of different code blocks, so that readability is reduced.

Description: subclass, parent class member variable name is the same, even public type variables can be compiled, and local variables in the same method in different code blocks of the same name is legal, but to avoid using. Non-setter/getter parameter names should also be avoided to be the same as member variable names.

Counterexample:

The parameter name of public class ConfusingName {public int age; / / is not allowed to have the same name as the member variable of this class: public void getData (String alibaba) {if (condition) {final int money = 531; / /...} for (int I = 0; I < 10; iSum +) {/ / in the same method body, and the same name as money in other code blocks is not allowed. / /...} class Son extends ConfusingName {/ / the same public int age; as the member variable name of the parent class is not allowed.

11. [force] put an end to completely irregular abbreviations and avoid ignorance of the meaning of the text.

Counterexample: AbstractClass "abbreviation" named AbsClass;condition "abbreviation" named condi, this kind of random abbreviation seriously reduces the readability of the code.

12. [recommended] in order to achieve the goal of code self-interpretation, any custom programming element uses as complete a combination of words as possible to express its meaning when naming.

Positive example: in JDK, the class that expresses atomic updates is called AtomicReferenceFieldUpdater.

Counterexample: the random naming of int a.

13. [recommended] when naming constants and variables, nouns indicating the type should be placed at the end of the word to improve recognition.

Positive example: startTime / workQueue / nameList / TERMINATED_THREAD_COUNT

Counterexample: startedAt / QueueOfWork / listName / COUNT_TERMINATED_THREAD

14. [recommended] if modules, interfaces, classes, and methods use design patterns, specific patterns should be reflected in naming.

Description: the design pattern is reflected in the name, which is helpful for readers to quickly understand the concept of architectural design.

Positive example:

Public class OrderFactory;public class LoginProxy;public class ResourceObserver

15. [recommended] do not add any embellishments to the methods and attributes in the interface class (neither do public), keep the code concise and add valid Javadoc comments. Try not to define variables in the interface, if you have to define variables, it must be related to the interface method, and is the basic constant of the whole application.

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

Counterexample: 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, the exposed service must be an interface, and the internal implementation class uses

The suffix of Impl is different from the interface.

Positive example: CacheServiceImpl implements the CacheService interface.

2) [recommended] if it is the name of the API that describes the capability, take the corresponding adjective as the name of the interface (usually the adjective of-able).

Positive example: AbstractTranslator implements the Translatable interface.

17. [reference] enumerated class names are suffixed with Enum, enumerated member names need to be capitalized, and words are separated by underscores.

Description: enumerations are actually special classes, domain members are constant, and constructors are forced to be private by default.

Positive example: enumerate members whose name is ProcessStatusEnum: SUCCESS / UNKNOWN_REASON.

18. [reference] naming protocols for each layer:

A) Service/DAO layer method naming specification

1) the method of getting a single object is prefixed with get.

2) the method of obtaining multiple objects is prefixed with list and ends in plural form such as: listObjects.

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

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

5) the method of deletion is prefixed with remove/delete.

6) the modified method is prefixed with update.

B) naming specification of domain model

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 domain.

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

4) POJO is a general term for DO/DTO/BO/VO, and it is forbidden to be named xxxPOJO.

Constant definition

1. [force] does not allow any magic values (that is, undefined constants) to appear directly in the code.

Counterexample:

String key = "Id#taobao_" + tradeId;cache.put (key, value); / / when caching get, problems occur due to missing underscores during code replication, resulting in cache breakdown

2. [force] when assigning long or Long values, use uppercase L after the value, not lowercase l. Lowercase is easy to be confused with the number 1, resulting in misunderstanding.

Description: Long a = 21; write 21 of the number, or 2 of Long.

3. [recommended] do not use a constant class to maintain all constants, but classify them according to their functions and maintain them separately.

Description: large and comprehensive constant class, disorganized, use the search function to locate the modified constant, which is not conducive to understanding and maintenance.

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

4. [recommended] there are five levels of constant reuse: sharing constants across applications, sharing constants within applications, sharing constants within sub-projects,

Share constants within packages and within classes.

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

2) shared constants within the application: placed in a library, usually under the constant directory in the sub-module.

Counterexample: easy-to-understand variables should also be uniformly defined as shared constants within the application, and the two engineers defined "YES" variables in two classes respectively:

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 actually returned as false, causing online problems.

3) shared constants within the sub-project: that is, under the constant directory of the current sub-project.

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

5) share constants within the class: private static final definition directly inside the class.

5 [recommended] if the value of a variable changes only within a fixed range, it is defined by the enum type.

Note: if there is an extension attribute other than the name, you should use the enum type. The number in the following example is the extension information, which represents the

What season is it?

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. [force] if the braces are empty, simply write {} without line breaks and spaces in the middle of the braces; if it is a non-empty code block:

1) do not wrap before the left curly brace.

2) wrap the line after the left brace.

3) wrap before the closing curly braces.

4) codes such as else after the closing curly braces do not wrap; the closing curly braces that indicate termination must be wrapped.

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 opening brace. For details, see the positive example below Article 5.

Counterexample: if (space a = b space)

3. Space must be added between reserved words such as if/for/while/switch/do and parentheses.

4. [force] any binocular and ternary operators need to add a space on the left and right sides.

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

5. [force] use 4 space indentation, forbid the use of tab characters.

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

Positive example: (involving 1-5 points)

Public static void main (String [] args) {/ / indent 4 spaces String say = "hello"; / / operator must have a space int flag = 0 flag / keyword if must have a space between parentheses, f in parentheses and left parentheses, 0 and closing parentheses do not need spaces if (flag = = 0) {System.out.println (say);} / left braces are preceded by spaces and do not wrap lines Line feed after opening brace if (flag = = 1) {System.out.println ("world"); / / line wrap before closing brace, followed by else, without line break} else {System.out.println ("ok"); / / if you end directly after closing brace, you must wrap}}

6. [force] there is only one space between the double slash of the comment and the content of the comment.

Positive example:

/ / this is a sample comment. Notice that there is a space String param = new String () after the double slash.

The above is about the content of this article on "Java naming style, constant definition and code format". I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.

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