|
File Naming
Class naming
Named hump should follow nomenclature
For class inherits from Android components, the name should be changed to the end of the name component; for example: SignInActivity, SignInFragment, ImageUploaderService, ChangePasswordDialog.
The file named Res
Resource file format should be named in lowercase + underscore (_) is.
Image files
The following is an image file naming conventions
Asset Type Prefix Example
Action bar ab_ ab_stacked.9.png
Button btn_ btn_send_pressed.9.png
Dialog dialog_ dialog_top.9.png
Divider divider_ divider_horizontal.9.png
Icon ic_ ic_star.png
Menu menu_ menu_submenu_bg.9.png
Notification notifi_ notifi_bg.9.png
Tabs tab_ tab_pressed.9.png
For icon naming convention
Asset Type Prefix Example
Icons ic_ ic_star.png
Launcher icons ic_launcher ic_launcher_calendar.png
Menu icons and Action Bar icons ic_menu ic_menu_archive.png
Status bar icons ic_stat_notify ic_stat_notify_msg.png
Tab icons ic_tab ic_tab_recent.png
Dialog icons ic_dialog ic_dialog_info.png
The choice of state naming convention
State Suffix Example
Normal _normal btn_order_normal.9.png
Pressed _pressed btn_order_pressed.9.png
Focused _focused btn_order_focused.9.png
Disabled _disabled btn_order_disabled.9.png
Selected _selected btn_order_selected.9.png
Layout file
Android layout file name components should be used for matches, but this should begin with the name of the component. For example, if we SignInActivity, create layout files that should be the name of the layout file is activity_sign_in.xml.
Component Class Name Layout Name
Activity UserProfileActivity activity_user_profile.xml
Fragment SignUpFragment fragment_sign_up.xml
Dialog ChangePasswordDialog dialog_change_password.xml
AdapterView item - item_person.xml
Partial layout - partial_stats_bar.xml
A special case is create a layout for the Adapter in the child when, for example, to display the contents of the ListView. In this case, the prefix layout file should be item_
There should be noted that when there is a special case, and that is creating a layout in which a small piece of the layout, in which case you should use the prefix partial_
File menu
Similar to the naming rules layout files, menu files, and the name of Android components should be used for matches. For example, when we create a menu file UserActivity, the name of the file that the menu should be activity_user.xml
Naming convention is not the word menu as part of the name, because these files are already stored in the file menu.
resource
The values in the resource file folder naming should be in the plural. For example, strings.xml, styles.xml, colors.xml, dimens.xml, attrs.xml
Code Specification
Java language specification
Do not neglect to handle exceptions
Never write the following code
void setServerPort (String value) {
try {
serverPort = Integer.parseInt (value);
} Catch (NumberFormatException e) {}
}
Do not think your code will never trigger abnormal or insufficient to deal with such or such like the above code in your code leaving a gap for others to help you in the future to fill in. You must follow the specification to capture every an exception. You can also view the official Android documentation describes.
Do not catch general exception
Never write the following code
try {
someComplicatedIOFunction (); // may throw IOException
someComplicatedParsingFunction (); // may throw ParsingException
someComplicatedSecurityFunction (); // may throw SecurityException
// Phew, made it all the way
} Catch (Exception e) {// I'll just catch all exceptions
handleError (); // with one generic handler!
}
You can view the Android specific reasons described in official documents
Do not use finalizers
Do not use finalizers (do not know finalize can be viewed here). Even finalizer ultimately be called, but when it will do the call is not guaranteed. In most cases, you can replace good exception catching mechanism finalizer. If in some cases you have to use it to define a close () method (or similar) and then accurately explain when the method is called to.
Specification reference
This is a bad reference writer: import foo *;.
It is a qualified reference writer: import foo.Bar;
More information here
Java style guide
Definition and Nomenclature variables
Variables should define the location in the file header, and should follow the naming rules.
Private, non-static variables should have been named at the beginning of m
Private, static variables should be named at the beginning of s
The remaining variables should have been the beginning of lowercase letters
Static constants should be all uppercase letters underlined name format. For example, ALL_CAPS_WITH_UNDERSCORES.
Examples are
public class MyClass {
public static final int SOME_CONSTANT = 42;
public int publicField;
private static MyClass sSingleton;
int mPackagePrivate;
private int mPrivate;
protected int mProtected;
}
The English acronyms also look to make a word
Good Bad
XmlHttpRequest XMLHTTPRequest
getCustomerId getCustomerID
String url String URL
long id long ID
Use spaces to indent
Use four spaces to indent the code block
if (x == 1) {
x ++;
}
Use eight spaces to code line breaks
Instrument i =
someLongExpression (that, wouldNotFit, on, one, line);
Use braces
The opening brace should be on the same line with the code in its previous
class MyClass {
int func () {
if (something) {
// ...
} Else if (somethingElse) {
// ...
} Else {
// ...
}
}
}
If the conditional statement with the results of the statement and just to its length is less than the maximum length of the same line on the same line, you can omit the braces
E.g
if (condition) body ();
Error examples
if (condition)
body (); // bad!
annotation
Application Notes
According to the official Android documentation, in Java annotations for some pre-determined criteria are applied
@Override: This annotation must rewrite time and any time you want to achieve or a parent class with, for example, when you use @inheritdocs tag, and is derived from a class rather than an interface, you must. while also adding @Override label on this method.
@SuppressWarnings:. When the label only in the encounter can not ignore the warnings of conditions can only be used if a warning in line with "Can not ignore" conditions, the label must be required to use, in order to ensure that all warnings reflect the actual problems in the code.
More on specifications please refer to the notes here
Notes format
Classes, methods, and constructors: annotations are used when classes, methods, constructors, annotations should be located in the following comments, and each comment as a form of a line is as follows.
/ * This is the documentation block about the class * /
@AnnotationA
@AnnotationB
public class MyAnnotatedClass {}
Object: Notes should be kept with the object in the same row, unless the bank has reached the maximum number of characters is limited.
1
@Nullable @Mock DataManager mDataManager;
Limit the scope of variables
The scope of local variables should be kept to a minimum. This increases code readability and maintainability, and reduce the probability of error.
Local variables should try when it was first called to be declared out. And when you declare a local variable that should be initialized variable, if you do not have enough information to initialize the variable, it should be postponed until the statement has sufficient information to this variable initialization time. more information can be found here
Specification log
Please use the company-wide LogUtil class instead of native Android Log class to print the log.
Specification class members arranged
This part is not mandatory requirements, but the use of a logical and common way to arrange the class members, can enhance the readability of the code
constant
Objects
Constructor
Rewriting and callback functions (including public and private)
Public function
Private functions
Internal interfaces and inner classes
E.g:
public class Child extends Parent {
private static final int CONSTANT = 1;
private String mName;
private int mAge;
public Child (String name, int age) {
mName = name;
mAge = age;
}
@Override
public void changeName () {
...
}
public void setName (String name) {
mName = name;
}
private void setSomething () {
...
}
static class AnInnerClass {
}
}
If your class is derived from Android components, such as Activity and Fragment, good habits are the life cycle of the assembly to rewrite the method. For example, if you have a realization of the Activity onCreate (), onDestroy (), onPause () and onResume (), then the correct order:
public class MainActivity extends Activity {
// Order matches Activity lifecycle
@Override
public void onCreate () {}
@Override
public void onResume () {}
@Override
public void onPause () {}
@Override
public void onDestroy () {}
}
Order function arguments
When writing Android code function with parameters Context is very common. If this happens, then you must Context as the first parameter.
Corresponding callback interface should always as the last parameter of the function
E.g:
// Context always goes first
public User loadUser (Context context, int userId);
// Callbacks always go last
public void loadUserAsync (Context context, int userId, UserCallback callback);
String constant naming
Android SDK contains many of the key elements required for example, SharedPreferences, Bundle and Intent. Even in a small app written application, it will also generate a lot of string constants.
When using the above components, you have the string defined as static final, and they should follow the prefix naming rules:
Element Field Name Prefix
SharedPreferences PREF_
Bundle BUNDLE_
Fragment Arguments ARGUMENT_
Intent Extra EXTRA_
Intent Action ACTION_
Although Fragment.getArguments () is the return of a Bundle, but in order to distinguish, so use ARGUMENT_ as its prefix.
// Note the value of the field is the same as the name to avoid duplication issues
static final String PREF_EMAIL = "PREF_EMAIL";
static final String BUNDLE_AGE = "BUNDLE_AGE";
static final String ARGUMENT_USER_ID = "ARGUMENT_USER_ID";
// Intent-related items use full package name as value
static final String EXTRA_SURNAME = "com.myapp.extras.EXTRA_SURNAME";
static final String ACTION_OPEN_USER = "com.myapp.action.ACTION_OPEN_USER";
Fragment of parameters and Activity
When the data is passed to the Fragment and Activity by Intent or Bundle time, Key's name must follow the above naming convention.
When the Activity or Fragment need to accept parameters when you need to create a public static method to create associated Intent or Fragment.
Activity of the case, usually a method named getStartIntent ():
public static Intent getStartIntent (Context context, User user) {
Intent intent = new Intent (context, ThisActivity.class);
intent.putParcelableExtra (EXTRA_USER, user);
return intent;
}
Fragment of the case, usually a method named newInstance (), to create the parameters passed Fragment
public static UserFragment newInstance (User user) {
UserFragment fragment = new UserFragment;
Bundle args = new Bundle ();
args.putParcelable (ARGUMENT_USER, user);
fragment.setArguments (args)
return fragment;
}
Such methods should be declared before in front of the class, onCreate () method: Note 1
Note 2: if we have declared more methods, then the Key Intent or Bundle declaration should be private, because no class outside to use.
Line length limit
The length of the line of code should not be more than 100 characters, if a line of code is too long, there are usually two ways to reduce the length of the code:
Extracting a local variable or method (recommended)
By changing a line of code line into multiple lines
There are two exceptions to the line of code can allow more than 100 characters
Unable to change lines of code, such as: Website URL
Statement of package and import
Specification wrap
There is also no standard mandatory line, but there are several more generic specification compliance can hope
Operators
When you want to change line operator at the time, we should wrap before operator, for example:
int longName = anotherVeryLongVariable + anEvenLongerOne - thisRidiculousLongOne
+ TheFinalOne;
However, the above rules do not apply to the = operator should wrap after the equality operator, for example:
int longName =
anotherVeryLongVariable + anEvenLongerOne - thisRidiculousLongOne + theFinalOne;
The method under chain case
When multiple methods on the same line together when the chain has become the method. For example, under Builder mode, each method should be independent in a row, and should wrap before.
Picasso.with (context) .load ( "http://ribot.co.uk/images/sexyjoe.jpg") .into (imageView);
Picasso.with (context)
.load ( "http://ribot.co.uk/images/sexyjoe.jpg")
.into (imageView);
The case where a plurality of parameters
When a function of many parameters and parameter too long, we should, after wrapping.
loadPicture (context, "http://ribot.co.uk/images/sexyjoe.jpg", mImageViewProfilePicture, clickListener, "Title of the picture");
loadPicture (
context,
"Http://ribot.co.uk/images/sexyjoe.jpg",
mImageViewProfilePicture,
clickListener,
"Title of the picture"
);
For the specification in RxJava
The method also requires the chain Rx wrap each operation must be independent of one line, and should wrap before.
public Observable syncLocations () {
return mDatabaseHelper.getAllLocations ()
.concatMap (new Func1 > () {
@Override
public Observable extends Location> call (Location location) {
return mRetrofitService.getLocation (location.id);
}
})
.retry (new Func2 () {
@Override
public Boolean call (Integer numRetries, Throwable throwable) {
return throwable instanceof RetrofitError;
}
});
}
XML specification
Use self-closing tags
When there is no other element in a XML element, you should use self-closing tags
this is correct:
android: id = "@ + id / text_view_profile"
android: layout_width = "wrap_content"
android: layout_height = "wrap_content" />
this is wrong:
<-! Don 't do this -!>
android: id = "@ + id / text_view_profile"
android: layout_width = "wrap_content"
android: layout_height = "wrap_content">
TextView>
Named Resources
ID and name of the resource should be lowercase + underscore format
The name ID
ID should have control name as a prefix to name, for example:
Element Prefix
TextView text_
ImageView image_
Button button_
Menu menu_
ImageView example:
android: id = "@ + id / image_profile"
android: layout_width = "wrap_content"
android: layout_height = "wrap_content" />
Menu examples:
|
|
|
|