In day by day work, a developer has to branch their logic checking for null, and it is obvious that checks for null are the most common checks in most projects.
The checks can be avoided by using Null Object Pattern or Specification Pattern both well documented by Martin Fowler. But the Null Object pattern can’t be reused everywhere, so still in some cases the null checks will exists. Specification pattern I consider is quite heavy just for null checks.
Let’s suppose that in UI layer we should display a list of users which have LastLoginDate null and has a Role assigned (Role property is not null):
void DisplayUserList()
{
IList<User> userList = UserService.GetAll();
if (userList == null && userList.Count > 0)
{
return;
}
foreach (User user in userList)
{
if (user.LastLoginDate == null && user.Role != null)
{
DisplayUser(user);
}
}
}
So as we can see there are boring and not readable checks, we can perform a small but useful refactoring and make a little bit more readable (and easier to type J ) by introducing few extension methods:
static bool IsNull(this object obj)
{
return obj == null;
}
static bool IsNullOrEmpty<T>(this ICollection<T> list)
{
return list.IsNull() || list.Count == 0;
}
static bool IsNotNull(this object obj)
{
return !obj.IsNull();
}
Now the code looks as follows:
void ExtentionDisplayUserList()
{
IList<User> userList = UserService.GetAll();
if (userList.IsNullOrEmpty())
{
return;
}
foreach (User user in userList)
{
if (user.LastLoginDate.IsNull() && user.Role.IsNotNull())
{
DisplayUser(user);
}
}
}
The conclusion is that extension methods not only can extend objects but also our imagination J “how we can improve our code”.
Note: The code above is not intended to show how is better to design but only to show how extension method can increase readability.
Thanks for your reading J