Android提升篇系列:Android项目代码优化实践

Android开发中,不同的开发团队,不同的开发人员,在实际编码中会有一些不同的地方。
但是,具有一定的更普适性的编码习惯,无疑还是相当重要的。本文主要罗列项目中常见的一些编码片段,并给出相关建议。

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.不要犯单词拼写错误
项目中发现不少英文单词拼写错误,其实,AS默认情况下对疑似拼写错误的单词都会有波浪线等提示。

 

总之,在编码过程中,一些推荐的更标准的写法或风格总是没有错的,并且,一定的代码洁癖等也是一种很好的编码态度和习惯。

 

posted @ 2016-03-30 12:42  HappyCorn  阅读(1590)  评论(0编辑  收藏  举报