How Extension Methods can increase readability

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

 

Published Monday, December 01, 2008 4:16 PM by Artur Trosin
Filed under: , ,

Comments

# re: How Extension Methods can increase readability

Monday, December 01, 2008 11:44 AM by Bryan

Meh, it's not that much easier.  In fact, it's pretty obfuscating because you don't actually know what is being checked for null without looking into the method implementation itself.  This is a dangerous path you go down.

# re: How Extension Methods can increase readability

Monday, December 01, 2008 12:46 PM by Artur Trosin

Hi Bryan,

It’s really good point Thank you for your comments,

To answer  I can say that we already using this kind of stuff in a real project and developers really know how to use and what it means, so I don’t  think here are some problems with obfuscation because it’s lake any other  method with meaningful  name  from infrastructure,  the approach is to introduce a more readable fluency in code and reduce code duplication in case such as userList.IsNullOrEmpty()  because we really often need to retype list == null || list.Count == 0 across the project to branch our logic.

# re: How Extension Methods can increase readability

Monday, December 01, 2008 3:00 PM by Marius

I dont think that making an extension method for the object type is a best practice; on the contrary I think it is bad to define extension methods for object type.

# re: How Extension Methods can increase readability

Monday, December 01, 2008 4:00 PM by Artur Trosin

Hi Marius,

In generally I’m totally agree with the statement “it is bad to define extension methods for object type”,

And making a reusable framework like .NET I would think first to make the decision or not (please read last link to clarify)

But here is special case, the methods are really indented for the any class which derive from object type, is there any type which derive from object but you wouldn’t do null checks?

…and finally the object Extension Methods not introduce some new logic which can be broken over a time but just wrap  “==” logic for readability and fluency as I already mentioned.

What about Extension Methods best practices here is a good post:

blogs.msdn.com/.../extension-methods-best-practices-extension-methods-part-6.aspx

# re: How Extension Methods can increase readability

Tuesday, December 02, 2008 9:16 AM by Scott

I would rather see something like this:

if (user.HasLoggedIn...)

Instead of:

if (user.LastLoginDate.IsNull()

It’s more readable and makes the intent even more clear.

# re: How Extension Methods can increase readability

Wednesday, December 03, 2008 3:41 AM by Tore Vestues

Although I have some minor objections to your examples (for instance be careful about the Law of Demeter), I like your point: Readability.

Readability is one of the foundations of code quality, IMHO. Any technique that helps us improve readability and thus code quality should be embraced. So all in all I really like your post. Keep up the good work!

# re: How Extension Methods can increase readability

Wednesday, December 03, 2008 3:16 PM by Artur Trosin

Hi Tore,

Thank you for your first positive feedback :), and interesting point of view which is a little lesson for me. :)

# re: How Extension Methods can increase readability

Friday, December 19, 2008 6:30 AM by Fabrice Marguerie

> if (userList == null && userList.Count > 0)

I don't think this is going to work...

# re: How Extension Methods can increase readability

Friday, December 19, 2008 8:13 AM by Artur Trosin

Hi Fabrice,

the line not but the line:

>if (userList.IsNullOrEmpty()) - YES :)

If to be serious, thank you, that’s my fault, I've updated the line.

One my school teacher would say in this kind of situation: "I'm just checking if all are attentive" :)

Leave a Comment

(required) 
(required) 
(optional)
(required)