好:
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 ""; } } |

