A clean, clean code style should be what most engineers expect. At work, I often struggle with naming. To exaggerate, it takes 5 minutes to program and 2 hours to name. Exactly why naming becomes a stumbling block in the work.
Each company has different standards to maintain uniformity, reduce communication costs and improve team r&d effectiveness. Therefore, this article is the author combined with Alibaba development specifications, as well as the work experience for the Java field related naming arrangement and summary, for reference only.
First, naming conventions in Java
Good naming can reflect the character, meaning, or purpose of the code, allowing the reader to quickly clarify the context of the program based on the meaning of the name. In Java, there are three common naming forms: UpperCamelCase (uppercase), lowerCamelCase (lower case), and UPPER_CAMEL_UNSER_SCORE (all uppercases and underscores). By convention, classes are generally named with a big camel, methods and local variables are named with a small camel, and uppercase underline is usually used in constants and enumerations.
type | The constraint | case |
---|---|---|
The project name | All lowercase, multiple words separated by underscore ‘-‘ | spring-cloud |
The package name | All lowercase | com.alibaba.fastjson |
The name of the class | Capitalize the first letter | Feature, ParserConfig,DefaultFieldDeserializer |
The variable name | Lowercase letter: When multiple words are composed, all words must start with a uppercase letter except the first word | password, userName |
Constant names | All caps, multiple words, separated by ‘_’ | CACHE_EXPIRED_TIME |
methods | With variable | read(), readObject(), getById() |
Two, package naming
The package names are all lowercase, and there is only one or more natural semantic English words between the dot delimiters, or more words are naturally connected together (for example, springframework and deepspace do not need to use any division). The package name must be singular. If the class name has a plural, it can be plural.
Package name can be divided into the following four parts [prefix] [initiator name] [project name] [module name]. Common prefixes can be classified as follows:
Prefix name | case | meaning |
---|---|---|
Indi (or ONEM) | Indi. Name of the initiator. Project name Module name…… | Individual project refers to a project initiated by an individual, but not completed by himself. It can be public or private, and the copyright mainly belongs to the initiator. |
pers | Pers. Personal name. Project name Module name…… | Individual projects refer to projects initiated, completed and shareable by individuals, and the copyright mainly belongs to individuals |
priv | Priv. personal name. Project name Module name…… | A private project refers to a project initiated by an individual, completed alone, not publicly available for private use, and the copyright belongs to an individual. |
team | Team. Team name. Project name Module name…… | Team project refers to the project initiated and developed by the team, and the copyright belongs to the team |
Top-level domain names | Com. Company name. Project name Module name…… | Company project, copyright is owned by the company sponsoring the project |
Third, class naming
In addition to nouns and noun phrases, interface names can also use adjectives or adjective phrases, such as Cloneable, Callable, etc., to indicate that the class that implements the interface has certain functions or capabilities. For a Test class, it starts with the class it is testing and ends with Test, such as HashMapTest.
It is also possible to use all caps for abbreviations of specific nouns, such as XMLHttpRequest, but I believe that abbreviations should be capitalized up to three letters, or more. There is no standard such as Fastjson in Alibaba, which uses JSONObject as the name of the class, and Google uses JsonObjectRequest. For this special abbreviation, the principle is unified.
attribute | The constraint | case |
---|---|---|
An abstract class | Abstract or Base | BaseUserService |
Enumeration class | Enum as suffix | OSType |
Utility class | Utils as a suffix | StringUtils |
Exception class | The Exception end | RuntimeException |
Interface implementation class | Interface name + Impl | UserServiceImpl |
Domain model correlation | /DO/DTO/VO/DAO | Example: UserDAO Example: UserDo, UserDAO |
Design pattern-related classes | Builder, Factory, etc | When you use a design pattern, you need to use the suffix of the corresponding design pattern, such as ThreadFactory |
Dealing with a specific function | The Handler, the Predicate, the Validator | It’s a processor, it’s a validator, it’s an assertion, and these class factories have method names like Handle, predicate, validate |
The test class | The Test end | UserServiceTest, which is used to test the UserService class |
MVC layered | Controller, Service, ServiceImpl, DAO suffix | UserManageController, UserManageDAO |
Four, the method
Method names are small humps, with the first letter in lower case and each subsequent word capitalized. Unlike class names, method names are usually verbs or phrasal verbs, which together with parameters or parameter names form verb-object phrases, i.e., verbs + nouns. A good function name usually tells you directly what the function does.
4.1 Method of returning true and false values
Note: Prefix- Prefix, Suffix- Suffix, Alone- used Alone
location | The word | meaning | case |
---|---|---|---|
Prefix | is | Whether the object meets the expected state | isValid |
Prefix | can | objectCan you performThe expected action | canRemove |
Prefix | should | Is when the caller executes a command or methodGood or bad.shouldOr,Recommended or not recommended | shouldMigrate |
Prefix | has | objectWhether to holdExpected data and attributes | hasObservers |
Prefix | needs | The callerIf you needExecute a command or method | needsMigrate |
4.2 Methods used for inspection
The word | meaning | case |
---|---|---|
ensure | Check whether the status is expected. If it is not, raise an exception or return error code | ensureCapacity |
validate | Check if it is a correct state. If it is not, raise an exception or return error code | validateInputs |
4.3 The on-demand approach
location | The word | meaning | case |
---|---|---|---|
Suffix | IfNeeded | Do it when you need it and do nothing when you don’t | drawIfNeeded |
Prefix | might | Same as above | mightCreate |
Prefix | try | Try to execute, throw an exception or return ErrorCode on failure | tryCreate |
Suffix | OrDefault | Attempts to execute, returns the default value on failure | getOrDefault |
Suffix | OrElse | Returns the value specified in the actual argument on failed attempts | getOrElse |
Prefix | force | A forcible attempt was made. Error throws an exception or returns a value | forceCreate, forceStop |
4.4 Asynchronous Related methods
location | The word | meaning | case |
---|---|---|---|
Prefix | blocking | Thread blocking method | blockingGetUser |
Suffix | InBackground | Threads that execute in the background | doInBackground |
Suffix | Async | Asynchronous methods | sendAsync |
Suffix | Sync | A synchronous method corresponding to an existing asynchronous method | sendSync |
Prefix or Alone | schedule | The Job and Task are put into the queue | schedule, scheduleJob |
Prefix or Alone | post | Same as above | postJob |
Prefix or Alone | execute | Execute asynchronous methods (note: I usually use this as the synchronous method name) | execute, executeTask |
Prefix or Alone | start | Same as above | start, startJob |
Prefix or Alone | cancel | Stop asynchronous methods | cancel, cancelJob |
Prefix or Alone | stop | Same as above | stop, stopJob |
4.5 Callback method
location | The word | meaning | case |
---|---|---|---|
Prefix | on | Execute when an event occurs | onCompleted |
Prefix | before | Execute before the event occurs | beforeUpdate |
Prefix | pre | Same as above | preUpdate |
Prefix | will | Same as above | willUpdate |
Prefix | after | Execute after the event occurs | afterUpdate |
Prefix | post | Same as above | postUpdate |
Prefix | did | Same as above | didUpdate |
Prefix | should | Execute when confirming whether the event can occur | shouldUpdate |
4.6 Methods of operating the object life cycle
The word | meaning | case |
---|---|---|
initialize | Initialization. Can also be used as deferred initialization | initialize |
pause | suspended | OnPause, pause |
stop | stop | OnStop, stop |
abandon | Substitution of destruction | abandon |
destroy | Same as above | destroy |
dispose | Same as above | dispose |
4.7 Methods related to collection operations
The word | meaning | case |
---|---|---|
contains | Whether to hold the same object as the specified object | contains |
add | add | addJob |
append | add | appendJob |
insert | Insert it at subscript n | insertJob |
put | Add the element corresponding to the key | putJob |
remove | Remove elements | removeJob |
enqueue | Add to the last bit of the queue | enqueueJob |
dequeue | Remove the head from the queue | dequeueJob |
push | Add to stack header | pushJob |
pop | Remove from stack header | popJob |
peek | Removed but not removed from the stack header | peekJob |
find | Look for something that fits the bill | findById |
4.8 Methods related to data
The word | meaning | case |
---|---|---|
create | The newly created | createAccount |
new | The newly created | newAccount |
from | Create it from something that already exists, or create it from some other data | fromConfig |
to | conversion | toString |
update | Update something that already exists | updateAccount |
load | read | loadAccount |
fetch | The remote reading | 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 it to its original state | clearAll |
reset | Clear data or restore it to its original state | resetAll |
4.9 Pairs of verbs
The word | meaning |
---|---|
Get access to | The set set up |
Increase the add | Remove delete |
The create create | Destory removed |
Start starts | Stop stop |
Open to open the | Close close |
Read read | Write to write |
The load is loaded | Save save |
The create create | Destroy the destruction |
Begin to start | End to end |
Backup backup | Restore to restore |
The import import | Export export |
The split segmentation | The merge with |
Inject injection | The extract extracted |
The attach attached | Detach from |
Bind the binding | Separate separation |
The view to see | Browse through |
Edit to edit | The modify change |
Select select | Mark mark |
Copy copy | Paste paste |
Undo to cancel | Redo redo |
Insert to insert | Delete to remove the |
The add to join | Append to add |
The clean clean | The clear clear |
The index index | The sort order |
Find find | Search search |
Happens to increase | Decrease reduce |
Play play | Pause suspends |
Launch start | Run run |
The compile compile | The execute perform |
The debug debugging | Trace tracking |
Observe observe | Listen to monitor |
Build building | The publish release |
The input input | The output output |
Encode coding | Decode decoding |
Encrypt encrypt | Decrypt decrypt |
Compress the compression | Decompress the decompression |
Pack pack | Unpack unpack |
The parse analytical | Emit generated |
Connect the connection | Disconnect disconnect |
Send to send | The receive receive |
Download download | The upload to upload |
Refresh to refresh the | The synchronize synchronization |
The update to update | Revert back |
The lock lock | Unlock the unlock |
Check out the checkout | Check in to check in |
Submit to submit | Commit to deliver |
Push push | Pull pull |
Expand open | The collapse collapse |
Begin to start | End to end |
Start start | Finish to complete |
Enter into the | The exit exit |
Abort to give up | The quit leave |
Obsolete scrap | Depreciate old |
Collect collect | Aggregate gathered |
Fifth, variable & constant naming
5.1 Variable Naming
Variables are variables whose values can be changed during program execution, 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, commonly known as camel naming (also known as camel naming), such as computedValues, index, variable naming, as short as possible to clearly express the function of the variable, the name reflects the specific business meaning.
Variable names should not begin with an underscore or dollar sign, although this is syntactically permissible. Variable names should be short and descriptive. Variable names should be chosen to be easy to remember, that is, to indicate their purpose. Avoid single-character variable names unless they are one-time temporary variables. Pojo Boolean variables should not be prefixed with is(all Boolean fields in the database should be prefixed with IS_).
5.2 Constant Naming
Constants are named CONSTANT_CASE, usually in all capitals (except when used as method parameters), and words are separated by underscores. So what is a constant?
Constants are values that remain constant in scope and are typically modified with final. There are three types of constants: global (public static final), internal (private static final), and local (constant within a method or parameter). Local constants are special, and are usually named with a small hump.
/** * a demo **@author Jann Lee
* @dateThe 2019-12-07 00:25 * * /
public class HelloWorld {
/** * global constant (positive example) */
public static final long USER_MESSAGE_CACHE_EXPIRE_TIME = 3600;
/** * global constant */
public static final long MESSAGE_CACHE_TIME = 3600;
/**
* 局部常量
*/
private static final String ERROR_MESSAGE = " error message";
/** * member variable */
private int currentUserId;
/** * console print {@codeMessage} Message * *@paramMessage Body, local constant */
public void sayHello(final String message){
System.out.println("Hello world!"); }}Copy the code
Constants generally have their own business meaning, and don’t be afraid to omit or abbreviate them over time. For example, a representation of the expiration time of the user’s message cache would be clearer and for you to judge.
General naming rules
- Try not to use pinyin; Avoid mixing pinyin and English. For some general expressions or difficult to describe in English pinyin can be used, once adopted pinyin must not be mixed with English. Example: BeiJing, HangZhou Example: validateCanShu
- Do not use special characters in the naming process, except constants.
- Do not use the same name as an existing class in the JDK or framework, and do not use Java keywords.
- Prepositions such as for(can be replaced by homophone 4), to(can be replaced by homophone 2), from, with, of, etc. For example, the class name is UserService4MySqlDAO, and the method name is getUserInfoFromRedis and convertJson2Map.
Code comments
6.1 Principles of annotations
Good naming makes code readable, and code naming is often strictly restricted. Unlike annotations, programmers are often free to do whatever they want, but that doesn’t mean they can do whatever they want. Elegant annotations usually meet three elements.
- Nothing is strange unannotated code is very unfriendly to the reader, even if the code is written clean, the reader will be at least psychologically resistant, and there is often a lot of complex logic in the code, so be sure to write annotations, not only to record the logic of the code, but also to clarify the logic of the change.
- From a code maintenance perspective, comments in code must be the best of the best. Reasonable and clear naming makes code easy to understand. Code with simple logic and naming conventions that clearly express what the code does does not need annotations. Overuse of annotations adds extra burden, not to mention that most of them are nonsense.
// Get information by id
getMessageById(id)
Copy the code
- 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. It is common to modify code without modifying annotations.
6.2 Annotation Format
Annotations can be broadly divided into two types, javadoc annotations and simple annotations. Javadoc annotations can be generated to provide effective support for external users through the JavaAPI. Javadoc annotations are automatically generated when using development tools such as IDEA or Eclipse. Custom annotation templates are also supported, requiring only the interpretation of corresponding fields. Students involved in the same project should try to set up the same annotation template.
6.2.1 note after class
In Javadoc annotations, each class must have an annotation.
/** * Copyright (C), 2019-2020, Jann balabala... * * class introduction: this is a used to do what the class, which functions, using the technology..... * *@authorClass creator names remain aligned *@dateKeep the creation date aligned *@versionKeep the version numbers aligned */
Copy the code
6.2.2 Attribute Annotations
Each attribute must be preceded by an attribute comment, usually in one of two forms, whichever you like, but be consistent throughout the project.
/** Prompt message */
private String userName;
/** * Password */
private String password;
Copy the code
6.2.3 Method notes
Each method must be preceded by a method comment that describes each parameter in the method, as well as the return value.
/** ** * /** * * *@paramNote whether the XXX parameter 1 is null *@returnA description of the results returned, and what results will be returned in different cases *@throwsThe exception type specifies how an exception is thrown from such a method
Copy the code
6.2.4 Constructor comments
Each constructor must be preceded by a comment. The comment template looks like this:
/** ** /** * /**@paramNote whether the XXX parameter 1 is null *@throwsThe exception type specifies how an exception is thrown from such a method
Copy the code
While simple annotations often require engineer byte definitions, there are a few things to note when using annotations:
-
Each attribute value of an enumerated class is annotated. Enumerations can be thought of as constants, usually unchanged, and often referred to in multiple places. Modifying and adding attributes to an enumeration often has a big impact.
-
Keep typography clean and don’t use end-of-line comments. Double slashes and asterisks are separated by 1 space.
int id = 1;Counterexample: Do not use end-of-line comments // Counterexample: there is no indentation between a line break and a comment int age = 18; // Name String name; /** ** 123 * 2333333 */ Copy the code
References:
Code Efficient
www.cnblogs.com/wangcp-2014…
Qiita.com/KeithYokoma…
Google. Making. IO/styleguide /…
If you are a beginner/intermediate Java developer who is extremely self-taught, follow me on my public account Cruder and make progress together