最近看了两本书《代码整洁之道》和《高效程序员的45个习惯敏捷开发修炼之道》的一些体会。
希望能和各位前辈交流一下。个人认为遵守一下几点就能写出不错的程序。
编码原则
1.让代码比你来的时候更干净,每次签入的代码都比签出的时候干净。
2.代码要清晰表达意图,用代码解释代码。
3.代码要有层次感。
4.类应该只有一个职责,一个修改原因,并与少数其他类一起协同达成期望的系统行为。
5.异常也是一件事情也是一个职责。
6.写解决日记。
7.警告就是错误,处理掉项目中的每一个警告。
8.提供有用的错误提示。
9.测试代码和普通代码一样重要。
10.别略过小测试。
11.项目管理者要及时的了解项目进度
12.不做超出需求的大设计,做自然简单的方案
编码规范
1.固定变量也要有意义
如 :
if
(state
==
4
)
可以修改为
int
state_close
=
4
if (state == state_close)
if (state == state_close)
2.不用单个字母作为变量名称
如 int i=0 改成 int length=0;
特别不能使用O l 这样的英文字母做完变量。
3.必要的前缀和不必要的前缀
Name可以改为 jobname,标明这个是工作的名称,而非用户名称
s_name这样的前缀是不必要的。谁都知道name是字符类型。
4.不要使用连串的函数
这是一个杯具
new
OrderInfo().Save().getid().toString();
修改为
int
rowid
=
new
OrderInfo().Save().getid()
txt_id.txt = rowid.toString();
txt_id.txt = rowid.toString();
5.异常处理不要打断正常逻辑,如果不处理这个异常就不要捕获他
以下是一个错误的例子
int
orderid
=
0
;
try
{
orderid = Convert.ToInt32(Request.Params[ " orderid " ]);
}
catch {
}
if (billingForm.Address == null )
{
billingForm.Address = Profile.AccountInfo;
}
try
{
orderid = Convert.ToInt32(Request.Params[ " orderid " ]);
}
catch {
}
if (billingForm.Address == null )
{
billingForm.Address = Profile.AccountInfo;
}
6.隐藏您的数据,变量,无用的方法。
private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());
减少公开的方法和变量。
7.函数表达行为
public
IList
<
ItemInfo
>
GetItemsByProduct(
string
productId) {
8.删除死代码,不要注释代码,因为我们有源码管理
9.也不要多余的注释
int
i
=
0
;
//
自增
这样的注释就是不必要的
10.不要传入bool作为参数
protected
void
But_Save(
object
sender, EventArgs e) {
bool _Save = Request.Params[ " rowid " ].ToString().Equals( " -1 " );
Save(_Save);
}
protected void save()
{
if (_Save)
{
// insert...
}
else
{
// update...
}
}
bool _Save = Request.Params[ " rowid " ].ToString().Equals( " -1 " );
Save(_Save);
}
protected void save()
{
if (_Save)
{
// insert...
}
else
{
// update...
}
}
修改为
protected
void
But_Save(
object
sender, EventArgs e) {
bool _Save = Request.Params[ " rowid " ].ToString().Equals( " -1 " );
if (_Save)
{
insert();
}
else
{
update();
}
}
protected void insert()
{
}
protected void update()
{
}
bool _Save = Request.Params[ " rowid " ].ToString().Equals( " -1 " );
if (_Save)
{
insert();
}
else
{
update();
}
}
protected void insert()
{
}
protected void update()
{
}
11.源文件尽量用少的语言