@DevWiki
2015-07-02T13:11:27.000000Z
字数 2790
阅读 1322
CleanCode
更多内容详见:CleanCode笔记
反例:
int w;int h;public int fun(){return w*h;}
从代码中看不出任何信息,w和h是何含义?
不如改为:
int width;int height;public int calculateArea(){return width*height;}
这样没有注释也能看懂代码的意图.
如果仅仅给你一个accountList,很容易让人误以为是一个账户类表.
Account[] accountList;//此处又很长的代码accountList = getAccountList(); //你能辨别出accountList是什么吗?
为了避免误导,应该改为:
Account[] accountGroup;//此处又很长的代码accountGroup = getAccountGroup(); //你能辨别出accountGroup是什么吗?
现在有三个类:
public class Account{}public class AccountInfo{}public class AccountData{}
仅仅从类名你能区分这三个类有什么区别吗?
既然要区分他们就应该取一个有意义的名称区分.
有的程序员喜欢用自造的词语,比如:
public void lxmcreateData(){//代码内容}
你能读出来上面函数的名称吗?函数本意是想创造数据,但是lxm是什么意思?翻到类头注释才知道,作者叫Lixiaoming.
如果改为下面这样,是不是更好读呢?
public void createData(){//代码内容}
经常在代码中可以见到类似a,b,w,h,e等这样的命名,而且同一个类中多次出现,特别是作为临时变量的i,j,k.当想查找时,编辑器也不知道你想要查找哪一个.
例如:
private List<Student> studentList;public float getMathAvgScore(){float s = 0;for(int i = 0; i < studentList.size(); i++){s = s + studentList.get(i).getMathScore();}float a = s/studentList.size();return a;}public float getAvgScore(){float s = 0;for(int i = 0; i < studentList.size(); i++){s = s + studentList.get(i).getTotalScore();}float a = s/studentList.size();return a;}
如果改为下面这样,你觉得哪个更好呢?
private List<Student> studentList;public float getMathAvgScore(){float mathTotalScore = 0;for(Student student : studentList){mathTotalScore = mathTotalScore + student.getMathScore();}float mathAvgScore = mathTotalScore/studentList.size();return mathAvgScore;}public float getAvgScore(){float totalScore = 0;for(Student student : studentList){totalScore = totalScore + student.getTotalScore();}float avgTotalScore = totalScore/studentList.size();return avgTotalScore;}
什么是命名编码?就像前面的lxmcreateData()函数名就是命名编码.
就像前面的lxmcreateData()一样,该类中存在很多类似lxmXXX的函数,变量.
在命名时应避免使用这样的前缀
使用Eclipse时,我们生命一个变量时,往往会给出命名提示:
String nameString
这是很不必要的,不需要在变量后面都带上该变量的类型,除非该变量的命名不足以表现出其类型.
每一个变量应明确其含义,不要让人在大脑中给其一个含义映射!
比如:
for(int i = 0; i < studentList.size(); i++){s = s + studentList.get(i).getMathScore();}
与下面相比:
for(Student student : studentList){mathTotalScore = mathTotalScore + student.getMathScore();}
下面的代码更直观,而上面的代码会让人去记住s代表什么含义.
类名和对象名应该是名词活名词短语,如Customer,WikiPage,Account,AccountParser等,避免使用Manager,Processor,Data,Info等这样的类名.类名不应该是动词.
方法名应该是动词或动词短语,如postPayment,deletePage或save.
属性访问与修改和断言应该根据其命名,并依照javabean标准加上get,set,is前缀.
如:
String name = person.getName();person.setName("Jack");player.isPlaying();
命名应该是直来直去的名称,不要使用一些俗语或俚语(不要以为别人都和你一样英文阅历很深).
别用whack()来表示kill().
如果你要写一个控制类,比如控制音频类.如果使用了AudioManager就不要在使用AudioController.否则别人是弄不懂二者之间区别.
比如add一词又很多含义,不要为了保持方法名一致就命名为add.
把单个条目放到集合中可以用put,不要用add;
把单个条目放大数据库中可用insert,不要用add.
有时同一个事物在不同领域有不同的含义,在写代码的过程中要用和项目相关领域的词汇命名.
尽量使用问题所在的领域的词语来命名,这样可以明确代码解决问题的领域.
有些词语会有一词多义的现象,如果找不到代替该词更好名称,那么至少给该词添加能明确含义的语境.
就像前面的lxmcreateData()一样,前缀lxm是没有任何含义的.一定不要附带这样的没有意义的语境.