How to write efficient Java code

Source: Internet
Author: User
Tags coding standards naming convention checkstyle

Code Quality Overview

how to tell if a project code is well written or bad? Where is the distinction between good code and corrupt code? How to write your own code is beautiful and vitality? The following is a rough introduction to the problem of code quality. Also ask a friend who has experience in code quality to make valuable comments.

code quality involves 5 aspects, coding standards, code duplication, code coverage, dependency analysis, and complexity analysis. These 5 aspects are a big part of the process of determining the quality of a code. Let's take a look at each of these 5 areas:

Coding Standards: it must be clear that almost every company has a code code, such as class naming, package naming, code style, and other things belong to it.

code duplication: As the name implies is duplicated code, if your code has a lot of duplicate code, you need to consider whether to extract the duplicate code, encapsulated into a common method or component.

Code Coverage: test the code ratio that the code can run to, has your code been unit tested? Is every method tested and what is the code coverage? This is related to the functionality and stability of your code.

Dependency Analysis: What about your code dependencies? What about coupling relationships? Is there a cyclic dependency? Does it conform to the principle of cohesion poly-low coupling? One or two can be distinguished by dependency analysis.

Complexity Analysis: Previously written programs nested 10 layers If else do you believe it? It is difficult to read because of the high complexity of the circle. This code can be pulled out through complexity analysis, and the better the code, the easier it is to read.

The above explains the code quality related 5 aspects, in the actual development environment, there are many tools for us to solve the above 5 issues, the following 5 Eclipse plug-ins for these 5 issues are very good support:

encoding standard: CheckStyle plugin URL: http://eclipse-cs.sourceforge.net/update/

code duplication: PMD's CPD plugin url:http://pmd.sourceforge.net/eclipse/

Code Coverage: Eclemma plug-in url:http://update.eclemma.org

Dependency Analysis: JDepend plug-in url:http://andrei.gmxhome.de/eclipse/

Complexity Analysis: Eclipse Metric plugin url:http://metrics.sourceforge.net/update

Note: Some plugins require scientific Internet access to update

Coding Standards (use of Checkstyle)

after installing the Checkstyle plugin on Eclipse, let's build a class to run with it. This class is very simple, a common user entity, contains the ID, user name, password, mail and other attributes, and contains the Get set method, a standard Pojo. Run Checkstyle check:

one of our usual ordinary but a class, was checkstyle to make so many problems, the sentiment why, we come to see what is the situation?

Take a look at these warning messages:

Line 1, , said missing Package-info.java file.

Line 2, , saying that the first sentence should be "." End.

Line 30, , the Java Doc Comment is missing.

Line 35, , GetID is not an inherited method and must be specified abstract,final or empty. There is also a lack of Java doc annotations.

This class basically on these four kinds of problems, the lack of package-info.java files, what is this file to do? He is used to describe the class of package annotations, there is a certain particularity, want to know more about Baidu please. If you don't have a big impact on your project, you can ignore it. How to configure Checkstyle we'll talk about this later. The first sentence of the comment is to "." At the end, this depends on your habits, you're sure you need this, you keep it, you don't have to ignore it. Without Java doc, annotations are necessary for the properties of Java classes, so this is to be preserved. Instead of inheriting the method, you need to add the final keyword, and if you have this habit, keep it, and ignore it instead.

We just set up a simplest class to check with Checkstyle, and as your class code gets more and more complex, the Checkstyle can check out more and more. Common Checkstyle errors have these:

1.Type is missing a Javadoc commentclass 
Missing type description 
2. "{" Should is on the previous line 
' {' should be on the previous line 
3.Methods is missing a Javadoc comment 
Missing Javadoc comment in front of method 
4.Expected @throws tag for "Exception" 
Note that you want to have @throws in the comments 
5. "." is preceeded with whitespace "." 
There must be no spaces in front 
6. "." is followed by whitespace "." 
There must be no space behind. 
7. "=" is not a preceeded with whitespace 
Missing space in front of "=" 
8. "=" is not a followed with whitespace 
Missing space after ' = ' 
9. "}" should be on the same line 
'} ' should be on the same line as the next statement 
10.Unused @param tag for "Unused" 
No parameter "unused", no comment required 
11.Variable "CA" Missing Javadoc 
Variable "CA" missing Javadoc comment 
12.Line longer than 80characters 
Line length more than 80 
13.Line contains a tab character 
Line contains "tab" character 
14.Redundant "public" modifier 
Redundant "public" modifier 
15.Final modifier out of order with the JSL 
Suggestionfinal modifier in order error 
16.Avoid using the ". *" Form of import 
Import format avoids using ". *" 
17.Redundant import from the same package 
Import content from the same package 
18.Unused import-java.util.list 
Import Java.util.list is not in use 
19.Duplicate Import to Line 13 
Duplicate Import Same content 
20.Import from Illegal package 
Import content from an illegal package 
"While" construct must use "{}" 
"While" statement is missing "{}" 
22.Variable "STest1" must be private and has accessor method 
The variable "STest1" should be private, and there is a way to call it 
23.Variable "ABC" must match pattern "^[a-z][a-za-z0-9]*$" 
Variable "ABC" does not conform to the naming convention "^[a-z][a-za-z0-9]*$" 
"(" is followed by whitespace 
"(" Cannot have spaces after 
")" is proceeded by whitespace 
")" must not be preceded by a space

It can be seen that checkstyle check out the problem, mostly coding rules and style problems, which is the most basic to write high-quality code. It should be noted that we will be some excellent open source code with Checkstyle to check also will check out a lot of problems, this can not say that these open source is not good, but each company organization has its own coding standards, this degree will reduce the workload of the programmer and can make the code readability qualified, But this degree is not the same as the complete standard of Checkstyle. So we generally use the Checkstyle to not use his default standards, but through the configuration, to develop appropriate coding rules.

Custom Checkstyle Rules:

Open the Checkstyle configuration, create a new configuration, and select the external configuration file. It is best to export an eclipse-brought Checkstyle configuration file (sun_ Checks.xml), and then renamed as an external configuration guide, the purpose of this is to modify the corresponding configuration after import, to achieve the purpose of the custom configuration (since the eclipse comes with a configuration that is locked and cannot be modified). After importing, click "Configure" on the right to edit.

remove the hint of missing Package-info.java file first

and then the first sentence of the comment to "." At the end of this rule, double-click "Style Javadoc" to remove the "checkfirstsentence" Check in the window.

for the entity class, the property has a comment, the Get Set method does not need to comment, double-click "Method Javadoc" to check allowmissingpropertyjavadoc.

"GetID is not an inherited method, you must specify abstract,final or NULL," If you are lazy to add "final" to the method, this rule can also be removed.

If you do not want each parameter to be "final", you also need to remove the final rule of the parameter:

There is also an error "' ID ' hides a field." Because the parameters of the method and the domain name defined in the class are the same, but the Get set method generated using eclipse will do so, so you can ignore this.

We then use Checkstyle to check an article, and found that only the attribute is missing comment this warning.

With the Java Doc comment for each attribute, all issues are cleared. And so on, the solution to the Checkstyle problem is: 1, according to the rules to solve the code problem, 2, if you feel this problem has little impact on the quality of your project, you can ignore it.

code duplication (use of PMD for CPD)

for multi-person development projects, it is difficult to avoid the problem of duplicate code, although we try to encapsulate the common code, but as the demand increases, personnel technology differences, lack of communication, and other reasons, duplication of code will be more and more. This not only seriously affects the quality of the code, but also virtually increases the amount of code.

Note: Streamlined programs and high-reusability code are the goals we have been pursuing.

PMD's CPD tools are designed to check for duplicate code. Right-click the project--->PMD---->find Suspect Cut and Paste to perform a duplicate code check:

Check out the duplicate code that you can double-click to view. Then, according to the business logic and code characteristics, decide whether to do encapsulation, how to encapsulate.

code Coverage (use of Eclemma)

a quality-qualified code that includes not only the function itself but also the corresponding test code, the Eclemma plug-in can be used to measure the functionality and stability of the code by measuring the ratio of the test code to the overall code.

after using Junit to write the test case, right-click coverage as--->junit test and run the test case, Eclemma will count the relevant code coverage:

based on this result, you can see that the test cases you write cover the code without overwriting the code, which can be a blind spot in code quality.

Dependency Analysis (use of jdepend)

with the increase of the business logic of the program, the dependency of code becomes more and more complex, and the Jdepend plug-in can count the dependencies of packages and classes, and analyze the stability, abstraction and the existence of cyclic dependencies. Right-click Package--->run JDepend analysis:

Take a look at these indicators:

CC (number of Classes)

The number of specific and abstract classes (and interfaces) of the package being analyzed to measure the scalability of the package. If you implement other classes in a class, such as implementing a listener class, the number of listener classes is also recorded here.

AC (Abstract classes)

the number of abstract classes and interfaces.

Ca (afferent couplings)

The number of other package that relies on the package being analyzed is used to measure pacakge's responsibilities. That is, how many packages have called it.

Ce (efferent couplings)

The number of other package that the class of the package being analyzed depends on to measure the package's independence. That is, how many other packages it calls.

A (abstractness)

The abstract classes and interfaces in the package are analyzed in proportion to the number of classes in the package, with a value range of 0-1.

I (instability)

i=ce/(CE+CA), which measures the instability of the package, has a value range of 0-1. I=0 is the most stable, and i=1 represents the most unstable. That is, if the class does not call any other packages, it is the most stable.

D (Distance)

the vertical distance between the a+i=1 of the package and the ideal curve is used to measure the package's balance between stability and abstraction. The ideal package is either purely abstract class and stable (X=0,y=1), or is completely concrete and unstable (x=1,y=0). the range of values for 0-1,d=0 represents a complete fit for the ideal standard, and d=1 indicates that the package has been most deviated from the ideal standard. that is, your package is either full of interfaces, does not call any other packages (completely abstract class and stable), or is a concrete class, not called by any other package.

Cycle

the number of cyclic dependencies.

One of these reports allows us to design and refactor the code accordingly.

complexity Analysis (use of metrics)

for people who read code, the simpler the code is, the better it is to understand and maintain, and if your code reads hard or you don't understand it after a while, you have to figure out how to solve the complexity of the code. The Metrics plugin can help you do this.

first, in the Java perspective, right-click a project---->properties, select Metrics, tick enble Metrics.

then window--->show view---->other---->metrics View

Open the Metrics view and click the Run icon in the top right corner to get the results of the complexity analysis:

you can optimize your program according to the complexity index.

Summary

This article describes 5 aspects related to Java code quality and describes the usage and role of the corresponding Eclipse plug-in. In our actual development, as far as possible according to their own company and team situation to develop some inspection rules, to improve the quality of code. And in most cases, there will be two inspection links, namely, local inspection and continuous integration environment inspection, our common Hudson can integrate many plugins.

References:

Pursuing code quality: Code quality for software architectures
http://www.ibm.com/developerworks/cn/java/j-cq04256/ 
JDepend
http://www.clarkware.com/software/JDepend.html 
PMD 
http://pmd.sourceforge.net/ 
CheckStyle 
http://sourceforge.net/projects/eclipse-cs/?source=directory 
Eclemma 
http://www.eclemma.org/ 
Metrics 
http://metrics.codahale.com/

How to write efficient Java code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.