4年前,进入一个外企,和一帮老外共同开发一个项目. 那时候还是菜鸟,当时就是因为代码规范问题导致几乎每周开发都被批,也因为代码规范导致烦了很多低级BUG.
其实软件开发并没什么太大难道,很多时候就是得靠心细。
1.数组标识符应该紧跟在数组类型后面,而非变量后面
如
int data[] = new int[1024];
建议写成
int[] data = new int[1024];
2.if中的条件判断在特定情况下需要合并
如
if(lastestTime > recordTime){
if(isLogin()){
//...
}
}
建议写成
if(lastestTime > recordTime && isLogin()){
//...
}
3.if语句块在特定情况下可以简写
如
if(isExistAccount()){
return true;
} else{
return false;
}
建议写成
return isExistAccount();
4.布尔型变量没必要再和true或false进行比较
如
int status = hasSubcribe == true ? 1 : 0;
建议写成
int status = hasSubcribe ? 1 : 0;
5.inteface中方法没有必要使用public修饰,常量没有必要使用public static修饰
如
public interface HostCallBack(){
public static int MODE_INSERT = 1;
public static int MODE_ALL =2;
public void clear();
}
建议写成
public interface HostCallBack(){
int MODE_INSERT = 1;
int MODE_ALL =2;
void clear();
}
6.重写equals方法需要遵守重写hashCode方法约定
如
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AccountVo accountVo = (AccountVo) o;
if (id != accountVo.id) return false;
return name.equals(accountVo.name);
}
建议增加上重写hashCode方法
@Override
public int hashCode() {
int result = (int) (id ^ (id >>> 32));
result = 31 * result + name.hashCode();
return result;
}
7.catch中不要再对Exception类型做判断
如
try{
//...
}catch(Exception e){
if(e instanceOf IOException){
//...
} else{
//...
}
}
建议写成
try{
//...
}catch(IOException e){
//...
}catch(Exception e){
//...
}
8.方法体不宜太长,可以根据具体情况适当将方法体内部部分逻辑拆解出来
如
public void fixRecord(int rid, String name){
//...
//方法体太长....
//...
}
建议写成
public void fixRecord(int rid, String name){
//...
updateRecord(int rid);
//...
}
private void updateRecord(int rid){
//...
}
9.xml元素没有内容应该采用简写形式
如
<item name="desc_tv" type="id"></item>
建议写成
<item name="desc_tv" type="id" />
10.switch语句块需要加上break
如
switch (retCode){
case 3
// ...
break;
case 1:
// ...
break;
case 2:
// ...
break;
}
建议写成
switch (retCode){
case 3
// ...
break;
case 1:
// ...
break;
case 2:
// ...
break;
default:
// ...
break;
}
11.变量名含义须具有唯一性
如:
String password = AppAccountManager.getCurrentPassword();
password = EncryptUtil.decrypt(password);
建议写成
String password = AppAccountManager.getCurrentPassword();
String decryptPassword = EncryptUtil.decrypt(password);
12.无效的import需要删除
如果没有用到需要删除干净
13.注释不要与代码放在同一行
如:
private int mState = STATE_ADD; // add record statef
建议写成
// add record statef
private int mState = STATE_ADD;
14. for 循环
如:
int[] integers = {1, 2, 3, 4};
for (int j = 0; j < integers.length; j++) {
}
建议写成
for (int i : integers) {
}