Java programming specifications, java programming

Source: Internet
Author: User

Java programming specifications, java programming

From the very beginning, I have heard many good coding habits from programming. Indeed, if you don't want good coding to become a habit, you can only indulge in casual code styles (the code you browse on the internet is like this ).

I also read many people's summary on the Internet and learned a lot. Summarize the parts. Most of this essay is just a text Porter. please correct me if you have any mistakes.

 

1. identifier name(Try to express the complete meaning with the least number of characters, but use the abbreviation in the name:Try not to use the abbreviation unless it is customary.)

Common abbreviations:

1.1 Camel naming method: This method is also known as the Camel naming method. Except the first word, the first letter of all other words is capitalized.

For example, touchEvent is used for "method name", "variable name", and "parameter name" (the parameter Should Not Be Named with a single character .)
Pascal (1.2 Pa) naming method: Also known as the big camper naming method, the first letter of all words is capitalized.

For example, TouchEvent is used for "Interface Name" and "class name ".
1.3 underline naming method: Separate words with underscores.

For example, touch_event is used for the name of a constant (uppercase letters are used for the name, for example, TOUCH_DOWN), "resource files", "controls", and "layout Files" (lowercase letters.

1. 4. Others.

Package: adopts the anti-write domain name naming rules, that is, in the form of com. xx. xxx. xxxx, such as com. tencent. qq. activitys.

All use lower-case letters. The first-level package name is com, the second-level package name is xx (generally the company or individual domain name), the third-level package name is based on the application name, and the fourth-level package name is the function module name.

 

Ii. source file structure

A source file contains (in order ):

Each part is separated by a blank line.

2.1 license or copyright information

If a file contains license or copyright information, it should be placed at the beginning of the file. Insert copyright information reference

2.2 import Statement

Do not use wildcard characters * For import. That is, multiple classes under the same package are introduced. It is generally not recommended to write in this way.

The import statements can be divided into the following groups. In this order, each group is separated by an empty row:

Rows in the group are arranged alphabetically.

2.3 class declaration

There is only one top-level class declaration (in the source file with the same name as it)

Note: 1. class member sequence: each class should sort its members in a certain logic (it is better not to simply add the members to the end in chronological order ).

2. When a class has multiple constructors or multiple methods of the same name, these functions/methods should appear together in order, and do not include other functions/methods in the middle.

 

Iii. Format

3.1 braces

Braces andif, else, for, do, whileStatement, even if there is only one statement (or empty), you should also write braces.

For non-empty blocks and block structures:

  • No line feed before left braces
  • Line feed after left braces
  • Wrap line before right braces
  • If the right braces are the termination of a statement, function body, or class, the right braces are followed by a line break; otherwise, no line feed is performed. For example, if the right braces are followed by else or comma, no line breaks are generated.
return new MyClass() {  @Override public void method() {    if (condition()) {      try {        something();      } catch (ProblemException e) {        recover();      }    }  }};

Do not separate a line of curly braces, which is the same line as the code above. In addition, curly braces are separated from the preceding Code by a space.

public void method() { // Good } public void method(){ // Bad}  public void method(){ // Bad} 

 

An empty block structure does not contain anything. Braces can be written in a concise way.{}, No line feed is required. Exception: if it is a part of a multi-block Statement (if/else or try/catch/finally), a line break is required even if there is no content in the braces.

Example:

void doNothing() {}

3.2 space usage

1. if, else, for, switch, while, and other logic keywords are separated by a space in the following statement.

// Goodif (booleanVariable) {    } else {    }// Badif(booleanVariable) {    }else {    }

2. Each operator is separated by a space.

Int result = a + B; // Good, = and + are separated by a space. int result = a + B; // Bad, = and + are separated by no space.

3. Each parameter of the method is separated by a space.

Public void method (String param1, String param2); // Good, the comma after param1 and String are separated by a space method (param1, param2); // Good, when calling a method, the comma following param1 is separated from param2 by a space method (param1, param2); // Bad, not separated by a space

3.3 Use of empty lines

Logically related code segments are separated by empty lines to improve readability. Empty rows also have only one row empty. Do not empty multiple rows. A blank line is required in the following cases:

  • Between Two Methods
  • Between two logical segments in the Method
  • Between the local variable in the method and the first logical statement of the Method
  • Between constants and variables

3.4 When an expression cannot be contained in a row, it can be displayed with a line break. The new line is indented with eight spaces.

String str = String.format("%.3f,%.3f,%.3f,", bandGyroscopeEvent.getAngularVelocityX(),        bandGyroscopeEvent.getAngularVelocityY(), bandGyroscopeEvent.getAngularVelocityZ()) + strTimestamp + "\n";

3.5 declare only one variable at a time

Do not use combination declarations, such

int a, b;//bad//goodint a;int b;

3.6 million formatting code shortcuts in Android Studio

CTRL + ALT + L (Win)
OPTION + CMD + L (Mac)

3.7 enumeration class

In many classic Java books, enumeration is recommended to replace int constants. However, enumeration is not recommended in Android development, especially in large apps. Because it will sacrifice the execution speed and greatly increase the file size. It is also an aspect of performance optimization to reduce OOM (memory optimization.Android uses enumeration annotations instead of enumeration optimization code.

3.8 supplement

The unit of text size is sp, and the unit of element size is dp.

The strings in the application are defined in strings. xml and referenced in the Code and layout file.

Color values are defined in colors. xml and referenced in the Code and layout files. In addition, do not reference the system color in the code or layout file, except for transparency.

 

Iv. Annotations

4.1 File Header comments

Add the copyright statement at the top of the file in the following format:

/** * Copyright (c) Microsoft Corporation All rights reserved.   */

4.2 class and interface comments

Add javadoc comments to classes and interfaces in the following format:

/*** Description of the class or interface ** @ author $ {USER} * @ date $ {DATE }*/

4.3 method comments

Javadoc comments must be added to each of the following methods to describe the purpose, parameters, and return values of the method.

  • All methods defined in the interface
  • Custom abstract methods in abstract classes
  • Abstract The Custom public methods of the parent class
  • Public methods of tool classes
/*** Login ** @ param loginName login name * @ param password * @ param listener callback listener */public void login (String loginName, String password, actionCallbackListener <Void> listener );

4.4 comments of variables and constants

  • All constants defined in the interface
  • Public constants of public classes
  • All enumeration constants defined by the enumeration class
  • All attribute variables of the object class

For more information, see Google Java programming style guide.

 

 

 

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.