好:
void SavePhoneNumber ( string phoneNumber )
{
// Save the phone number.
}
不好: // This method will save the phone number.
void SaveData ( string phoneNumber )
{
// Save the phone number.
}
|
好:
// Save the address.
SaveAddress ( address );
// Send an email to the supervisor to inform that the address is updated.
SendEmail ( address, email );
void SaveAddress ( string address )
{ // Save the address.
// ...
}
void SendEmail ( string address, string email )
{
// Send an email to inform the supervisor that the address is changed.
// ...
}
|
不好:
// Save address and send an email to the supervisor to inform that the address is updated.
SaveAddress ( address, email );
void SaveAddress ( string address, string email )
{
// Job 1.
// Save the address.
// ...
// Job 2.
// Send an email to inform the supervisor that the address is changed.
// ...
}
|
好:
int age; string name; object contactInfo; 不好: Int16 age; String name; Object contactInfo; |
好:
enum MailType
{
Html,
PlainText,
Attachment
}
void SendMail (string message, MailType mailType)
{
switch ( mailType )
{
case MailType.Html:
// Do something
break;
case MailType.PlainText:
// Do something
break;
case MailType.Attachment:
// Do something
break;
default:
// Do something
break;
}
}
|
void SendMail (string message, string mailType)
{
switch ( mailType )
{
case "Html":
// Do something
break;
case "PlainText":
// Do something
break;
case "Attachment":
// Do something
break;
default:
// Do something
break;
}
} |
别把成员变量声明为 public 或 protected。都声明为 private 而使用 public/protected 的Properties.
注释
异常处理
好:
void ReadFromFile ( string fileName )
{
try
{
// read from file.
}
catch (FileIOException ex)
{
// log error.
// re-throw exception depending on your case.
throw;
}
}
|
void ReadFromFile ( string fileName )
{
try
{
// read from file.
}
catch (Exception ex)
{
// Catching general exception is bad... we will never know whether it // was a file error or some other error. // Here you are hiding an exception. // In this case no one will ever know that an exception happened. return ""; } } |
原贴: http://tb.blog.csdn.net/TrackBack.aspx?PostId=66467 (责任编辑:铭铭)
内容导航





















