Java Learning Path: 10 Common code violations in Java

Source: Internet
Author: User

Recently, I did a code cleanup for the Java project. After cleansing, I found that a common set of code violations (that is, code that does not represent code errors) repeats itself in the code. Therefore, I summarize these common code violations into a list and share them with you to help Java enthusiasts improve the quality and maintainability of their codes.

This list is not based on any rules or order, all of which are checked out through the code quality tools including Checkstyle,findbugs and PMD. Look together:

First, the Eclipse compiler provides source code format input

Eclipse provides automatic source formatting options and organizes input (removing unused code). You can use these shortcut keys to do this.

Ctrl + Shift + F-source code format

Ctrl + Shift + o-- organization input and delete unused code

Instead of calling these two functions manually, you can save the file at any time, depending on the Eclipse auto-format and auto-organize options.

Operation Steps, in Eclipse, enter the save actions, Editor, Java, Window, Preferences, and save in the selected way, and finally check the Format Source code + Organize imports.

Second, avoid multiple returns (exit points)

According to your method, make sure there is only one exit point. Do not use returns in the same place or in multiple places. For example, the following code, notRECOMMENDED, is not recommended because there are multiple exit points (return statements).

 
   
  
  1. Private Boolean iseligible (int age) {
  2. if ( age > ) {
  3. return true;
  4. }else{
  5. return false;
  6. }
  7. }

The following code has been improved, which is later version.

 
   
  
  1. Private Boolean iseligible (int age) {
  2. Boolean result;
  3. if ( age > ) {
  4. result = true;
  5. }else{
  6. result = false;
  7. }
  8. return result;
  9. }

Iii. simplification of If-else

I wrote a few useful methods for reference, checking the statement condition and returning the value based on that condition. For example, consider the Iseligible method, as you have seen before:

 
   
  
  1. Private Boolean iseligible (int age) {
  2. Boolean result;
  3. if ( age > ) {
  4. result = true;
  5. }else{
  6. result = false;
  7. }
  8. return result;
  9. }

The entire method is rewritten with a single return statement:

 
   
  
  1. Private Boolean iseligible (int age) {
  2. return Age >  18;
  3. }

Iv. do not create a new instance of Boolean, Integer, or string

Avoid creating new instances for boolean,integer,string. For example, using the new Boolean (true), boolean,valueof (true). The modified statement is basically the same as the previous effect, except for improved performance.

V. Using BRACES module statements

Never forget to use braces module statements such as if, for, and while. The advantage of this is that when you modify a module-level statement, you reduce the blurring of the code and avoid the opportunity to introduce bugs.

Not recommended:

 
   
  
  1. if ( age > )
  2. result = true;
  3. Else
  4. result = false;

Suggestions:

 
   
  
  1. if ( age > ) {
  2. result = true;
  3. }else{
  4. result = false;
  5. }

Vi. marking method parameters in final type, applicable at all times

Keep in mind that the method parameters are marked with the final type and are applicable at all times. The advantage of this is that when you accidentally modify a parameter value, the compiler warns you, and it also optimizes compiler code bytes in a better way.

Suggestions:

 
   
  
  1. Private Boolean iseligible (final int age) {...}

Vii. name public static final field in uppercase

The public static final field is named in uppercase (often referred to as a constant). This allows you to easily distinguish between a constant field and a local variable.

Not recommended:

 
   
  
  1. Public static Final String Testaccountno  =  "12345678" ; 

Suggestions:

 
   
  
  1. Public static Final String Test_account_no  =  "12345678" ;, 

Eight, combined into a single if statement

In as many cases as possible, combine multiple if statements into a single if statement, such as the following code:

 
   
  
  1. if ( age > ) {
  2. if ( voted = = False) {
  3. Eligible to vote.
  4. }
  5. }

Merge into a single if statement:

 
   
  
  1. if ( age > &&!voted) {
  2. Eligible to vote
  3. }

Nine, switch should have default

Always add default to the switch statement.

X. Use constants to avoid repeating the same string values

If you must use strings in multiple places, use constants to avoid repeating a string that has the same value.

For example, look at the following code:

 
   
  
  1. private void SomeMethod () {
  2. Logger.log ("My application" + E);
  3. ....
  4. ....
  5. Logger.log ("My application" + f);
  6. }

string literal "My app" can be a constant and can be used in code.

 
   
  
  1. public static final string  span class= "attribute" >my_app  =  "my  Application " ;  
  2.  
  3. private  void somemethod () { 
  4.   logger.log (my_app + e);  
  5.    ...  
  6.   ....  
  7.   logger.log (my_app + f);  

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.