少写代码就是好代码
我常常看到项目中,有像下面这样的代码:
[code lang="cpp"]
bool bVisible = (FLAG_SHOW == strValue) ? true : false;
[/code]
其实,这算是好的情况了,如果你跟他说这个代码可以写得更简单些:
[code lang="cpp"]
bool bVisible = (FLAG_SHOW == strValue);
[/code]
他可能会跟你争辩,说加上true/false的写法更容易理解。这就难说了,因为是否容易理解是个仁者见仁智者见智的问题,说不定还有审美趣味的因素,而我真的没有更好的理由说服他,毕竟,这只是个微不足道的单行代码而已。
下面的if...else语句与此类似,每次看到它我都要强忍住随手改之的冲动。
[code lang="cpp"]
if (<bool表达式>) {
return true;
} else {
return false;
}
[/code]
少写代码意味着不写不必要的代码。避免坏代码最好的方法就是少写代码。少写代码往往比多写代码需要更多的经验和觉悟。比如让你对一组浮点数进行排序:
[code lang="cpp"]
void sort(float* values, size_t size);
[/code]
最简单的方法就是使用STL的sort():
[code lang="cpp"]
void sort(float* values, size_t size) {
std::sort(values, values + size);
}
[/code]
这样的代码再好不过了。前提是你首先得了解STL(经验),其次要能抑制住重新发明轮子的冲动(觉悟)。
看一个我们项目中的例子,下面这个函数替换子字符串:
[code lang="cpp"]
std::string replace(const std::string & src,const std::string & oldstr,const std::string & newstr)
{
size_t pos = 0;
std::string buffer = src;
std::string::size_type newlen = newstr.length();
std::string::size_type oldlen = oldstr.length();
while(true)
{
pos = buffer.find(oldstr, pos);
if (pos == std::string::npos) break;
buffer.replace(pos, oldlen, newstr);
pos += newlen;
}
return(buffer);
}
[/code]
我之所注意到这个函数,是因为最近一位同事在重构时对它进行了优化,重构前它是下面这个样子:
[code lang="cpp"]
std::string str::replace(const std::string & src,const std::string & oldstr,const std::string & newstr)
{
std::string buffer=src;
const std::string::size_type oldlen=oldstr.length();
if (oldlen>0)
{
std::string::size_type index=0;
std::string::size_type newlen=newstr.length();
if (newlen)
{
if (newlen<oldlen)
{
if ((index=newstr.find(oldstr))!= std::string::npos)
{
newlen=index;
}
}
}
while ((index=buffer.find(oldstr,index))!= std::string::npos)
{
buffer.replace(index,oldlen,newstr);
index+=newlen;
}
}
return(buffer);
}
[/code]
我想说的是,这个重构做得很不到位。其实对于字符串替换这种问题,肯定有人早就做过了,并且做得很好,比如boost algorithm就提供了replace_all/replace_all_copy。所以,这个函数可以直接删掉,用boost好了。
在我们项目中,重新发明轮子的事情实在是太多了,比如下面这个从字符串转浮点数的函数(应该是从网上拷贝来的):
[code lang="cpp"]
static double string_to_double(const char* s)
{
double val = 0,power = 1;
int i,sign = 1;
for(i=0;isspace(s[i]);i++);
sign=(s[i]=='-')?-1:1;
if(s[i]=='+'||s[i]=='-')
i++;
for(val=0.0;isdigit(s[i]);i++)
val=10.0*val+(s[i]-'0');
if(s[i]=='.')
i++;
for(power=1.0;isdigit(s[i]);i++)
{
val=10.0*val+(s[i]-'0');
power*=10.0;
}
return sign*val/power;
}
[/code]
当然,还有double_to_string,我都不好意思贴出来了。
少写代码不是说可以随便拷贝别人的代码,特别是从网上。再举一个我们项目中的一个例子(靠!你有没有发现我们项目的伟大!?),读取一个文本文件,把内容存在字符串里:
[code lang="cpp"]
bool ReadFile(const std::string& file, std::string& stream)
{
/*
* C version -- read file
*/
// Read file characters line by line(perfect)
FILE* fpin = NULL;
const int maxLen = 180; // Assume the character number of a line is less than 180
char buf[maxLen];
fpin = fopen(file.c_str(), "r");
if (NULL == fpin) return false;
while (!feof(fpin) && fgets (buf , maxLen , fpin)) // Judge the end of file
{
stream += buf;
}
fclose(fpin);
return true;
}
[/code]
这段代码是从网上拷的,连注释都保留原样。"假定每行字符数少于180"这一句特别显眼,这种假设是荒谬的。