Android Development Code Specification

Source: Internet
Author: User
Tags coding standards comment tag

Directory

  • 1. Naming principles
  • 2. Naming the basic specification
  • 2.1 Programming Basic Naming conventions
  • 2.2 Classification Naming conventions
  • 3. Classification naming conventions
  • 3.1 Basic data type naming conventions
  • 3.2 Control Naming conventions
  • 3.3 Variable Naming conventions
  • 3.4 Catalog Normalization for the entire project
  • 3.4 Res resource file naming specification
  • 4. Code Writing Specification
  • 5. Notes
  • 6. Improve code Quality
  • 7. Design mode (Patterns)

1. Naming principles
In object-oriented programming, it is very tricky to name classes, objects, methods, variables, and so on. For example, case sensitivity, using different letters to start, and so on. However, the pursuit of its source, in the name of a resource, should be based on the description and uniqueness of the two characteristics to name, in order to ensure that there is no conflict between the resources, and each one is easy to remember.

For understanding the logical flow of applications, naming schemes are the most influential kind of help. The name should describe "what" rather than "how". The naming principle is: Make the name long enough for a certain meaning, and short enough to avoid lengthy. The unique name is programmed only to separate the areas. The following points are the canonical naming methods.

2. Naming the basic specification

2.1 Programming Basic naming Conventions
(1) Avoid hard-to-understand names such as attribute name xxK8, which can cause ambiguity.
(2) In an object-oriented language, it is superfluous to include the class name in the name of the class attribute, such as book.booktitle, but should use Book.title.
(3) in languages where function overloading is allowed, all overloads should perform similar functions.

(4) Use a verb-noun method to name a routine that performs a specific action on a given object, such as Calculateinvoicetotal (). (a routine is a collection of functionality interfaces or services provided externally by a system)

(5) If appropriate, add the qualifier (AVG, Sum, Min, Max, Index) at the end or beginning of the variable name.
(6) Use complementary pairs in variable names, such as Min/max, Begin/end, and Open/close.

(7) The Boolean variable name should contain is, which means yes/no or true/false values, such as Fileisfound.

(8) Use meaningful names even for variables that may appear to be short-lived in only a few lines of code. Use single-letter variable names for short-loop indexes only, such as I or J.

(9) To help differentiate variables and routines, use Pascal casing (calculateinvoicetotal) for the routine name, where the first letter of each word is capitalized. For variable names, use camel casing (documentformattype), where the first letter of each word is capitalized except for the first word.

(10) Instead of using literal numbers or literal strings, use named constants, Num_days_in_week, for maintenance and understanding.

2.2 Classification Naming conventions

(1) Name of package

The Java package name is made up of lowercase words. However, due to the Java object-oriented programming feature, each Java programmer can write their own Java package, in order to guarantee the uniqueness of each Java package naming, in the latest Java programming specification, the programmer is required to add a unique prefix to the name of the package they define. Because domain names on the Internet are not duplicated, programmers generally use their own domain name on the Internet as the only prefix for their packages.

Example: Com.pccb.app

(2) Naming of classes

The name of the class must start with a capital letter and the other letters in the word are lowercase, and if the class name consists of multiple words, the first letter of each word should be capitalized such as Testpage, and if the class name contains a word abbreviation, each letter of the word should be capitalized, such as: Xmlexample, One more naming technique is that because a class is designed to represent an object, you should choose a noun when you name the class.

For example: Circle

(3) Naming of methods

The first word of the name of the method should begin with a lowercase letter, and the following words begin with a capital letter.

Example: Sendmessge

(4) Naming of constants

The names of the constants should all use uppercase letters and indicate the full meaning of the constant. If a constant name consists of multiple words, you should use underscores to split the words.

Example: Max_value

(5) Naming of parameters

The naming conventions for parameters are the same as the naming conventions for methods, and to avoid confusion when reading a program, make the name of the parameter as clear as possible if the parameter name is a single word.

Private attribute: private int mAge;

Static variable: static String sName;

function internal variable: int _age;

The formal parameter when the method is defined: int pAge;

(6) Javadoc notes

In addition to the common annotations that Java can use, the Java language Specification defines a special kind of comment, which is what we call the Javadoc annotation, which is used to record the API in our code. Javadoc comments are a multiline comment that begins with/** and ends with a comment that can contain some HTML tags and specific keywords. The advantage of using the Javadoc annotation is that comments written can be automatically converted to online documents, eliminating the hassle of writing program documents separately.

For example:

/**

* This is an example of

* Javadoc

*

* @author Darchon

* @version 0.1, 10/11/2002

*/

At the beginning of each program, generally use Javadoc annotation to the overall description of the program and copyright information, and then in the main program for each class, interface, method, field to add Javadoc comments, the beginning of each note in a sentence to summarize the class, interface, methods, fields completed functions, This sentence should occupy a single line to highlight its general role, in the following sentence can follow a more detailed description of the paragraph. After a descriptive paragraph, you can also follow some special paragraphs that start with the Javadoc comment tag, such as the @auther and @version in the example above, which appear in the generated document in a specific way.

Although adding comments to a poorly designed program does not make it a good program, writing programs according to programming specifications and adding good annotations to your programs can help you write programs that are perfectly designed, run efficiently, and are easy to understand, especially if the programming specification becomes more important when multiple people work together to complete the same project. As the saying goes, "Ax", it's good to spend a little time adapting to the Java programming specification.

3. Classification naming conventions

3.1 Basic data type naming conventions

integer:int+ Description char:chr+ Description boolean:bln+ Description

long:lng+ Description Short:shr + description double:dbl+ Description

string:str+ Description float:flt+ Description single:sng+ Description

datatime:dt+ Description array:arr+ Description object:obj+ Description

such as: String srtname;

3.2 Control Naming conventions

textview:txt_+ description

button:btn_+ description

imagebutton:imgbtn_+ description

imageview:imgview_+ description

checkbox:chk_+ description

radiobutton:rdobtn_+ description

analogclock:anaclk_+ description

digitalclock:dgtclk_+ description

datepicker:dtpk_+ description

TIMEPICKER:TMPK _+ Description

togglebutton:tglbtn_+ description

edittext:edttxt_+ description

progressbar:lcb_+ description

Seekbar:skbar _+ Description

autocompletetextview:autotxt_+ description

multiautocompletetextview:mlautotxt_+ description

zoomcontrols:zmctrl_+ description

include:ind_+ description

videoview:vdovi_+ description

webview:webvi_+ description

ratingbar:ratbar_+ description

tab:tab__+ description

spinner:spn_+ description

chronometer:cmt_+ description

scrollview:sclvi_+ description

textswitcher:txtswt_+ description

gallery:gal_+ description

imageswitcher:imgswt_+ description

gridview:gv_+ description

listview:lvi_+ description

expandablelist:epdlt_+ description

mapview:mapvi_+ description

The control description is as follows:

TextView-Text display controls

button-button controls

ImageButton-Picture Button control

ImageView-Picture display controls

checkbox-check box control

RadioButton-Radio box control

AnalogClock-Clocks (the kind with the dial) controls

DigitalClock-Electronic Watch controls

DatePicker-Date selection control

Timepicker-Time selection control

ToggleButton-Double-state button control

EditText-Editable text controls

ProgressBar-progress bar control

Seekbar-draggable progress bar control

Autocompletetextview-Editable text control with auto-completion enabled

Multiautocompletetextview-Editable text control that supports AutoComplete, allowing multiple values to be entered (multiple values are automatically separated by the specified delimiter)

zoomcontrols-Zoom In/Out button control

include-integrated controls

Videoview-Video playback controls

WebView-Browser Controls

Ratingbar-scoring controls

tab-Tab control

spinner-drop-down box control

chronometer-Timer control

ScrollView-scroll bar control

Textswitcher-Text converter control (adds some animation effects when changing text)

gallery– Gallery Controls

Imageswitcher-Picture Converter controls (add some animations when changing pictures)

GridView-Grid control

ListView-List control

expandablelist-List control that supports the expand/Shrink feature

3.3 Variable Naming conventions

Variable naming: Prefix + type description + meaning description

Prefix:

Member variable: m_*** local variable: l_*** parameter: a_***

Constant: Uppercase _*** enumeration value: em_***

3.4 Catalog Normalization for the entire project

1, the System directory specification:

The project directory includes not only the source code, but also: requirements related documents, design documents, planning log documents, test documents, project in-progress learning documents (refer to the demo), to make the whole project clearer,

2, Source code directory specification:

The general System namespace directory should try not to exceed 3 levels, [organization name]. [Project name]. [Module Name]:com.pccb.app

3.5 Res resource file naming

The XML file under 1,res/layout is named with a combination of lowercase and underscore "_" and prefixed to differentiate

Positive example:

XML configuration file for dialog box: Dlg_name.xml

The ID in 2.layout takes the following naming pattern: The logical name of the view abbreviation _ Module name _view

Description: View's abbreviation details are as follows

Listview:lv

Relativeview:rv

Textview:tv

Imageview:iv

Imagebutton:ib/ibtn

Button:btn

Positive example:

@+id/lv_appstore_applist

Counter Example:

@+id/listview01

The view variable in 3.activity takes the following naming pattern: logical name _view abbreviation

Positive example:

Listviewapplistlv

The resource file under 4.res/drawable takes the following naming pattern: Activity Name _ logical name/common_ logical name

Positive example:

Main_default.png,main_pressed.png

The ID in 5.strings.xml takes the following naming pattern: Activity Name _ Function Module Name _ Logical name/activity name _ logical name/common_ logical name

Positive example:

<string name= "main_downloading" > Downloading "</string>

6. String information should be defined uniformly in Strings.xml, except for debugging information

7. When using logs, unimportant information is defined at the debug level or info level, and in more severe cases the log defines the warn level and the error level. Do not use SYSTEM.OUT.PRINTLN () as much as possible under normal circumstances; As output of the log


4. Code Writing Specification
(1) Establish a standard indent size (such as four spaces) and consistently use this standard. Aligns the code section with the specified indentation.
(2) Align the left and right brackets vertically in the position of the brackets aligned, such as:
for (i=0; i<100; i++)
{
;
}
(3) Indenting code along logical structure lines makes the code easier to read and understand, such as:
if (expression)
{
if (expression)
{
//
Fill in your code block here;
//
}
Else
{
//
Fill in your code block here;
//
}
}
(4) Establish the maximum line length for comments and code to avoid having to scroll the source editor and provide a neat hard-copy representation.
(5) When a line is too long and must be wrapped, use the indent format in the following line-wrapping code, as follows:
String inserstring = "Insert into TableName (username,password,email,sex,address)"
+ "Values (' soholife ', ' chenyp ', ' [email protected] ', ' Male ', ' Shenzhen Futian ')";
(6) The statement placed on each line avoids more than one line. Special loops, such as for (I =0;i<100;i++), are excluded.
(7) When writing an SQL statement, use all uppercase for the keyword and use case blending for database elements such as tables, columns, and views. For example select * from Table1;
(8) Placing each major SQL clause on a different line makes it easier to read and edit statements, such as:

SELECT FirstName, LastName
From Customers
WHERE state = ' WA '

(10) Use whitespace to provide structural clues to the source code. Doing so creates a code "segment" that helps the reader understand the logical segmentation of the software
(11) Divide large complex code segments into smaller, easier-to-understand modules.

5. Notes
Software documentation exists in two forms: external and internal. External documents, such as specifications, help files, and design documents, are maintained outside the source code. Internal documentation consists of comments that developers write in the source code at development time.
Regardless of the availability of external documents, the source code list should be able to exist independently because hard-copy documents may be misplaced.   External documents should consist of specifications, design documents, change requests, error histories, and coding standards used. The following points are the annotated methods of the specification:

(1) A project should have a unified header file annotation to illustrate the entire project information, creation date, version, etc.

(2) Explanation of important procedures and annotations

(3) When the code is modified or deleted, the original code is masked by the method of annotation, and the developer's own comments on the modification operation are added. The format is:

Original code

Added/(modified/deleted) by developer name year-month-day;

For business reasons, please indicate the reason for modification or deletion)

New Code
(4) Use the XML document format, such as the following method of comments:
<!--comment Content--

(5) Avoid messy annotations, but instead use whitespace to separate comments from the code.
(6) Remove all temporary or extraneous comments to avoid confusion in future maintenance work.
(7) Comments should be accurate description of the code, there should be no ambiguity.
(8) Constructs annotations throughout the application using a uniform style with consistent punctuation and structure.

(9) The contents of the method note (1,5,6,7 items are normally written up)

1. Class what does the method do? 2. How the method works. 3. Code revision history. 4. Method call code demonstration.

5. What parameters must be passed to this method. @param 6. Exception handling. @throws

7. What this method returns. @return

6. Improve code quality

(1) Delete useless variables

(2) Remove useless introductions

(3) For reusable parts, must be extracted into a common method to reduce the amount of code

(4) Variable/method name must be clear and easy to understand, do not care about the length

(5) After the code review, reduce the chance of error.

(6) Use the appropriate way to think about design patterns to develop

7. Design mode (Patterns)--the basis of reusable object-oriented software

Design patterns are a set of reusable, most known, categorized purposes, code design experience Summary. Design patterns are used in order to reuse code, make code easier for others to understand, and ensure code reliability. There is no doubt that design patterns in others in the system are multi-win, design patterns so that code is truly engineering, design patterns are the cornerstone of software engineering, like a block of bricks and tiles in the building. The rational use of design patterns in the project can solve many problems perfectly, each of which has corresponding principles in the present, each of which describes a recurring problem around us, and the core solution of the problem, which is why it can be widely used.

A programmer's understanding of the design pattern:
"Do not understand" why the very simple things to make so complicated. Later with the experience of software development began to understand that I see the "complex" is precisely the essence of design patterns, I understand the "simple" is the key starts locks model, the purpose is only to focus on solving the present problem, and the design pattern of "complex" is that it is to construct a "universal key", The aim is to propose a lock-out scheme for all locks. I've been writing "simple" code before I really understood design patterns.
This "simple" is not a simple function, but a simple design. Simple design means lack of flexibility, the code is hard, it's only useful in this project, and getting the rest of the project is rubbish, which I call "one-time code."

To make the code reusable, design your code in ' design mode '.

Many of the programmers I know come into contact with the design patterns, have a sense of brief encounter, some people describe after learning the design patterns feel like they have been reborn, reached a new level, and some people even know whether to understand the design pattern as a programmer to divide the standard.

We also cannot fall into the trap of patterns, in order to use the pattern to go to the pattern, that will fall into the formalism. When we use patterns, we must pay attention to the intent of the pattern (intent), rather than focusing too much on the implementation details of the pattern, as these implementation details may change in certain circumstances. Do not stubbornly believe that a class diagram or implementation code in a design pattern represents the pattern itself.


Design principles: (important)
1. Logic code independent into a separate method, focusing on encapsulation-easy to read, easy to reuse.
Do not write down hundreds of lines of logical code in one method. Separate the small logic code, write in other methods, easy to read its repeatable call.
2. Write the class, write the method, write the function, should consider its portability, reuse sex: Prevent one-time code!
Is it possible to get other things in the same category? Can I get it in other systems?
3. Skilled use of inherited ideas:
Find the similarities in the application, and not easily change things, extract them into the abstract class, let subclasses inherit them;
The idea of inheritance also facilitates the establishment of their own logic on the achievements of others. such as ImageField extends JTextField;
Skilled use of the idea of the interface:
Find out where changes may be needed in your application, separate them, and don't mix with code that doesn't need to change.

Design mode:

1.java design mode in 23

2.MVC mode

3.MVP mode

Android Development Code Specification

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.