Simple and clean code style should be expected by most engineers. In the work, the author often struggles because of the name. The exaggeration point can be said to be 5 minutes of programming and 2 hours of naming! Why is naming a stumbling block at work?

Each company has different standards in order to maintain uniformity, reduce communication costs, and improve team R & D efficiency. Therefore, in this article, the author combined the development specifications of Alibaba and the experiences in the work to sort out and summarize the relevant naming in the Java field, for reference only.

First, the naming convention in Java

Good naming can reflect the characteristics, meaning or purpose of the code, so that readers can quickly clarify the context of the program according to the meaning of the name. The naming forms used in different languages ​​are quite different. There are three naming forms commonly used in Java: UpperCamelCase with uppercase letters, lowerCamelCase with lowercase letters, and UPPER_CAMEL_UNSER_SCORE with all uppercase words separated by underscores. It is generally agreed that classes use big camel names, methods and local variables use small camel names, and capitalized names are usually used in constants and enumerations.

Types of

title All lowercase, multiple words separated by ‘-‘ spring-cloud
Package names All lowercase
Class name Capitalize the first letter of a word Feature, ParserConfig, DefaultFieldDeserializer
variable name Lowercase first letter. When multiple words are used, all words except the first word must be capitalized. password, userName
Constant name All capitals, multiple words, separated by ‘_’ CACHE_EXPIRED_TIME
method Same variable read (), readObject (), getById ()

Second, package naming

Package names are in lowercase uniformly , and there are only one natural English word or multiple words between the dot separators, which are naturally connected to one block (such as springframework, deepspace does not need to use any division). Package names use the singular form. If the class name has a plural meaning, you can use the plural form.

The structure of the package name can be divided into the following four parts [prefix] [initiator name] [project name] [module name]. Common prefixes can be divided into the following types:

Prefix name

indi (or onem) indi. initiator name. project name. module name … Individual projects refer to projects initiated by individuals but not completed by themselves. They can be public or private projects. Copyright mainly belongs to the initiator.
pers pers. personal name. project name. module name … Personal projects refer to projects initiated by individuals and completed on their own and can be shared. Copyright mainly belongs to individuals.
priv priv. personal name. project name. module name … A private project refers to a project initiated by an individual and completed on his own. It is a non-public private project. Copyright belongs to the individual.
team team. team name. project name. module name … A team project refers to a project initiated by a team and developed by the team. Copyright belongs to the team
Top-level domain com. company name. project name. module name … Company project, copyright is owned by the company that initiated the project

Third, class naming

The class name uses the camel naming form . The class name is usually a noun or noun phrase . In addition to the noun and noun phrase , the interface name can also use adjectives or adjective phrases, such as Cloneable, Callable, etc. Function or ability. For a test class, it starts with the class it is testing and ends with Test, such as HashMapTest.

For some special unique noun abbreviations, you can also use all uppercase names, such as XMLHttpRequest, but I believe that the abbreviation is less than three letters, and more than three letters are counted as words. There is no standard such as fastjson in Alibaba uses JSONObject as the class name, and Google uses JsonObjectRequest to name it. For this special abbreviation, the principle is to be unified.


Abstract class Abstract or Base BaseUserService
Enum class Enum as suffix GenderEnum
Tools Utils as suffix StringUtils
Exception class Exception end RuntimeException
Interface implementation class Interface name + Impl UserServiceImpl
Domain model related / DO / DTO / VO / DAO Positive example: UserDAO Counter example: UserDo, UserDao
Design pattern related classes Builder, Factory, etc. When using a design pattern, you need to use the corresponding design pattern as a suffix, such as ThreadFactory
Handle specific functions Handler, Predicate, Validator Represents processors, validators, and assertions. These class factories also have matching method names such as handle, predicate, and validate.
Test class Test end UserServiceTest, which is used to test the UserService class
MVC layering Controller, Service, ServiceImpl, DAO suffix UserManageController, UserManageDAO

四 、 Method

The method is named in the form of small hump . The first word is lowercase, and the first letter of each subsequent word must be capitalized. Unlike class names, method names are generally verbs or verb phrases , which together with parameters or parameter names form a verb-object phrase, that is, verb + noun. A good function name usually knows what kind of function the function implements by its name.

4.1 Methods to return true and false values

Note: Prefix- prefix, Suffix- suffix, Alone- use alone


Prefix is Whether the object meets the expected state isValid
Prefix can Whether the object can perform the desired action canRemove
Prefix should Whether the caller executes a command or method is good or bad , should it be , or should it be recommended or not recommended? shouldMigrate
Prefix has Does the object hold the expected data and attributes hasObservers
Prefix needs Does the caller need to execute a command or method needsMigrate

4.2 Methods to check


ensure Check if it is in the expected state, if not, throw an exception or return an error code ensureCapacity
validate Check if the status is correct, if not, throw exception or return error code validateInputs

4.3 On-demand methods


Suffix IfNeeded Perform when needed, do nothing when not needed drawIfNeeded
Prefix might Ibid mightCreate
Prefix try Attempt to execute, throw exception or return errorcode on failure tryCreate
Suffix OrDefault Attempt execution, return default value if failed getOrDefault
Suffix OrElse Attempt to execute, return the value specified in the actual parameter on failure getOrElse
Prefix force Force an attempt. error throws an exception or returns a value forceCreate, forceStop

4.4 Asynchronous methods


Prefix blocking Thread blocking method blockingGetUser
Suffix InBackground Execute threads in the background doInBackground
Suffix Async Asynchronous method sendAsync
Suffix Sync Synchronous method corresponding to existing asynchronous method sendSync
Prefix or Alone schedule Jobs and tasks are queued schedule, scheduleJob
Prefix or Alone post Ibid postJob
Prefix or Alone execute Execute asynchronous method (Note: I usually use this as the synchronous method name) execute, executeTask
Prefix or Alone start Ibid start, startJob
Prefix or Alone cancel Stop asynchronous methods cancel, cancelJob
Prefix or Alone stop Ibid stop, stopJob

4.5 callback methods


Prefix on Executed when an event occurs onCompleted
Prefix before Execute before event beforeUpdate
Prefix pre Ibid preUpdate
Prefix will Ibid willUpdate
Prefix after Executed after the event afterUpdate
Prefix post Ibid postUpdate
Prefix did Ibid didUpdate
Prefix should Executed when the event can be confirmed shouldUpdate

4.6 Methods of Manipulating Object Lifecycle


initialize initialization. Can also be used as a delayed initialization initialize
pause time out onPause, pause
stop stop onStop, stop
abandon Destruction alternative abandon
destroy Ibid destroy
dispose Ibid dispose

4.7 Methods related to set operations


contains Whether to hold the same object as the specified object contains
add Add to addJob
append Add to appendJob
insert Insert into subscript n insertJob
put Add element corresponding to key putJob
remove Remove element removeJob
enqueue Add to the bottom of the queue enqueueJob
dequeue Remove and remove from the head of the queue dequeueJob
push Add to the head of the stack pushJob
pop Remove from stack head and remove popJob
peek Remove from the top of the stack without removing it peekJob
find Find something that meets the conditions findById

4.8 Data-Related Methods


create Newly created createAccount
new Newly created newAccount
from New from something, or from other data fromConfig
to Conversion
update Update something updateAccount
load Read loadAccount
fetch Remote read fetchAccount
delete delete deleteAccount
remove delete removeAccount
save save saveAccount
store save storeAccount
commit save commitChange
apply Save or apply applyChange
clear Clear data or restore to the original state clearAll
reset Clear data or restore to the original state resetAll

4.9 Verbs in Pairs


get set
add remove remove
create destory removed
start stop stop
open open close close
read read write
load save save
create destroy
begin end
backup restore restore
import export
split merge
inject extract
attach detach
bind separate
view view browse browse
edit edit modify
select mark mark
copy paste
undo redo redo
insert delete
add join append
clean clear
index sort
find find search search
increase decrease
play play pause
launch launch run run
compile execute
debug debug trace
observe listen
build build publish
input output
encode decode
encrypt decrypt
compress decompress
pack unpack
parse emit
connect connect disconnect
send receive
download download upload upload
refresh refresh synchronize
update revert
lock unlock
check out check in
submit commit
push pull
expand expand collapse
begin end
start finish
enter exit exit
abort quit leave
obsolete depreciate
collect aggregate

Five, variable & constant naming

5.1 Variable Naming

Variables are variables whose values ​​can be changed while the program is running, including member variables and local variables. When a variable name consists of multiple words, the first letter of the first word is lowercase, and the first letter of the following words is uppercase. It is commonly known as camel nomenclature (also called camel nomenclature), such as computedValues, index and variable names. The role of the variable can be clearly expressed, and the name can reflect the specific business meaning.

Variable names should not begin with an underscore or dollar sign, although this is allowed syntactically. Variable names should be short and descriptive. The choice of variable names should be easy to remember, that is, to indicate their purpose. Try to avoid single-character variable names, except for one-time temporary variables. Do not add is to Boolean variables in pojo (all Boolean fields in the database must be prefixed with is_).

5.2 Constant Naming

The constant name is CONSTANT_CASE, generally all uppercase (except when used as a method parameter), the words are separated by underscores. So what is a constant?

Constants are values ​​that remain constant in scope and are generally modified using final. Generally divided into three types, global constants (public static final modification), in-class constants (private static final decoration) and local constants (constants in methods or parameters), local constants are more special, usually using small camel names .

 * demo
 * @author Jann Lee
 * @date 2019-12-07 00:25
public class HelloWorld {

     * local(positive)
    public static final long USER_MESSAGE_CACHE_EXPIRE_TIME = 3600;
     * local (negtive demo)
    public static final long MESSAGE_CACHE_TIME = 3600;
     * global 
    private static final String ERROR_MESSAGE = " error message";

     * member
    private int currentUserId;

     *  {@code message} 
     * @param message 
    public void sayHello(final String message){
        System.out.println("Hello world!");


Constants usually have their own business meanings. Don’t be afraid to omit or abbreviate the length . For example, the user message cache expiration time is better and clearer. It is up to you to judge.

Common naming rules

  1. Try not to use pinyin; avoid mixing pinyin with English. For some common expressions or difficult to describe in English, you can use Pinyin. Once you use Pinyin, you must not mix it with English.
    Positive example: BeiJing, HangZhou
    Counter example: validateCanShu
  2. Try to avoid special characters in the naming process, except for constants.
  3. Try not to duplicate the names of existing classes in the jdk or framework, nor use keywords in java.
  4. Use prepositions wonderfully, such as for (can be replaced with a homophone 4), to (can be replaced with a homophone 2), from, with, of, etc.
    For example, the class name uses User4RedisDO, the method name getUserInfoFromRedis, convertJson2Map, and so on.

Six, code annotations

6.1 Principles of annotations

Good naming increases code readability. Code naming often has strict restrictions. Unlike the annotations, programmers are often free to play, but it does not mean that they can do whatever they want. Elegant annotations usually satisfy three elements.

  1. Nothing is strange
    . Code without annotations is very unfriendly to the reader. Even if the code is cleared, the reader will at least psychologically conflict. Moreover, the code often has a lot of complex logic. Document the logic of the code, as well as the logic to clarify the changes.
  2. Less is more
    from the perspective of code maintenance, code notes must be best of the best. Reasonable and clear naming makes the code easy to understand. For simple logic and naming conventions, code that can clearly express the function of the code does not need annotations. The misuse of annotations adds an extra burden, not to mention most of it is nonsense.
Copy// get info from id(no use)
  1. Advance with the time
    annotations should change as the code changes, and the information expressed in the annotations should be exactly the same as in the code. In general, you must modify the comments after modifying the code.

6.2 Annotation Format

Annotations can be roughly divided into two types, one is javadoc annotations, and the other is simple annotations. Javadoc annotations can generate JavaAPI to provide effective support for external users. javadoc annotations can usually be automatically generated when using IDEA or Eclipse and other development tools, and also support custom annotation templates, which only need to explain the corresponding fields. Students participating in the same project development should try to set up the same annotation template.

a. package annotations

Package annotations are often special in the work. Through package annotations, you can quickly know what functions the current package code is used to implement. It is strongly recommended to add them in the work, especially for some more complicated packages. Below, the name is unified as

 * xxxx
 * 1. xxxx
 * xxxx
 * 2. yyy
 * yyyyyyyyyy
 * yyyyyyyyyyyyyyyyyyyy
 * @author cruder
 * @time 2019/12/7 20:30
package cn.mycookies.landingpagecheck;

b. Class annotations

In javadoc annotations, every class must have annotations.

* Copyright (C), 2019-2020, Jann  balabala...
* class info.....
* @author   
* @date     
* @version 

c. Attribute annotations

You must add a property comment in front of each property. There are usually two forms. As for how to choose, you are happy, but you must maintain uniformity in a project.

Copy/** tips */
private String userName;
 * password
private String password;

d. Method Notes

Each method must be preceded by a method comment, and each parameter in the method and the return value must be specified.

  * ...
  * @param xxx   
  * @return 
  * @throws 

e. Constructor annotation

Each constructor must be preceded by a comment. The comment template is as follows:

  * @param xxx   
  * @throws 

Simple annotations often require engineer byte definitions. When using annotations, pay attention to the following points:

  1. Each property value of an enumeration class must be annotated. An enumeration can be understood as a constant and usually does not change. It is usually referenced in multiple places. Modifying and adding properties to the enumeration usually brings great influences.
  2. Keep your typography neat and do not use end-of-line comments; separate them with a space after the double slash and asterisk.
Copyint id = 1;// neative demo
//negtive demo
int age = 18;
// positive
String name;
 * 1. multi lines
 * 2. space


Whether it’s naming or annotations, their purpose is to allow the code to talk to engineers, to enhance the readability and maintainability of the code. Good code can often be seen and understood, and annotations often complement and improve the naming.

Orignal link: