其中有一點我覺得蠻重要的
不要回傳null
與其回傳null不如回傳一個special case
這樣呼叫這個class的人就不需要去做 if(xx ==null)的判斷
也不會出現 NullPointerException 以下是範例
abstract class EmployeeData
{
protected string name;
protected string birthday;
protected string address;
public string GetName()
{
return name;
}
}
class Ted : EmployeeData
{
public Ted()
{
name = "Ted";
birthday = "1009";
address = "Taipei";
}
}
class NullEmployeeData : EmployeeData
{
public NullEmployeeData()
{
name = "";
birthday = "";
address = "";
}
}
class EmployeeList
{
public EmployeeData GetData(string name)
{
switch (name)
{
case "Ted":
return new Ted();
default:
return null;
}
}
}
class EmplyeeListBetter
{
public EmployeeData GetData(string name)
{
switch (name)
{
case "Ted":
return new Ted();
default:
return new NullEmployeeData();
}
}
}
class Program
{
static void Main(string[] args)
{
EmployeeData employeedata;
EmployeeList badEmployeeList = new EmployeeList();
employeedata = badEmployeeList.GetData("Marry");
if (employeedata!=null)
employeedata.GetName();
EmplyeeListBetter betterEmployeeList = new EmplyeeListBetter();
employeedata = betterEmployeeList.GetData("Marry");
employeedata.GetName();
Console.ReadKey();
}
}
上面的範例說明了當 user想要去Get Marry的資料時 系統內並沒有這個資料
badEmployeeList return 了 null
然而 betterEmployeeList 回傳了 NullEmployeeData這個物件
這樣寫的好處是就算user沒有做 if (employeedata!=null) 這個判斷式
也不需要擔心 NullPointerException 的發生 系統還是可以繼續 run 下去
沒有留言:
張貼留言