資料存取方法回傳 IEnumerable<Customer>,若直接 .First() 會在結果為 null 時拋出 NullReferenceException。若在每個方法中重複撰寫 null 檢查,程式碼冗長且難以維護。
定義泛型擴充方法統一處理驗證邏輯:
public static class EnumerableExtensions
{
public static IEnumerable<T> ValidateNotNull<T>(this IEnumerable<T> source, string errorMessage)
{
if (source == null)
throw new MyException(errorMessage);
return source;
}
}
使用時:
var customers = new CustomerDAL().FindCustomers(Role.Admin).ValidateNotNull("找不到客戶資料");
var first = customers.First();
優點:集中驗證邏輯、減少重複、提高可重用性。亦可搭配 Null Object Pattern 進一步簡化。