You must never do the following (不要出现类似下面的代码 —>没有处理异常):
void setServerPort(String value) {
try {
serverPort = Integer.parseInt(value);
} catch (NumberFormatException e) { }
}
PS:就算你觉得不重要,或者不必要,也要处理,哪怕是一个简单的输出
You should not do this:
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!
}
This is bad: import foo.*;
This is good: import foo.Bar;
字段(属性变量)应该定义在文件的顶部,它们应该遵循下面列出的命名规则。
私有的非静态字段名称以m开头。
私有的静态字段名称以s开头。
其他字段以小写字母开头。
静态字段(常数)是带下划线的大写字母。
Example:
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;
。。。。。。。。
}
把缩写词当作单词
Good | Bad |
---|---|
XmlHttpRequest |
XMLHTTPRequest |
getCustomerId |
getCustomerID |
String url |
String URL |
long id |
long ID |
下一层级的首字母应该比上一个层级的首字母差4个位置,eg:
if (x == 1) {
x++;
}
位置不够写,代码下移一行写时,前面空8个空格位置,eg:
Instrument i =
someLongExpression(that, wouldNotFit, on, one, line);
写判断语句,如果只需要一行就能写完(连判断在内一行写完),那么不需要用括号,eg:
if (condition) body();
This is bad:
if (condition)
body(); // bad!
重写任何方法,都需要在前面添加@Override
关于注释:
任何方法、结构体、类添加注释的时候,都应该是写在前面,并且都应该以一行一个注释的形式。
当对变量添加注释的时候,代码和注释应该是在同一行,除非到达了该行最大长度。
关于打印
使用类名作为标记,并将其定义为文件顶部的静态最后字段
e.g.:
public class MyClass {
private static final String TAG = MyClass.class.getSimpleName();
public myMethod() {
Log.e(TAG, "My error message");
}
}
ps:必须在发布版本上禁用打印和调试日志。还建议禁用信息、警告和错误日志,但如果认为它们可能有助于识别发布版本中的问题,则可以使用。如果您决定让它们启用,必须确保它们不会泄露私人信息,如电子邮件地址、用户ID等
仅在调试中显示日志:
if (BuildConfig.DEBUG) Log.d(TAG, "The value of x is " + x);
当扩展组件的时候,比如 Fragment 等,应该优先使用重写方法,并且重写顺序应该和生命周期对应,eg:
public class MainActivity extends Activity {
//Order matches Activity lifecycle,重写顺序和Activity的生命周期顺序一致
@Override
public void onCreate() {}
@Override
public void onResume() {}
@Override
public void onPause() {}
@Override
public void onDestroy() {}
}
自定义方法的时候,参数列表如果存在获取上下文(Context 对象),那么应该写在第一个,如果有回调接口,那么应该写在最后一个 ,eg:
// Context always goes first
public User loadUser(Context context, int userId);
// Callbacks always go last
public void loadUserAsync(Context context, int userId, UserCallback callback);
关于字符串常量的命名和值
在某个对象使用键值对方法的时候,key 值要和它们对应的类名前缀相同。
e.g.:
Element | Field Name Prefix |
---|---|
SharedPreferences | PREF_ |
Bundle | BUNDLE_ |
Fragment Arguments | ARGUMENT_ |
Intent Extra | EXTRA_ |
Intent Action | ACTION_ |
在全局方法中获取到的对象,比如Fragment.getArguments() 获取到的是一个Bundle,但也应该使用不同的前缀来区分它们,eg:
Example:
// 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”;
当活动或者碎片需要某些参数(数据 )的时候,应该声明一个public static的方法,
相对于活动,eg:
public static Intent getStartIntent(Context context, User user) {
Intent intent = new Intent(context, ThisActivity.class);
intent.putParcelableExtra(EXTRA_USER, user);
return intent;
}
相对于 fragment,e.g.:
public static UserFragment newInstance(User user) {
UserFragment fragment = new UserFragment;
Bundle args = new Bundle();
args.putParcelable(ARGUMENT_USER, user);
fragment.setArguments(args)
return fragment;
}
ps:这些方法应该写在顶部,并且在onCreate()前
方法里面使用的参数或者参数的 key 应该是私有的。
关于跳到下一行。
如果要跳到一下行,如果代码包含操作符,只能在操作符前面断开,eg:
int longName = anotherVeryLongVariable + anEvenLongerOne - thisRidiculousLongOne
+ theFinalOne;
如果是赋值操作符(=)后断开,应该是一整句断开,eg:
int longName =
anotherVeryLongVariable + anEvenLongerOne - thisRidiculousLongOne + theFinalOne;
当多个方法在同一句(符号『;』前算一句)的时候,每个方法应该单独的在一行,在『.』前面,eg:
Picasso.with(context)
.load("http://ribot.co.uk/images/sexyjoe.jpg")
.into(imageView);
当一个方法参数很多或者参数很长的时候,你如果要断开,那么必须在『,』之后断开,eg:
loadPicture(context,
"http://ribot.co.uk/images/sexyjoe.jpg",
mImageViewProfilePicture,
clickListener,
"Title of the picture");
关于 XML 的风格
尽量使用『/>』作为结束
This is good:
This is bad :
当给组件 ID 命名的时候,使用组件名字作为前缀,eg:
关于 Strings
字符串命名应使用它们所属功能或者部分来作为它们的名字前缀,eg:
registration_email_hint
or registration_name_hint
如果它们不属于任何一部分,则应该遵守类似下面的原则:
Prefix | Description |
---|---|
error_ |
An error message |
msg_ |
A regular information message |
title_ |
A title, i.e. a dialog title |
action_ |
An action such as "Save" or "Create" |