在開發業務層數據的時候,我總是擔心數據層給我返回的對象實例為null。
所以,每次使用數據層返回的對象實例我都要判斷下是否為null
UserRepository respository = new UserRepository();
var user = respository.GetById("008");
if (user!=null)
{
user.SayHello();
}
雖然這樣是避免了因為空值引發異常的問題,但是這樣增加了客戶端代碼的很多工作量,而且一旦某個地方忘記判斷,我的代碼就會出現空異常;為了解決這個問題,我們引入了空對象模式,將空對象扼殺在數據的源頭
public interface IUser
{
void SayHello();
}
public class User : IUser
{
public string Id { get; private set; }
public User(string id)
{
Id = id;
}
public void SayHello()
{
Console.WriteLine("{0}:Hello", Id);
}
}
public class NullUser : IUser
{
public void SayHello()
{
//對於空對象實例來說,它的任何方法都應該不用做任何處理
}
}
public class UserRepository
{
private ICollection<User> users;
public UserRepository()
{
users = new List<User>() {
new User("001"),
new User("002"),
new User("003"),
new User("004"),
new User("005")
};
}
public IUser GetById(string userId)
{
IUser user = users.SingleOrDefault(s => s.Id == userId);
if (user == null)//檢查User的實例是否為null,如果是返回一個特殊的Iuser
{
user = new NullUser();
}
return user;
}
}
在上面的代碼中,我們在數據層中直接就判斷了user實例是不是為null,如果為null,就返回一個用作null值處理的對象實例
static void Main(string[] args)
{
UserRepository respository = new UserRepository();
var user = respository.GetById("008");
user.SayHello();
user = respository.GetById("003");
user.SayHello();
Console.ReadLine();
}
現在媽媽再也不用擔心我調用數據層的對象實例報空引用了,當然這種方式並不僅限於在數據層使用