下面是ArrayList的代码片段,它接受用户提供的'initialCapacity'或默认值10.我的问题 - 为什么10不是静态常数?我想在代码中重复多次变量时会使用常量.我对吗 ?
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
}
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this(10);
}
Run Code Online (Sandbox Code Playgroud)
常量用于为变量命名.
你可以称之为" DEFAULT_INITIAL_CAPACITY"
一个好的程序,是一个你可以像故事一样阅读的程序.
这是一个代码片段,例如:
char * find_type(char *str,int *type){
str = trim_leading_space(str);
if(*str == SLASH_SIGN){
str++;
}else{
display_error(BAD_TYPE_FORMAT, str);
}
str = trim_leading_space(str);
*type = convert_to_zero_or_one(str[0]);
if(*type == NO){
display_error(BAD_TYPE_FORMAT, str);
}else {
str++;
}
return str;
}
Run Code Online (Sandbox Code Playgroud)
代码是用C语言编写的,但仍然证明了我的观点.
这是" BAD_TYPE_FORMAT" 的定义
#define BAD_TYPE_FORMAT 34
Run Code Online (Sandbox Code Playgroud)
如果我把它留下来34,当有人来编辑我的代码时,他不知道为什么我写了34个.但它只是错误的下一个索引,来自一长串可能的错误.