Android development code specification, android development code

Source: Internet
Author: User
Tags image converter

Android development code specification, android development code

Directory

  • 1. Basic naming principles
  • 2. Basic naming rules
  • 2.1 Basic Programming naming rules
  • 2.2 Classification naming rules
  • 3. Classification naming rules
  • 3.1 basic data type naming rules
  • 3.2 Control naming rules
  • 3.3 variable naming rules
  • 3.4 directory standardization for the entire project
  • 3.4 res resource file naming rules
  • 4. code writing specifications
  • 5. Notes
  • 6. Improve code Quality
  • 7. Design Patterns)

 

1. Basic naming principles
In object-oriented programming, naming of classes, objects, methods, and variables is very skillful. For example, case sensitivity, starting with different letters, and so on. However, in order to ensure that there is no conflict between resources, and every one is easy to remember.

The naming scheme is the most influential help for understanding the logical flow of an application. The name should indicate "what" rather than "how ". The naming principle is: make the name long enough for a certain purpose, and be short enough to avoid lengthy. The unique name is only used to differentiate items. The following are standard naming methods.
 

2. Basic naming rules

2.1 Basic Programming naming rules 
(1) Avoid obscure names, such as the property name xxK8, which may lead to ambiguity.
(2) In an object-oriented language, it is unnecessary to include a class name in the class attribute name, such as Book. BookTitle. Instead, Book. Title should be used.
(3) in languages that allow function overloading, all overloading should execute similar functions.

(4) use the verb-Noun method to name the routine for performing specific operations on a given object, such as CalculateInvoiceTotal (). (A routine is a set of functional interfaces or services provided by a system)

(5) If appropriate, add the computing qualifier (Avg, Sum, Min, Max, Index) at the end or start 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, such as fileIsFound.

(8) even for variables that may only have a short lifetime in several lines of code, they still use meaningful names. Only use single-letter variable names for short-cycle indexes, such as I or j.

(9) to help distinguish between variables and routines, use CalculateInvoiceTotal for the routine name. the first letter of each word is capitalized. For variable names, use camel case-sensitive (documentFormatType). The first letter of each word except the first word is capitalized.

(10) do not use the original numeric or string, but use the name constant NUM_DAYS_IN_WEEK for maintenance and understanding.

 

 

2.2 Classification naming rules

(1) package name

The Java package name is composed of lowercase words. However, due to the characteristics of Java object-oriented programming, every Java programmer can write their own Java packages. To ensure the uniqueness of each Java package name, in the latest Java programming specification, the programmer is required to add a unique prefix before the name of the defined package. Because domain names on the Internet are not repeated, programmers generally use their own domain names on the Internet as the unique prefix of their packages.

Example: com. pccb. app

(2) Class naming

The class name must start with an upper-case letter and the other letters in the word must be lower-case. If the class name is composed of multiple words, the first letter of each word should be in the upper-case format, such as TestPage; if the class name contains the abbreviation, each letter in the written word should be capitalized, for example, XMLExample. Another naming technique is that the class is designed to represent objects, therefore, you should select a noun whenever possible when naming a category.

Example: Circle

(3) method naming

The first word of the method name should start with a lower-case letter, and the subsequent words should start with an upper-case letter.

Example: sendMessge

(4) constant naming

The constant names should all use uppercase letters and indicate the complete meaning of the constant. If a constant name is composed of multiple words, the words should be separated by underscores.

Example: MAX_VALUE

(5) parameter naming

The parameter naming rules are the same as the method naming rules. To avoid confusion during reading the program, make sure that the parameter name is a word as clear as possible.

Private property: private int mAge;

Static variable: static String sName;

Internal variable of the function: int _ Age;

Parameter for method definition: int pAge;

 

(6) Javadoc comments

In addition to using our common annotation methods, the Java language specification also defines a special annotation, that is, the Javadoc annotation we call, it is used to record APIs in our code. Javadoc comments are multiline comments that start with/** and end with */. Comments can contain HTML tags and specialized keywords. The advantage of using Javadoc annotations is that the compiled notes can be automatically converted into online documents, saving the trouble of writing program documents separately.

For example:

/**

* This is an example

* Javadoc

*

* @ Author darchon

* @ Version 0.1, 10/11/2002

*/

At the beginning of each program, Javadoc is generally used to comment on the overall description of the program and copyright information. Then, Javadoc comments can be added to each class, interface, method, and field in the main program, the first part of each comment first summarizes the functions completed by the class, interface, method, and field in one sentence. This sentence should take a separate line to highlight its generalization, A more detailed description section can be followed after this sentence. After descriptive paragraphs, you can also follow special paragraphs starting with the Javadoc annotation label, such as @ auther and @ version in the preceding example. These paragraphs are displayed in a specific way in the generated document.

Although adding comments to a poorly designed program won't make it a good program, writing programs according to programming specifications and adding good comments to the program can help you write out the perfect design, it is more important to run highly efficient and easy-to-understand programs, especially when multiple people work together to complete the same project. As the saying goes, it is good to spend a little time adapting to Java programming specifications.

 

3. Classification naming rules

3.1 basic data type naming rules

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

For example, String srtName;

 

3.2 Control naming rules

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: SPNs _ + 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

 

Controls are described as follows:

• TextView-text display control

• Button-Button control

• ImageButton-image button control

• ImageView-Image Display Control

• CheckBox-check box Control

• RadioButton-single-Stick Control

• AnalogClock-a clock (with a table disk) Control

• DigitalClock-workbook Control

• DatePicker-date Selection Control

• TimePicker-Time Selection Control

• ToggleButton-Dual-state button control

• EditText-editable text Control

• ProgressBar-progress bar Control

• SeekBar-a drag progress bar Control

• AutoCompleteTextView-editable text controls that support Automatic completion

• MultiAutoCompleteTextView-editable text controls that support Automatic completion and allow multi-value input (values are automatically separated by specified delimiters)

• ZoomControls-zoom in/out button control

• Include-integrated controls

• VideoView-video playback control

• WebView-browser controls

• RatingBar-scoring Control

• Tab-Tab Control

• Spinner-drop-down box Control

• Chronometer-timer control

• ScrollView-scroll bar Control

• TextSwitcher-Text Converter Control (some animation effects are added when the text is changed)

• Gallery-Gallery controls

• ImageSwitcher-Image Converter Control (some animation effects are added when the image is changed)

• GridView-Grid Control

• ListView-List Control

• ExpandableList-List controls supporting the expand/contract function

 

3.3 variable naming rules

Variable name: prefix + type description + meaning description

Prefix:

Member variable: m _ *** local variable: l _ *** form parameter: _***

Constant: uppercase _ **** enumeration value: em _***

 

3.4 directory standardization for the entire project

1. System Directory specifications:

The project directory contains not only the source code, but also the requirement-related documents, design documents, plan log documents, test documents, and project learning documents (refer to the Demo ); make the entire project clearer,

2. Source Code directory specification:

Generally, the system namespace Directory should not exceed three layers. [organization name]. [project name]. [Module name]: com. pccb. app

 

3.5 res resource file name

1. xml files under res/layout are all named in combination with lowercase letters and underscores (_), and prefix is added to distinguish them.

Example:

Xml configuration file of the dialog box: dlg_name.xml

2. The id in layout adopts the following naming mode: view abbreviation _ module name_view logical name

Description: The abbreviation of view is as follows:

ListView: lv

RelativeView: rv

TextView: TV

ImageView: iv

ImageButton: ib/ibtn

Button: btn

Example:

@ + Id/lv_appstore_applist

Counterexample:

@ + Id/ListView01

3. The view variable in the activity uses the following naming mode: Logical name_view

Example:

ListViewapplistLv

4. The resource file in res/drawable adopts the following naming mode: activity name_logical name/common _ logical name

Example:

Main_default.png,main_pressed.png

5. The id in strings. xml adopts the following naming mode: activity name_function module name_logic name/activity name_logic name/common _ logic name

Example:

<String name = "main_downloading"> downloading... </string>

6. The string information should be defined in strings. xml, except for debugging information.

7. When using logs, unimportant information is defined in the debug or info level. In severe cases, the logs are defined as warn and error levels. Normally, try not to use System. out. println (); as the log output.


4. code writing specifications
(1) create a standard indent size (such as four spaces) and use this standard in a consistent manner. Align the code section with the specified indentation.
(2) Align the Left and Right brackets vertically at the positions of the brackets, such:
For (I = 0; I <100; I ++)
{
;
}
(3) indent the code along the logical structure line to make the code easier to read and understand, such:
If (expression)
{
If (expression)
{
//
// Enter your code block here;
//
}
Else
{
//
// Enter your code block here;
//
}
}
(4) Create the maximum line length for comments and codes to avoid having to scroll the source code editor and provide neat hard copy representation.
(5) When a line of content is too long and must be changed, use the indent format in the line feed code, as shown below:
String inserString = "Insert Into TableName (username, password, email, sex, address )"
+ "Values ('soholife', 'chenyp', 'soholife @ sina.com ', 'male', 'shenzhen Futian ')";
(6) avoid placing more than one statement on each row. Except for special loops such as for (I = 0; I <100; I ++.
(7) When writing SQL statements, all keywords are capitalized, and database elements (such as tables, columns, and views) are case-insensitive. For example, SELECT * FROM Table1;
(8) place each major SQL clause on different rows to facilitate reading and editing statements. For example:

SELECT FirstName, LastName
FROM MERs
WHERE State = 'wa'

(10) Use a blank space to provide a structure clue for the source code. This will create code segments to help readers understand the logical segments of the software.
(11) divide large complex code segments into small and easy-to-understand modules.

5. Notes
Software Documents exist in two forms: external and internal. External documents (such as specifications, help files, and design documents) are maintained outside the source code. Internal documents are composed of comments written by developers in the source code during development.
The availability of external documents is not considered. The source code list should be independent because the hard copy document may be put in the wrong place. External documents should consist of specifications, design documents, change requests, error history records, and encoding standards used. The following are standard comments:

(1) A project should have a uniform header file comment to describe the information, creation date, version, and so on of the entire project.

(2) Add notes to important programs

(3) When modifying or deleting the code, block the original code with comments, and add the developer's own comments on the modification operation. Format:

// Original code

// Added/(Modified/Deleted) by developer name year-month-day;

// For business reasons, you must specify the reasons for modification or deletion)

New Code
(4) use the XML document format, as described in the following method:
<! -- Comment content -->

(5) Avoid messy comments. Instead, use blank spaces to separate comments from the code.
(6) Remove all temporary or irrelevant comments to avoid confusion during future maintenance work.
(7) annotations should be accurate descriptions of codes, and there should be no ambiguity.
(8) construct comments using a unified style with consistent punctuation and structure throughout the application.

(9) content of method comments (items 1, 5, 6, and 7 should be written under normal circumstances)

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

 

6. Improve code Quality

(1) Delete useless variables

(2) Delete useless Introduction

(3) for reusable parts, we must extract them into a shared method to reduce the amount of code.

(4) variable/method naming must be clear and easy to understand, so you don't need to care too much about the length.

(5) After the code is complete, review the code to reduce the chance of errors

(6) use the appropriate method to think as much as possible about the design mode for development

 

 

7. Design Patterns-the basis for reusable Object-Oriented Software

Design pattern is a set of summary of code Design experiences that are repeatedly used, known to most people, classified and catalogued. The design pattern is used to make code reusable, make it easier for others to understand, and ensure code reliability. There is no doubt that the design model is a win-win solution for others and the system. The design model enables code compilation to be truly engineered. The design model is the foundation of software engineering, just like the building blocks. The rational use of the design pattern in the project can perfectly solve many problems. Each pattern has a corresponding principle in the present, each pattern describes a recurring problem around us and its core solution, which is also the reason for its wide application.

A programmer's understanding of the design model:
"Don't understand" Why make simple things so complicated. Later, with the increase of software development experience, I began to understand that what I saw as "complicated" is precisely the essence of the design model. What I understood as "simple" is the one-key unlock mode, the purpose is only to solve the current problem. The "complexity" of the design model lies in the fact that it is to construct a "universal key" to propose an unlocking solution for all locks. I have been writing "simple" code before I really understand the design pattern.
This "simple" is not a simple function, but a simple design. A simple design means a lack of flexibility, and the code is very steel. It is only useful in this project. It is rubbish in other projects. I call it "one-time code ".

--> To make the code reusable, use 'Design mode' to design your code.

Many programmers I know have a sense of mutual sorrow when they come into contact with the design model. Some people describe that after learning the design model, they feel like they have been reborn and have reached a new realm, some people even regard whether or not they understand the design pattern as the criteria for programmer division.

We cannot fall into the pattern trap either. To use the pattern, we will fall into formalism. When using the pattern, we must pay attention to the intent of the pattern (intent), instead of paying too much attention to the Implementation Details of the pattern, because these Implementation Details are under specific circumstances, some changes may occur. Do not stubbornly think that the class diagram or implementation code in the design pattern book represents the pattern itself.


Design principles: (important)
1. The logic code is independent to a separate method, focusing on encapsulation-easy to read and easy to reuse.
Do not write hundreds of lines of logic code in a method. Separate small Logic Codes and write them in other methods. This method is easy to read and can be called repeatedly.
2. Portability and reusability should be taken into account when writing classes, writing methods, and writing functions: preventing one-time code!
Can I find other similar things? Can I get it from other systems?
3. Skillful Use of inheritance ideas:
Find the similarities in the application that are not easy to change, and extract them into the abstract class so that the subclass can inherit them;
It is also convenient to establish your own logic on others' achievements. For example, ImageField extends JTextField;
Skills in Using Interfaces:
Identify potential changes in the application and separate them from those that do not need to be changed.

 

Design Mode:

1. Design Pattern in java 23

2. MVC Mode

3. MVP Mode

 

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.