I've been reading that the null object pattern will help you to avoid the null checks and null pointer exceptions making your code cleaner to understand.
I have never used it and I find it interesting. "null" won't occupy memory but if I start to replace my null checks with the creation of "default" objects, will this procedure have a negative impact in memory in long term?
ex:
Null Object Pattern
public void DoSomething()
{
User user = this.GetUser(id);
string strDisplayName = user.DisplayName;
}
So, as soon as I go out from the scope of the method, the object will be collected by the GC later. But what if I pass through a loop before going out from scope.
public void DoSomething()
{
users = this.GetAllUsers();
foreach(User user in users)
{
string strAddress = user.Address.DisplayName;
//continue tasks
}
}
Meanwhile in other class
public User GetUser(int id)
{
User user = this.LoadUserFromDB(id);
if(user == null)
return User.CreateNull();
return user;
}
public Address Address
{
get
{
if(this.Address == null)
this.Address = Address.CreateNull();
return this.Address;
}
}
CreateNull will create an object of the type User with nothing special inside
Null check
User user = this.GetUser(id);
string strDisplayName = String.Empty;
if(user != null)
{
strDisplayName = user.DisplayName;
}
Just check if user is not null, so assign the property value. I won't create a "null" object
Thanks in advance.
Aucun commentaire:
Enregistrer un commentaire