Android coding specifications | code style guide

Source: Internet
Author: User

I. Exceptions

1. Do not ignore Exception Handling

If the following code is used to empty the exception after catch, it will make people feel the same as planting mines:

Incorrect practice:

 
 
  1. void setServerPort(String value) {   
  2.     try {   
  3.         serverPort = Integer.parseInt(value);   
  4.     } catch (NumberFormatException e) {   
  5.     }   
  6. }   

Correct practice (1 ):

When an exception is thrown during method declaration, the client programmer is responsible for digesting the exception.

 
 
  1. void setServerPort(String value) throws NumberFormatException {   
  2.     serverPort = Integer.parseInt(value);   
  3. }   

Correct practice (2 ):

 
 
  1. /** Set port. If value is not a valid number, 80 is substituted. */   
  2. void setServerPort(String value) {   
  3.     try {   
  4.         serverPort = Integer.parseInt(value);   
  5.     } catch (NumberFormatException e) {   
  6.         serverPort = 80;  // default port for server   
  7.     }   

Correct practice (3 ):

 
 
  1. /** Set port. If value is not a valid number, die. */   
  2. void setServerPort(String value) {   
  3.     try {   
  4.         serverPort = Integer.parseInt(value);   
  5.     } catch (NumberFormatException e) {   
  6.         throw new RuntimeException("port " + value " is invalid, ", e);   
  7.     }   

Correct practice (4 ):

 
 
  1. void setServerPort(String value) throws ConfigurationException {   
  2.     try {   
  3.         serverPort = Integer.parseInt(value);   
  4.     } catch (NumberFormatException e) {   
  5.         throw new ConfigurationException("Port " + value + " is not valid.");   
  6.     }   
  7. }   

2. Do not be lazy and catch General Exceptions

The code below will catch exception exceptions. It is wrong to get the exception size. This will make it difficult for you to locate the cause when an error occurs. Generally, exceptions cannot be handled in a unified way.

Incorrect practice:

 
 
  1. try {   
  2.     someComplicatedIOFunction();        // may throw IOException   
  3.     someComplicatedParsingFunction();   // may throw ParsingException   
  4.     someComplicatedSecurityFunction();  // may throw SecurityException   
  5.     // phew, made it all the way   
  6. } catch (Exception e) {               // I'll just catch all exceptions   
  7.     handleError();                      // with one generic handler!   
  8. }   

Ii. Notes/javadoc

1. Copyright Notice on top
2. Package and import block (each block is separated by blank lines)
3. Class or interface declaration. In javadoc annotations, describes the usage of classes or interfaces.

 
 
  1. /*  
  2.  * Copyright (C) 2007 The Android Open Source Project  
  3.  *  
  4.  * Licensed under the Apache License, Version 2.0 (the "License");  
  5.  * you may not use this file except in compliance with the License.  
  6.  * You may obtain a copy of the License at  
  7.  *  
  8.  *      http://www.apache.org/licenses/LICENSE-2.0  
  9.  *  
  10.  * Unless required by applicable law or agreed to in writing, software  
  11.  * distributed under the License is distributed on an "AS IS" BASIS,  
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  13.  * See the License for the specific language governing permissions and  
  14.  * limitations under the License.  
  15.  */   
  16. package com.android.internal.foo;   
  17. import android.os.Blah;   
  18. import android.view.Yada;   
  19. import java.sql.ResultSet;   
  20. import java.sql.SQLException;   
  21. /**  
  22.  * Does X and Y and provides an abstraction for Z.  
  23.  */   
  24. public class Foo {   
  25.     ...   
  26. }   

Class/interface comments (1 requirement)
The document notes for classes and interfaces contain the following information:
1. Purpose. Before using a class/interface, developers need to know the purpose of using this class/interface.
2. How to use it. Developers need to know how this class/interface should be used. If necessary, they need to indicate that this class/interface should not be used.
How to use it.
3. Development and maintenance logs. A maintenance record for this class/interface: time, author, abstract.

Content of method comments (Requirements for items 1, 5, 6, and 7)
1. Class what this method does.
2. How the method works.
3. Code modification history.
4. Demo method call code.
5. What parameters must be passed in to this method. @ Param
6. Exception Handling. @ Throws
7. What does this method return. @ Return

3. advantages and disadvantages of using wildcards in imports 4. Local variables should be declared and initialized before use 5. Field naming

* Non-public, non-static field names start with M.
* The static domain name starts with "S.
* Other fields start with lowercase letters.
* All public static final fields (constants) are in uppercase and connected with underscores.

 
 
  1. public class MyClass {   
  2.     public static final int SOME_CONSTANT = 42;   
  3.     public int publicField;   
  4.     private static MyClass sSingleton;   
  5.     int mPackagePrivate;   
  6.     private int mPrivate;   
  7.     protected int mProtected;   
  8. }   
6. curly braces do not have a single line. They share the same line with the code above. 7. Naming rules

1. lower case.

Com. chinacache. Billing
Com. chinacache. Billing. Node

2. It is composed of uppercase and lowercase letters.

Class raster;
Class imagesprite;

3. The interface is composed of uppercase and lowercase letters, and the first letter is uppercase. It often ends with "able" and "visible.

Interface rasterdelegate;
Interface runna ble;
Interface accessible;

4. The method is composed of uppercase and lowercase letters. The first letter of the first word is lowercase, And the last letter is uppercase.

Run ();
Runfast ();
Getbackground ();

5. the variables and parameters are in lower case. Underlines are not recommended.

Char C;
Int I;
Float m yw idth;

6. Set and array should reflect the meaning of the plural in the name, for example, adding the suffix s or prefix some.

MERs MERS;
Postedmessages;
Some MERs MERS;
Some items;

8. When defining a class, the attributes and methods should be arranged according to the access permissions.

1. Public
2. Protected
3. Package level (if there is no access modifier, the default value is default)
4. Private

 

After writing the code, check against the code specification.

(1) eclipse code formatting
You can import files under development/IDE/eclipse so that eclipse follows the android code style rules. Select "window › preferences › Java › code style, use" formatter › import ", import android-formatting.xml," organize imports › import "to import Android. importorder.


(2) set the eclipse tab to four spaces:
Preferences-> General-> editors-> text editors:
Insert spaces for tabs

(3) automatically format the code Ctrl + Shift + F

(4) Globally search and replace Ctrl + F

 

[Reference]

Http://source.android.com/source/code-style.html

Http://wenku.baidu.com/view/ce17addd5022aaea998f0fad

Related Article

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.