The development specification of Android Development notes

Source: Internet
Author: User
Tags comments lowercase mixed home screen
Preface

Come to a new company, write code before, I usually find the leader to develop norms. However, many companies do not have any development specifications, or the development of specifications is really very simple, only to modify the annotation format description, this ... Now this company, I've been here for two years, did not see what development specifications, in my strong request, the company's leadership to give a functional mobile phone development era of C + + development norms, I said to Android Java Development Specification, the leadership is very not happy, on the internet to find a development specification document sent to me, Also said that everyone is not just developed, should know how to write code, ... In fact, my intention is to set up the company's own development norms, to be honest, this development specification is not just to meet my requirements, should be the company's own research and development quality and system of self requirements, I actually basically do not need any development specification documents, because I write code is still relatively normative, but the level of the company's leadership is really not good , think I'm just a trouble maker. Well, I was wrong ... So that someone asked me later, we write code what exquisite no, I thought about it, back a sentence, you want to write how to write, no one will look at your code, there is no one to answer you. This is a bit of a shame, but that's the truth ....

All right, let's not do it, we're going to tidy up an Android development code for ourselves, and that's what we'll use later. Purpose

This document is mainly: The style of unified code, improve the readability of code, easy code maintenance and porting. Unified Code Agreement, facilitate research and development engineer collaboration, improve productivity improve software quality, reduce code errors, strengthen code tracking and management of Android development specifications

We organize this development specification in the order in which the Android code is developed: Code modification notes:

Any changes we make to the code require the use of modified annotations to facilitate code tracking and management: Java files:

Start of Code modification Comment:

add-xxx (modifier name)-xxxx (feature description)-xxxx (modified date 20150101)-start

End of Code modification Comment:

add-xxx (modifier name)-xxxx (feature description)-xxxx (modified date 20150101)-end
XML file:

Start of Code modification Comment:

<!--add-xxx (modifier name)-xxxx (feature description)-xxxx (modified date 20150101)-start-->

End of Code modification Comment:

<!--add-xxx (modifier name)-xxxx (feature description)-xxxx (modified date 20150101)-end-->
file Comments

In Java or XML file switches, we typically give the file a note of a file, mainly including the copyright statement, filename, version information, date and author, and so on.
Java File Comments:

 * * Copyright (C) 2016 XXX (company name) Inc. 
 * All Rights Reserved.
 * File Name:
 * Function:
 * Version: *
 Date: */
 

XML file Comments:

<!--*
 * Copyright (C) 2016 XXX (company name) Inc. 
 * All Rights Reserved.
 * File Name:
 * Function:
 * Version:
 * Date:
 *
 *-->
Naming Conventions

The naming conventions are basically in line with the existing Java and Android source styles for easy code reading and code understanding.

Name Type Basic Specification Example
Package (Packages) A unique package name is always prefixed with all lowercase ascii letters and is a top-level domain name, usually COM, the second parameter is the company name, and the third parameter is a functional module, such as: [Domain inversion]. [Project name]. [Module name]. [Child module name] ..., such as package com.android.contacts; Com.xxx.helloworld (XXX is abbreviation for company name)
Class (Classes) Class names are mixed in uppercase and lowercase, with the first letter of each word capitalized. Class names should be specific, readable, and fully express the meaning of the class. Use complete words to avoid abbreviations (unless the acronym is more widely used, like url,html). Inheriting from the system component class naming, the suffix must clearly indicate the class of the system component, and the Activity class suffix uses the service,broadcasereceiver suffix using the Activity,service class suffix to use the receiver. ContentProvider Use Provider Class Usbmanager,class Activitymanager,class speechrecorderactivity, class Accountservice
Interface (interfaces) Similar to the class name, only the first plus I to represent the interface Interface Iactivitymanager
Method (Methods) Method name is a verb + object, in a mixed case, the first letter lowercase, then the first letter of the word in uppercase, what it does to name, rather than how it is named Finishactivity (), GetID ()
Variable (Variables) Variable name, including classes, class constants, are mixed in case, the first letter lowercase, followed by the first letter of the word uppercase. Variable names should be short, complete, and clearly articulate the meaning of the variable. The choice of variable names should be easy to remember, that is, can point to its use. Try to avoid the variable name of a single character unless it is a one-time temporary variable. Temporary variables are usually named I,j,k,m and N, and they are generally used for integers; c,d,e, which are generally used for character types. Non-public, non-static field names begin with M. The static field name begins with S. Other fields begin with lowercase letters int i,j,k; Context Mcontext; Packagemanager mPm; Button mOk; Uri moriginatinguri;private Static MyClass Ssingleton
Constants (Constants) The declaration of a class constant is all uppercase and the words are separated by an underscore public static final int start_voice_hidden_session =-10;
Package and Introduction

In the Java file, after the file annotation is the package and the introduction,

Package is primarily a path to the package, which is defined by the development definition, such as a package for Android:

Package com.android.contacts;
Package Com.android.server.usb;

We can customize package:

Package com. Xxx.helloword

XXX is the company's English name.

Classes in the same package should be declared together when they are imported, and invalid unused references are deleted:

Import Sample:

Import Android.content.Context;
annotations for classes and interfaces

Standard NOTES:

 description of the/** * class or interface
 * @see related class or interface
 * *

However, if the class is simpler, we can also describe the function of this class or interface directly in a single sentence

For example, the annotation of the Usbalsamanager class:

/**
 * Usbalsamanager manages USB audio and MIDI devices.
 */
Method

The specification requirements of the method are more:
(1) The name of the method should clearly describe the function of the method, suggesting that the verb + object (e.g. GetID)
(2) The responsibility of the method is unitary, the function is clear (is to accord with single duty principle)
(3) The length of the method is appropriate, not too long, not too short, it is best to embody the principle of interface isolation, the interface as much as possible granular
(4) The method of the number and order of parameters to be appropriate, the number of parameters not too much, the order of the parameters must have a certain order, such as in accordance with the order of In–modify–out
(5) The annotation of the method should be reasonable and easy to read.
(6) The layout and style of the method should be consistent
(7) Methods try not to use the mysterious number
(8) The method should conform to the Dimitri Law, try not to use other variables that are not parameters, reduce the coupling of the method, improve the cohesion of the method, and facilitate the transplant
(9) The method should have the corresponding exception, the wrong means, improve the robustness of the method.

Like what:

/** * Method describes the
 method in
 detail
 * @param parameters, Description *
 @param parameters, description
 * @return return value, description *
 @throws anomaly, description
 * @see phase Off Method
 * * Public
boolean functionname (int param_0,boolean param_1) {
    Boolean result = false;
    ...........;
    return result;
}

Of course, many times, the method is simple and straightforward, there is no need to annotate the method, we can not add comments, we can add only a simple description of the method of comments. Like what:

/**
 * Show the overflow items from the associated menu.
 * @return True if the menu is able to is shown, false otherwise
/public boolean showoverflowmenu () {
    ret Urn Mmenuview!= null && mmenuview.showoverflowmenu ();
}
class member variables and constant annotations

Member Variable annotation:

/**
 * Member Variable description
 *
/private String test;

/** member Variable description *
/private int hello;

Buttons to indicate user acceptance
private Button mOk;

Constant annotations:

Dialog identifiers used in ShowDialog
private static final int dlg_base = 0;
declaration and initialization of variablesWhen declaring a variable, initialize the variable at the location near the first use of the variable, declare and define it near the first use of the variable, and initialize the parentheses

Curly braces do not occupy a single row, and should be followed by the previous line. Like what:

public class Nullobject extends Abstractobject {
    ...
    .. public void Doaction () {
        ...
    }}
If, If-else, if else-if else statement
if (condition) {
    statements;
}

if (condition) {
    statements01;}
else {
    statements02;
}

if (condition) {
    statements01;}
else if (condition) {
    statements02;}
else{
    statements03;
}

The IF statement should note: Handle the normal code path first, and then handle the abnormal situation to put the most common situation on the front of the normal situation after the IF, put the do not put to the else behind if you follow a meaningful statement to use Boolean method calls to simplify complex conditions detect switch statements

Switch (condition) {case
    case1:
        statements01;
        break;
    Case CASE2:
        statements02;
        break;
    Case CASE3:
        statements3;
        break;
    Default:
        statements;
        break;

Switch statement Note: Put the normal situation in front by the execution frequency to arrange the case clause after each of the cases add a break loop

For statement:

for (initialization; condition update) {
    statements;
}

While statement:

while (condition) {
    Statements
}

Do-while statement:

do {
    statements;
} while (condition);

Loop to note: Keep the logic of the loop simple and easy to read to minimize the internal work done within the loop as much as possible. Put the busiest loop in the inner layer you can use a sentinel value to control whether or not to exit the Loop Try-catch statement

try {
    statements
} catch (Exceptionclass e) {
    statements;
}

try {
    statements
} catch (Exceptionclass e) {
    statements;
} finally {
    statements;
}

Try-catch Statement Note: When catch, be sure to print out the exception, never allow catch is empty, do nothing. For example, the following code is prohibited.

try {
    statements
} catch (Exceptionclass e) {
    //Do nothing
}

try {
    statements;
} catch (Exceptionclass e) {
    //Nothing to do
} finally {
    statements;
}
do not use magic numbers

The Magic value refers to the number that appears directly in the code.
Like what:

    public void Magicfunction () {
        int i = 1000;
    }

We don't know what it means to have this 100 coming from there. The correct way to use it is:

public static final int number_light = 1000;
    public void Magicfunction () {
        int i = number_light;
    }

This can improve the readability of the code, on the other hand, can also change the local localization, so as to improve maintainability. Layout naming

The name of the layout file, we use all the words lowercase, the words are divided between the following lines, as far as possible use of nouns or noun groups, that is, the use of module name _ function name to be named. Like what:

Contact_tile_list_frequent.xml
Contact_editor_activity.xml
name Group_browse_list_item.xml resource ID

The ID name used in the layout must be in all words lowercase, the words are separated by an underscore, as far as possible using nouns or noun groups, can directly understand the current component by ID to achieve the function.
Button android:id= "@+id/cancel_button"
ImageButton android:id= "@+id/open_details_button"
TextView android:id= "@+id/suggestion_for_contacts_number" Strings.xml in the name of ID

Names must be separated by an underscore in all the words, and a noun or noun group as much as possible, for example:

<string name= "Menu_create_contact_shortcut" >place on home screen</string> <string
"Name=" Picker_title ">choose photo</string>
Picture Resource naming

The name of the picture under the drawable directory must be in all the words lowercase, the words are divided between the underlined, as far as possible use the noun or noun group, that is, use the module name _ use to name. If it is a public resource, such as a split line, it is named directly by purpose. Like what:

Group_icon_1.png
Btn_star_on_normal_holo_light.png
Use of controls

Take the button as an example:
To define a control in a layout file:

<button
    android:id= "@+id/cancel_button"
    android:layout_width= "wrap_content"
    android:layout_ height= "Wrap_content"
    android:text= "@string/quickcontact_suggestion_cancel_button"/>

Use in Java file:

Private Button Mcancelbutton;

mcancelbutton= (Button) Findviewbyid (R.id.cancel_button);

Mcancelbutton.setonclicklistener (New Onclicklistener () {
    @Override public
    void OnClick (view view) {
        ......
    }
});
Log Information

Log information is the performance of the system has an impact, the proposed server code, the development of our debug log information to delete all. public methods and Interfaces

Some are public methods or interfaces that are suggested to be placed in a newly created file, such as (Util.java,help.java), or in a public file in the system itself, and are defined as publicly static forms that are convenient for reuse. reference materials:

1.Android Development Specification
http://blog.csdn.net/huangyabin001/article/details/30095775
2. Code Encyclopedia 2

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.