Coding standard, JAVA programmers have to pay attention!

01 existing normative sense

Application coding standards is particularly important for the software itself and software development staff, there are several reasons :

  1. Good coding standards can minimize the cost of maintaining software, and hardly any software throughout its life cycle, originally developed by the staff to maintain;
  2. Good coding standards can improve the readability of the software, which allows developers to thoroughly understand the new code as soon as possible;
  3. Good coding standards can maximize the efficiency of the progress of team development cooperation;
  4. Long-term normative coding also allows developers to develop good coding habits, exercise and even a more critical thinking;

02 naming conventions

1. General concept

  • Try to use a full English descriptor
  • Suitable for use in the relevant art, the term
  • Mixed case to make names readable
  • Minimize the use of abbreviations, but if used, must meet the same definition throughout the project
  • Avoid using long names (less than 15 letters of the normal selection)
  • Avoid using a similar name, or just different names case
  • Avoid using the underscore (in addition to the static constant, etc.)

2. Identifier Type Description

(1) package (Package) named

Package name should use a full English descriptor is composed of a lowercase words. And the prefix the package name is always a top-level domain, usually com, edu, gov, mil, net, org and so on;

Such as: com.yjhmily.test

(2) class (Class) named

A class name should be a noun, in mixed case with the first letter of each word capitalized. Try to ensure that the class name is simple and full description.

Use whole words, avoid abbreviations (unless the abbreviation within the same project specification or the acronym is more widely used, like URL, HTML)

Such as: FileDescription

(3) Interface (Inte named CE) of

Substantially similar to the Class naming conventions. On the basis of the above meet Classd naming rules to ensure the beginning of the first letter "I", easy to open and ordinary Class distinction. It now takes the name of the class name of the interface to the end of the second letter, and satisfies the class name naming convention;

Such as: IMenuEngine

(4) enumeration (Enum) named

Substantially similar to the Class naming conventions. On the basis of the above meet Classd naming rules to ensure the beginning of the first letter "E", easy to open and ordinary Class distinction.

Such as: EUserRole

(5) naming exception (Exception) of

Exception (Exception) commonly used letter e indicates an abnormal, for custom exception class suffix must Exception

Such as: BusinessException

(6) The method (Method) named

Method name is a verb, mixed case, and the first letter of the first word lowercase, followed by the first letter of the word capitalized.

Method names describe the action as much as possible the behavior of the method. Return type is a Boolean value from the beginning to the general method "is" or "has"

Such as:

getCurrentUser() 
addUser()
hasAuthority()
复制代码

(7) parameters (Param) named

The first letter of the first word lowercase, followed by the first letter of the word capitalized. Project Name parameter does not agree to start with an underscore, or dollar sign, although it is grammatically promised. Parameter name should be short and full description.

如:public UserContext getLoginUser(String loginName);

(8) the constant field (the Constants) named

Constant static fields (static final) used in all capital letters, words separated by an underscore;

Such as:

public static final Long FEEDBACK;
public static Long USER_STATUS;
复制代码

03 Notes Specification

A good rule of thumb about comments may follow are:

Ask yourself, if you have never seen this code, to effectively understand the code within a reasonable period of time, what you need some information? ? ?

1. General concept

  1. Comments should increase the clarity of the code
  2. Keep it simple comment
  3. Before writing code or write comments at the same time
  4. Comment out Why do some things, and not just what has been done

2. Which of the comment

  • Java files : You must specify the copyright information as well as creation time and author of the document;
  • Class : Class of purpose, that is, the class functions performed, and the time and the name of the class is created; more than once when editing or modify the same class, the name should appear in more than name of the author;
  • Interface : the basis of meeting the class comments above, the interface comments should include the purpose of setting the interface, how it should be used and how it is not being used. Corresponding comments in the interface implementation class clear condition may not add comments;
  • Methods Notes : For the set (Set method) method (Get method) and a member of the acquisition, in the case of a member variable has been described, can not add comments; ordinary members of the method requires the instructions to complete what function, what is the meaning of the parameters and return values What; creation time another method must be clearly annotated provide valuable clues for future maintenance and reading;
  • Note internal method : control structures, and the code does why, processing procedure and the like, particularly complex logic processing section, to give a specific comment as possible;
  • Parameters : Parameter Meaning, and any constraints or conditions other conditions;
  • Attribute : Field Description;
  • Topical (intermediate) variables : Note without the case of no particular significance;

3. Notes format

The project follows the provisions of the same comment format, under normal circumstances will file formats codetemplates.xml guide into IDE (Eclipse) Eclipse or use the default;

Code 04 format specification

Follow the same predetermined code format engineering, general code format using direct IDE (Eclipse) comes default code format;

05 other specifications

JSP file

Illustrated by a full English description JSP completed features, including a vivid verbs as far as possible, the first letter lowercase,

Such as: viewMessage.jsp, editUser.jsp and so on.

06 project-specific naming convention

1. Persistence

  • Hibernate mapping file and the entity and the database table name corresponding to exactly;
    such as: Advertisement.hbm.xml, Advertisement.java

  • Data Access DAO
    DAO interface and implementation class name must exactly match the naming rules normal interfaces and implementation classes, and finally to "DAO" end of the data access method in the DAO must abstract sufficiently describe the basic CRUD database manipulation;
    such as: ICrossAdDAO (Interface), CrossAdDAO (implementation class)

  • HQL profile of various database manipulation
    principle HQL file number and the number of services equal System Services layer, and a service name file named HQL;
    such as: resource.hbm.xml

2. Service Layer

(1) service interface and implementation

Service interface and implementation class must fully comply with the normal naming interfaces and implementation classes; engineering services defined named body, and the same with "Serv" ending
, such as: IResourceServ (Service Interface), ResourceServ (interface class)

(2) service interface method

Method name is a verb, mixed case, and the first letter of the first word lowercase, followed by the first letter of the word capitalized.
Method names describe the action as much as possible the behavior of the method.

  • Return type is a Boolean value: with "is" or "has" to begin with
  • A Data obtained: get + Noun + data describing the data type;
  • All data obtained: get + All + Noun + data describing the data type;
  • Obtained by XXX / a Data Query: get / query + + Data Description Data Type Noun + By + conditions;
  • Add a Data: save / add + noun description data ()
  • A data update: save / update + noun description data;
  • Delete some data: delete / remove + data describing noun;

(3) Business Objects

Business name + BO

(4) query parameter object

Those who continue Abst *** QuerySpec query parameter class meet all the following rules:

  • Query + noun describing data to be queried + Spec
  • As a parameter passed in the parameter name must be: the description of the data to be queried noun + Spec

Such as: QueryProgramSpec

3. MVC layer

(1) Action control layer

  • Action class name: Action + Name function module;
  • Actoin method names describe the page as much as possible to migrate to

Such as: LoginAction (log in action), toWelcome (steering action method welcome page)

(2) resource file

  • System global resource file: globalMessages_ + + .properties character encoding type
  • Function inside the module resource files: package.properties

4. Spring configuration file

(1) Action configuration file

  • File directory: WebRoot/WEB-INF/spring/action/Function module name+_ApplicationContext.xml

(2) Services configuration file

  • File Directory: WebRoot/WEB-INF/spring/services/Services_ApplicationContext.xml

(3) global profile

  • File directory: WebRoot/WEB-INF/spring/project name+_ApplicationContext.xml

(4) JSP file

Using a full English description of functions performed by the JSP, including a vivid as possible verb, first letter lowercase,
such as: viewMessage.jsp, editUser.jsp like.

07 Application Named summary

All files, variables represent the same word in English. Try to avoid abbreviations and acronyms.

1. java class

According java java class using standardized mark hump, capitalized java class, the class name in the first letter of each word capitalized.

Things a Java class represents the real world, like the best term is a noun. The best use of the name of reality. Such as employees with Employee, rather than Employ avoid ambiguity. Better not use abbreviations such as empl.

  • Software applications are often layered, the class name of each layer of the belt layer as much as possible suffix.
  • Recommended entity class has no suffix.
  • Data layer using SQLMapper suffix.
  • Param query parameters for the data layer
  • Service layer uses Service
  • Use of the Web Packager
  • Web form layer forms suffix Form

Such as employee module, respectively, the Employee (entity), EmployeeSQLMapper (data layer), the EmployeeService (service layer), EmployeePackager (web layer)

Common English name (it is best to organize a common vocabulary dictionary)

  • Employees: employee
  • Section: department

2. field

According java hump labeling nomenclature, java field to start with a lowercase first letter of each word capitalized (except for the first word).

Field indicates the reality of things in a property name in the class, with the best terms. Field name should be the most accurate word, as far as possible the use of a word. The class name is not necessary to hang in front of the field, such as the employee id field, id can be used directly, without using employeeId, if there are two fields may be ambiguous, you can increase the descriptive words to distinguish.

Fields named best watch word meaning knowledge.

3. Methods

The method shows a behavior, it represents an action, preferably a verb or verb phrase, or the first word of a verb.

Property methods, get / the beginning of the set, followed by the field names, field names capitalized.

Data layer method can only insert (insert), delete (delete), update (update), select (to find), the beginning of the count (statistics), the other layers to this method avoids the beginning of five words, so as to avoid misunderstandings.

Services layer method, according to the method of naming the behavior, meaning the method of description only and not the purpose of the method name. Such as adding new users of the system, the user can register the front desk, the administrator can also add background, the method can be reused, so it is best not to use use the register, the use of add would be better to write. The method avoids using web layer relevant.

Web layer method is preferably close to the web language, such as register, login, logout and other methods.

4. Variable

A variable is an important element method, a fitting name, make the code elegance of times (about exaggeration). Variable names first letter lowercase.

The variable part of the name, to avoid using the use of other parts of speech.

The use of the name to represent the significance in the method. If the employee list:

List employees is preferable to use or not to use the employeeList List list, or even worse in List l, if applied List employees and Map employees use and employeeMap employeeList respectively.

Custom type variable name itself can be used, the first letter to lowercase.

5. Xml file name

Xml naming method similar to the class name, first letter capitalized hump marked.

Ibatas mapping file: namespace name for the module name of the entity class, capitalized, typealias use of such *** name. sql resultMap names and first letter lowercase naming the rules, the method name and method name of the data layer.

Form and FormItem file names with only the first letter capitalized hump marked. Form also uses the name capitalized format. Form item names used in the form the form class property name. Using labeled hump (preferably without using the partition _)

Action file name using the first letter capitalized, file package and field action name all the letters in lower case format.

6. URL name

url path the same name in lowercase (All letters are lowercase), submitted by the get method parameter name and url path names as lowercase.

(1) J2EE specification

the J2EE specification

J2EE (Java 2 Platform, Enterprise Edition) is a development of distributed enterprise applications company SUN specification defined. It provides a multi-tiered distributed application model and develop a series of technical specifications. Multi-level distributed application model refers to a functional application logic into a plurality of levels, each level corresponding server and support components, assembly operation (e.g., running on Servlet Servlet container assembly in a distributed server component container, EJB components, run on the EJB container), communication between the container through the relevant protocols to achieve mutual calls between components. Compliance with this specification developers will be widely supported by the industry, the development of enterprise applications becomes simple and fast.

the J2EE component level

J2EE components and levels shown in Figure 1-1.

Figure 1-1 J2EE component level (slightly)

. ① J2EE specification defines the following components :

A. client component
B. Web Component
C. EJB components

②. J2EE specification defines the following four levels .

A. The client tier (Client Tier)

Used to implement the client layer and the display layer manipulation interface enterprise application systems. Further, some client program may implement the business logic. It can be divided into Web-based and non-Web-based client in both cases. Based on the case of the Web browser as the main corporate Web server. Non-Web-based client layer is a separate application that can complete the thin client can not complete the task.

B. Web layer

Providing Web services. Including enterprise information dissemination. Web by the Web layer components. J2EE Web components include JSP pages and Servlets. Web layer may also include some JavaBeans. Web layer is mainly used to process client requests, call the appropriate logic blocks, and the results returned to the client in the form of dynamic pages.

C. business layer (Business Tier)

Also called the business layer EJB layer or the application layer, which consists of EJB servers and EJB components. Under normal circumstances many developers to integrate Web server and EJB server products together release, called the application server. EJB tier business logic used to implement enterprise-wide information systems. This is the core enterprise applications, is handled by the EJB run in the business layer. A Bean data received from a client, processing, and sending the data stored enterprise information system. Similarly, a Bean can retrieve data from the enterprise information system, sent to the client program. The business layer EJB should run in a container, the container solve the underlying topic, such as transaction processing, lifecycle state management, multithreading security governance, resource pools.

D. enterprise information system (Enterprise Information System tier)

Processing enterprise system software, including enterprise infrastructure systems, database systems, and other legacy systems. J2EE connector architecture to support future versions (Connector Architecture). It is connected to the J2EE platform and enterprise information system layer standard API.
Web service layer and layer together form the middle layer of the three-tier J2EE applications, the other two client layer and the storage layer or enterprise information system.

E. J2EE application distribution technology

In order to achieve enterprise-class distributed applications, J2EE defines the wealth of technical standards, development tools and API to meet these standards to provide support for the development of enterprise applications. These technologies cover database access, distributed communications, security and so on. To provide multi-faceted support for distributed applications.

a. Component Technology

The core idea is based on the J2EE application components / container. Each component provides methods, properties, events interfaces. Components may be developed by languages. Components can be reused, shared and distributed.

b. Servlets and JSP

Servlets for natural or receive user requests dynamic page generates a corresponding manipulation (call EJB). JSP based on the text. Servlets generated by the respective containers, and that the content displayed separately. In J2EE provides Servlet API, for creating Servlets.

c. EJB technology

EJB specification provides a method of developing and deploying server-side components. Each EJB is logically divided according to function, the system does not have to focus on the development of the underlying details of the subject, focus only on the specific transaction analysis. After the EJB development is completed, according to specifications deployed in the EJB container, complete the corresponding transaction function. EJB support distributed computing. Truly reflects the enterprise-class applications.

d. Database Access

Whether it is traditional enterprise information systems in the future of enterprise information systems, databases plays an important role. Development of distributed systems require database access has good flexibility and scalability. JDBC (JavaDatabase Connectivity) is a development interface independent of specific database management systems. It provides a common mechanism for accessing SQL databases and storage structures, a common underlying functionality supports basic SQL application programming interface. It provides a unified user interface on a different database interface. It offers a wide variety of database connection. J2EE JDBC API provides a variety of database manipulation so simple and feasible.

e. Distributed Communication Technology

Distributed communication technology is the core technology of distributed enterprise systems. J2EE framework provides a variety of communication modes for Web applications and EJB applications.

In order to run another target machine to call the object on a machine, the J2EE achieve the following communication :

  • RMI the Java (Remote Method, the Invoke): Remote Method Invocation. Java RMI remote communication between Java objects. Server name with a registrar to a remote object and tied together, the client looking up remote objects from the server registered by name, download the remote object after finding a local agent, method calls the remote object.
  • IDL the Java (the Java Inte *** ce Defilation Language): Interface Definition Language. Java objects can be achieved remote object communication in line with the CORBA specification.
  • The JNDI (the Java Naming and Directory Inte *** ce): the Java Naming and Directory Interface. JNDI provides a standard interface to access remote object named as a distributed system. EJB home interface objects, data sources, messaging server and so can register with the form JDNI tree to the name server, call them to find the object interface remote object with the specified name in the JNDI name server by JDNI in line with the program.
  • JMS (the Java the Message Service): the Java Message Service. It defines a set of specifications for the development of messaging middleware applications. Java clients and Java middle layer access messaging system simple interface to achieve as long as JMS-defined, complex applications can be achieved without having to focus on low-level technical details.

08 JAVA programming specification

1. Application

This specification is applied to the project using J2EE specification, all the items in the JAVA code (including JSP, SERVLET, JAVABEAN, EJB) shall comply with the specification. At the same time, also be used as reference to other items.

2. Design classes and methods

(1) create a class has a strong cohesive force

The importance of methods are often more easily understand the importance of class than the method refers to a section of code to perform the same function. Class is often considered to be wrong merely a container for storing methods. Some developers even the staff made this idea further play, put all their methods in a single class.

① J2EE technology architecture is a completely different from traditional application development, it contains many components, primarily to simplify and standardize application development and deployment, and further progress portability, security and reuse value.

② J2EE four-story model

  • Running on the client machine at the client layer assembly
  • Web-tier components run on the J2EE server
  • Running on J2EE server business logic components
  • Server running on the EIS Enterprise Information System (Enterprise information system) layer software

09 J2EE application components

J2EE application is composed of components as .J2EE is an independent software functional units are assembled into a J2EE application through the relevant classes and files, and interaction with other components

J2EE specification defines the following J2EE components :

  • Applications and applets client is the client component.
  • Java Servlet and JavaServer Pages (JSP) is a web layer assembly.
  • Enterprise JavaBeans (EJB) business layer components.

1. The client tier components

J2EE applications can be web-based methods, it can also be based on the traditional way.

2. web layer assembly

J2EE web tier components can be JSP pages or Servlets. According to the J2EE specification, static HTML pages and Applets not a web tier components. Positive client layer as shown below, web layer may contain JavaBean objects to process user input, and the output operation to the enterprise bean embarked on the service layer to be processed.

3. Business-tier components

Business logic level code to meet specific fields of business banking, retail, banking, etc., processed by the business enterprise bean running layer. The chart below shows how an enterprise bean receives data from the client program, the processing (if necessary) and sent to the EIS tier storage, this process may be reverse. There are three enterprise-class bean:. Session (session) beans, entity (entity) beans, and message-driven (message-driven) beans session bean represents a temporary program to interact with the client when the client program after the implementation of the session bean. and related data will disappear. Instead, an entity bean represents a permanent record of the database table row. when a client or server to suspend program closed, there will be lurking service assurance entity bean's data can be preserved. message-driven bean combines characteristics session bean and JMS message listener, promised a business layer component of an asynchronous receive JMS messages.

4. enterprise information system

Enterprise Information System layer processing enterprise information system software includes enterprise infrastructure systems such as enterprise resource planning (ERP), mainframe transaction processing, database systems, and other legacy information systems. For example, J2EE application components might need access to corporate information for the database connection system 3, J2EE platform, application programming interfaces (APIs) and protocol consists of a set of services (services), it provides the ability to support the development of Web-based multi-tier application, the following technical specifications of the 13 kinds of simple J2EE description

5. JDBC(Java Database Connectivity)

The JDBC API provides access to a different database in the same way, the same as ODBC, JDBC developer shield some details of the subject, in addition, JDCB also have access to the database platform independence. JNDI (Java Name and Directory Inte *** ce)

JNDI API is used to perform name and directory services. It provides a consistent model to access and manipulate enterprise-level resources, such as DNS and LDAP, local file system, or application server object.

6. EJB(Enterprise JavaBean)

One of the reasons why J2EE technology has won widespread media attention is the EJB. They provide a framework to develop and implement distributed business logic, thereby simplifying the development clearly scalable and highly complex enterprise applications. EJB specification defines how to interact with the EJB components thereof when the container. Container is responsible for providing public services, such as directory services, transaction management, security, resource pools, and fault tolerance. But it is worth noting here is that the only way to EJB is not the J2EE. It is because of the openness of J2EE, so some companies can and EJB in a way parallel to achieve the same purpose. RMI (Remote Method Invoke)

As its name implies, the RMI remote object method call protocol. It uses serialization data transfer between the client and the server. RMI is a lower level protocol to be used EJB.

7. Java IDL / CORBA

In the Java IDL's support, development staff can be integrated with Java and CORBA. They can create Java objects and can be deployed in the CORBA ORB, or they can also create Java classes and as customers start with the ORB and other CORBA objects. The latter method provides another way by which Java can be used to your new applications and legacy systems integration. JSP (Java Server Pages)

JSP page from the HTML code and Java code embedded therein formed. Server for processing these Java code after the page is requested by the client, then the natural HTML page back to the client's browser.

8. Java Servlet

Servlet is a small Java program that extends the functionality of the Web server. As real applications A server started when requested, which is very similar to CGI Perl scripts. Most of the functions provided Servlet and JSP similar, but different ways of. JSP is usually the majority of HTML code embedded a small amount of Java code, all written in Java servlets and natural HTML.

9. XML(Extensible Markup Language)

XML is a language used to define other markup languages. It is used to share data in a different business processes.

XML development and Java are independent of each other, however, and it has the same goal is the Java level

Neutrality. By a combination of Java and XML, you can get a perfectly flat has
Solution of neutrality.

10. JMS(Java Message Service)

And MS is a message-oriented middleware application program interface communicate with each other (API). It supports point to point field, there is support for publish / subscribe (publish / subscribe) type of domain, and provides support for the following types: approved messaging, transactional message delivery, consistency of messages and subscribers have persistent those who support. JMS also provides another way to integrate your application with the old back-end systems.

11. JTA(Java Transaction Architecture)

JTA defines a standard API, an application system whereby access to various transaction monitoring.

12. JTS(Java Transaction Service):

JTS is the basic CORBA OTS transaction monitoring of realization. JTS specifies the implementation of the Transaction Manager. The Transaction Manager is a high-level support for Java Transaction API (JTA) specification, and implements OMG OTS specification of Java image in the deeper in. JTS Transaction Manager as the application server, the Explorer, a standalone application and communication resource management provides transaction services.

13. JavaMail

JavaMail API is used to access the mail server, which provides an abstract class mail server. Not only supports SMTP servers also support IMAP server.

14. JAF(JavaBeans Activation Framework)

JavaMail JAF to handle e-mail attachments using MIME encoding. MIME byte stream can be converted into a Java object, or convert from a Java object. Most applications can not need to use JAF.



Guess you like

Origin juejin.im/post/5d3813eae51d454d565358b3