【android】Android项目代码优化的几点建议
2017-05-11 本文已影响241人
当时不是寻常
要想写出高效优秀的代码,这就要求我们平常在开发过程中要规范自己的开发行为,只要能优化的地方就尽量都去优化,千里之行始于足下,一点一点的改变,最终能够让自己树立良好的意识。
1、代码中不要直接用具体的字符串进行比较,写在常量文件中。


2、没必要的空行进行删除。
3、将某些代码提取成公共方法,简化代码结构(HomeActivity),另外在一些控制View显示隐藏的地方也可以写成公共方法,然后通过传入控件id形式控制其显示隐藏。


4、要理解不同Context的生命周期区别,ApplicationContext生命周期与项目是一致的,而Activity则不是,要避免长生命周期对象持有对短生命周期对象的引用。
5、避免在for循环当中用list.size()等形式,应当用变量代替list.size()。

6、避免在项目中出现e.printStackTrace(),应将日志进行记录上传

7、针对java变量命名,除了在布局文件中使用_分割,其他地方尽量还是以小写字母开头,让变量名通俗易懂的形式。


8、代码中该有空格的地方要用空格分割,便于阅读

9、在多个变量叠加的时候,不要使用String的+连接,用StringBuffer和StringBuilder连接,因为用+连接的话会创建多个对象。

10、在obj可能出现null的情况下慎用toString,应事先进行判断object是否为null。

11、弹出对话框的方法等可以提取出工具类,便于调用

12、尽量避免写重复代码,提取公共部分。

13、代码中出现警告的地方,尽量都解决
14、在Switch语句中,default就是如果没有符合的case就执行它,default尽管并不是必须的,为了统一规范,大家都是加上的好。

15、避免在布局文件中直接写汉字,应提取到strings.xml中。

16、在进行变量命名的时候少用拼音,多用英文单词,如下图英文单词更新应该是update而不是updata,另外版本号不要直接写ban,要改成version比较好。

17、布局文件中有警告的地方应予以解决,大小等值应该写在dimen.xml文件中进行调用

18、代码当中常量字符串要写到配置文件中


19、mipmap和drawable的区别
google 建议大家只把 app 的启动图标放在 mipmap 目录中,其他图片资源仍然放在 drawable 下面。
20、要对新建的类或者方法进行注释说明,便于其他开发人员理解。



21、尽量简化代码结构,该有空格的地方要有空格

可以改成,还有命名不要命名为OtherUtil

22、变量命名尽量用java风格,而不是C、C++,布局文件除外

23、建议写法 1 == model

24、命名规范,常量字符串

25、不要硬解析json数据,建议使用项目中阿里巴巴的fastjson

硬解析不仅效率低,而且如果在response当中有特殊字符未过滤就会出现异常。
26、用foreach代替for循环,尤其是对List能极大地提高效率。

27、将常量声明为static final,这样在编译器就能将常量放到常量池,提高效率。

28、sd卡路径不要写成/sdcard这样的形式。

可以用Environment.getExternalStorageDirectory().getPath()代替
29、可以简化的代码


30、SharedPreference的apply和commit区别

Commit有返回值,是同步方法,apply是异步方法,没有返回值,如果对结果不关心可以使用apply以提高效率。
31、不要给一个方法传入太多的参数

参数太多势必增加了调用出错的概率,也违背了面向对象原则,java讲究一切都是对象,咱们可以把传入的参数用实体类或者bundle传递进去。
32、使用静态内部类而不是非静态内部类。
该篇文章会继续更新,敬请期待。。。。。
如果文章当中有任何不正确的地方,还请广大读者纠正,非常感谢!