Java naming convention (very complete), collected!

Introduction

In this article, we will summarize the naming conventions in Java programming from large to small, from outside to inside. This article will involve common naming examples in daily work, such as package naming, class naming, interface naming, method naming, variable naming, constant class naming, abstract class naming, exception class naming, and extended class naming. I will introduce it in the order of packages, classes (interfaces, abstract classes, exception classes), methods, variables and constants according to the project directory structure.

1. Package naming convention

The function of a package is to group and manage classes or interfaces with similar or related functions to facilitate the location and search of classes. At the same time, packages can also be used to avoid class name conflicts and access control, making the code easier to maintain. Usually, packages are named using lowercase English letters and separated by “.”. Each divided unit can only contain one noun. Generally, package naming often uses the top-level domain name as the prefix, such as com, net, org, edu, gov, cn, io, etc., followed by the company/organization/individual name and the function module name. Here are some package naming examples:

package org.springframework.boot.autoconfigure.cloud
package org.springframework.boot.util
package org.hibernate.action
package org.hibernate.cfg
package com.alibaba.druid
package com.alibaba.druid.filter
package com.alibaba.nacos.client.config
package com.ramostear.blog.web

Here are some common package naming examples for Oracle Java:

package java.beans
packagejava.io
packagejava.lang
packagejava.net
packagejava.util
package javax.annotation

2. Class naming convention

Classes are usually named with nouns, and the first letter of each noun should be capitalized. If a class name contains more than two nouns, it is recommended to use the Camel-Case method to write the class name, and the first letter of each noun should also be capitalized. Generally, class names should be written as simple and descriptive as possible, so it is not recommended to use abbreviations when writing class names (except for some conventional naming, such as Internationalization and Localization abbreviated to i18n, Uniform Resource Identifier abbreviated to URI, Data Access Object is abbreviated as DAO, JSON Web Token is abbreviated as JWT, HyperText Markup Language is abbreviated as HTML, etc.). The following are some common class naming examples:

public class UserDTO{
    //TODO...
}
class EmployeeService{
    //TODO...
}
class StudentDAO{
    //TODO...
}
class OrderItemEntity{
    //TODO...
}
public class UserServiceImpl{
    //TODO...
}
public class OrderItemController{
    //TODO...
}

Here are some standard naming examples in Oracle Java:

public class HTMLEditorKit{
    //...
}
public abstract class HttpContext{
    //...
}
public interface ImageObserver{
    //...
}
public class ArrayIndexOutOfBoundsException{
    //...
}
public class enum Thread.State{
    //...
}

2.1 Interface naming convention

First of all, an interface (Interface) is a special class that expresses the actions of a certain type of object; simply put, an interface is also a class (not too rigorous), so the name of the interface should also be written in accordance with the class name writing standards, and the first letter should be Capital letters. Different from ordinary class names, adjectives or verbs are usually used when naming interfaces to describe the action behavior of the interface. The following are examples of adjective naming for some standard library interfaces in Oracle Java:

public interface Closeable{
    //...
}
public interface Cloneable{
    //...
}
public interface Runnable{
    //...
}
public interface Comparable<T>{
    //...
}
public interface CompletionService<V>{
    //...
}
public interface Iterable<T>{
    //...
}
public interface EventListener{
    //...
}

In the Spring Framework standard library, interfaces are usually named using a combination of noun + verb/adjective. The following are some examples of interface naming in Spring Framework:

public interface AfterAdvice{
    //...
}
public interface TargetClassAware{
    //...
}
public interface ApplicationContextAware{
    //...
}
public interface MessageSourceResolvable{
    //...
}

2.2 Abstract class naming convention

Abstract Class is a special class whose naming is equivalent to the naming convention of ordinary classes. Generally, in order to distinguish abstract classes from ordinary classes and interfaces and improve the readability of abstract classes, when naming abstract classes, “Abstract”/”Base” will be used as the prefix of the class name. Here are some common naming examples in programming:

public abstract class AbstractRepository<T>{
    //...
}
public abstract class AbstractController{
    //...
}
public abstract class BaseDao<T,ID>{
    //...
}
public abstract class AbstractCommonService<T>{
    //...
}

The following are common examples of abstract classes in Spring Framework:

public abstract class AbstractAspectJAdvice{
    //...
}
public abstract class AbstractSingletonProxyFactoryBean{
    //...
}
public abstract class AbstractBeanFactoryPointcutAdvisor{
    //...
}
public abstract class AbstractCachingConfiguration{
    //...
}
public abstract class AbstractContextLoaderInitializer{
    //...
}

2.3 Exception class naming convention

Exception Class is also a type of class, but unlike ordinary class naming, exception classes need to use “Exception” as their suffix when naming. The following are common exception class naming examples:

public class FileNotFoundException{
    //...
}
public class UserAlreadyExistException{
    //...
}
public class TransactionException{
    //...
}
public class ClassNotFoundException{
    //...
}
public class IllegalArgumentException{
    //...
}
public class IndexOutOfBoundsException{
    //...
}

In addition, there is another type of exception class in Java, which belongs to system exceptions. The name of this type of exception class uses “Error” as its suffix to distinguish Exception (coding, environment, operation, etc. exceptions). The following is an example of naming system exceptions (unchecked exceptions):

public abstract class VirtualMachineError{
    //...
}
public class StackOverflowError{
    //...
}
public class OutOfMemoryError{
    //...
}
public class IllegalAccessError{
    //...
}
public class NoClassDefFoundError{
    //...
}
public class NoSuchFieldError{
    //...
}
public class NoSuchMethodError{
    //...
}

3. Method naming convention

When naming a method, its first letter should be lowercase. If the method signature consists of multiple words, use camel case to write it starting from the second word. Generally, when naming methods, a combination of verb/verb + noun is usually used. Here are some common examples of method naming.

3.1 Representation acquisition

If a method is used to obtain a value, it is usually prefixed with “get”, for example:

public String getUserName(){
    //...
}
public List<Integer> getUserIds(){
    //...
}
public User getOne(){
    //...
}

3.2 Expression query

If a method needs to obtain certain data through query or filtering, “find”/”query” is usually used as its prefix, for example:

public List<User> findOne(Integer id){
    //...
}
public List<Integer> findAll(){
    //...
}
public List<String> queryOrders(){
    //...
}

3.3 Expression conditions

If a method requires some conditional parameters, you can use characters such as “by”/”with” as connectors for the conditions in the method name, for example:

public User findByUsername(String username){
    //...
}
public List<Integer> getUserIdsWithState(boolean state){
    //...
}
public List<User> findAllByUsernameOrderByIdDesc(String username){
    //...
}

3.4 Presentation settings

If a method is to set, insert, modify, delete, etc., the corresponding verb (set, insert, update, delete) should be used as the prefix of its noun, for example:

public void setName(String name){
    //...
}
public User insert(User user){
    //...
}
public void update(User user){
    //...
}
public void clearAll(){
    //...
}

3.5 Other specifications

If a method is used to obtain the length or quantity of a certain set of data, the method should be named with length or size; if the return value of the method is Boolean, the method should be prefixed with “is” or “has” ; If the method is used to convert one type of data to another data type, you can use “to” as a prefix. Here’s a comprehensive example:

public long length(){
    //...
}
public int size(){
    //...
}
public boolean isOpen(){
    //...
}
public boolean isNotEmpty(){
    //...
}
public boolean hasLength(){
    //...
}
public Set<Integer> mapToSet(Map map){
    //...
}
public UserDto convertTo(User user){
    //...
}
public String toString(Object obj){
    //...
}

4. Variable naming convention

Variable naming includes parameter names, member variables and local variables. Variable names usually start with a lowercase letter. If the variable name consists of multiple words, the first letter from the second word needs to be capitalized. During the variable naming process, it is not recommended to use “_” as a prefix or a separator between words. . Here are some common variable naming examples:

private String nickName;
private String mobileNumber;
private Long id;
private String username;
private Long orderId;
private Long orderItemId;

5. Constant naming convention

Generally, constant names are written in all uppercase English words. If the constant name consists of multiple words, “_” is used to separate the words. The following is an example of constant naming:

public static final String LOGIN_USER_SESSION_KEY = "current_login_user";
public static final int MAX_AGE_VALUE = 120;
public static final int DEFAULT_PAGE_NO = 1;
public static final long MAX_PAGE_SIZE = 1000;
public static final boolean HAS_LICENSE = false;
public static final boolean IS_CHECKED = false;

6. Enumeration naming convention

The enumeration (Enum) class is a special class. Its naming convention follows the naming constraints of ordinary classes. The first letter is capitalized and the camel case naming method is used. The names of the values defined in the enumeration class follow the naming convention of constants, and the enumeration The name of the enumeration value needs to have a certain correlation with the class name. Here are some examples of enumerations:

public enum Color{
    RED,YELLOW,BLUE,GREEN,WHITE;
}
public enum PhysicalSize{
    TINY, SMALL, MEDIUM, LARGE, HUGE, GIGANTIC;
}

Here is an example from the Oracle Java standard library:

public enum ElementType{
    TYPE,
    FIELD,
    METHOD,
    PARAMETER,
    CONSTRUCTOR,
    LOCAL_VARIABLE,
    ANNOTATION_TYPE,
    PACKAGE,
    TYPE_PARAMETER,
    TYPE_USE;
}

7. Other naming conventions

7.1 Array

When defining an array, for ease of reading, try to maintain the following writing conventions:

int[] array = new int[10];
int[] idArray ={1,2,3,4,5};
String[] nameArray = {"First","Yellow","Big"}

public List<String> getNameById(Integer[] ids){
    //...
}
//or
public List<String> getNameById(Integer...ids){
    //...
}

7.2 Expressing plural numbers or sets

If a variable is used to describe multiple data, try to write it in the plural form of the word, for example:

Collection<Order> orders;
int[] values;
List<Item> items;

In addition, if a Map data is expressed, “map” should be used as its suffix, for example:

Map<String,User> userMap;
Map<String,List<Object>> listMap;

7.3 Generic classes

When writing generic classes, the following conventions are usually made:

  • E stands for Element, usually used in collections;

  • ID is a unique identifier type used to represent an object

  • T stands for Type, usually referring to a class;

  • K represents Key, usually used in Map;

  • V represents Value, which is usually used in Map and appears paired with K;

  • N represents Number, usually used to represent numerical types;

  • ? Represents an undefined Java type;

  • X is used to indicate exceptions;

  • U and S represent any type.

The following is an example of writing a generic class:

public class HashSet<E> extends AbstractSet<E>{
    //...
}
public class HashMap<K,V> extends AbstractMap<K,V>{
    //...
}
public class ThreadLocal<T>{
    //...
}
public interface Functor<T,X extends Throwable>{
    T val() throws X;
}
public class Container<K,V>{
    private K key;
    private V value;
    Container(K key,V value){
        this.key = key;
        this.value = value;
    }
    //getter and setter ...
}

public interface BaseRepository<T,ID>{
    T findById(ID id);

    void update(T t);

    List<T> findByIds(ID...ids);
}

public static <T> List<T> methodName(Class<T> clz){
    List<T> dataList = getByClz(clz);
    return dataList;
}

7.4 Interface implementation class

For ease of reading, under normal circumstances, it is recommended that interface implementation classes use “Impl as a suffix”, and it is not recommended to use a capital “I” as an interface prefix. The following is an example of writing an interface and an interface implementation class.

Recommended writing method:

public interface OrderService{
    //...
}
public class OrderServiceImpl implements OrderService{
    //...
}

Not recommended way of writing:

public interface IOrderService{
    //...
}
public class OrderService implements IOrderService{
    //...
}

7.5 Test classes and test methods

In the project, the test class is written using the test business module name/tested interface/tested class + “Test” method. The test function in the test class is written using the combination of “test” + use case operation_status. For example:

public class UserServiceTest{

    public void testFindByUsernameAndPassword(){
        //...
    }

    public void testUsernameExist_notExist(){
        //...
    }

    public void testDeleteById_isOk(){
        //...
    }
}

8 Extension: Shorthand for various O in Java development

Finally, use a table and diagram to quickly analyze BO, DTO, DAO, PO, POJO and VO are sorted out.

Name Scope of use Explanation
BO Used for naming service, manager, business and other business-related classes Business Object business processing object, its main function is to encapsulate business logic into an object.
DTO The internal properties of the processed PO object may increase or decrease Data Transfer Object, Mainly used for remote calls and other places where a large amount of data needs to be transmitted. For example, some or all attributes of one or more PO classes can be encapsulated as DTO for transmission
DAO
DAO Name the class used to read and write the database Data Access Object, which is mainly used to encapsulate access to the database. POJO can be persisted into PO through DAO. PO can also be used to encapsulate VO and DTO
PO Name of Bean, Entity and other classes Persistant Object persistent object , the mapping status of data in the database table in the Java object can be simply understood as a PO object is a record in the database table
POJO POJO is the collective name for DO/DTO/BO/VO Plain Ordinary Java Object. It is a simple ordinary Java object. It is forbidden to name the class XxxxPOJO
VO Usually a data object passed between the view control layer and the template engine Value Object, mainly used for view layers and view controllers Encapsulate the properties required by the view layer into an object, and then use a VO object to transfer data between the view controller and the view.
AO Application layer object Application Object, an abstract reuse object model between the Web layer and the Service layer, Rarely used.

The following is a diagram to understand the mutual conversion relationship between the above types of O:

Picture

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java Skill TreeHomepageOverview 138,179 people are learning the system