有意义的命名
一个好的有意义的命名可以提高阅读代码效率包括:变量
,函数
,参数
,类名
,方法名
等,如何去给它们一个好的命名,一般遵守下面几个命名规则,慢慢地你就会养成一个会命名的好程序员。
1.选择体现本意的词语
int d;
public List<int[]> getThem() {
List<int[]> list1 = new ArrayList<int[]>();
for(int[] x: theList)
if(x[0] == 4)
list1.add(x);
return list1;
}
由上述代码可以看出4个问题:
- theList是什么类型的东西?
- theList中零下标的元素的意义是啥?
- 数字4代表什么意思?
- 如何使用返回的列表?
2.避免使用专有名字以及易误导的词
例1:
int a = 1 ;
int b = java;
int c = Time;
if(l == O) {
a = O1;
}else {
l = 01;
}
- O和0相似,1和l相似
- java属于专有名词
- Time属于Java.util包中的类
3.做有意义的区分
对变量做有意义的区分不能按照顺序进行固化编程:
a1,a2,a3,a4等类似这种如下实例:
public static void copyChars(char a1[],char a2[]) {
for(int i=0;i<a1.length;i++) {
a2[i] = a1[i];
}
}
无法区分a1,a2分别代表什么如果是source,destination就可以明显区分了。
4.使用读得出来的名称
人类长于记忆和使用单词,不要傻乎乎的制造单词,
class DtaRcrd102 {
private Date genymdhms;
private Date modymdhms;
private final String pszqint = "102";
/* .......*/
}
class Customer {
private Date generationTimestamp;
private Date modificationTimestamp;
private final String recordId = "102";
/*...........*/
}
5.使用可搜索的名称
若变量和常量可能在代码中被多次使用,应该赋以便于搜索的名称,名称的长短应和作用域相对应。
const int WORK_DAYS_PER_WEEK = 5;
6.避免不必要的成员前缀
不需要用_m
来标明成员变量
public calss Part {
private String m_des;//The textual description
void setName(String name) {
m_dec = name;
}
}
---------------------------------------------------------------
public class Part {
String description;
void setDescription {
this.description = description;
}
}
7.接口与实现
一般来书接口定义AbstractFactory那么接口的实现为了方便可以定义为AbstractFactoryImp。
8.类名
类名和对象名应该是名词或名词短语,类名不应该是动词,不以数字开头。
9.方法名
方法名应该为动词或是动词短语。属性访问词,修改器,和断言应该根据其值命名,加上get,set,is等等。
10.避免同一个单词用于不同的目的
例如:三层架构中:Dao,Service,Servlert
中
public class Dao {
void add(int args) {
/*....*/
}
}
//---------------------------------
public class Servlert {
Dao dao = new Dao();
void update/apped(int args) {
dao.add(args);
}
}
11.不要添加没用的语境
对于Adress类的实体来说,accountAdress和customerAdress都是不错的名称不过用在类名就不太好了,所以添加有意义的语境相当重要。