HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Helper class for Null and Empty checks

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
checkshelpernullemptyforandclass

Problem

I have some static helper class:

public static class Helper
{
    public static bool IsNull(this T value) where T : class
    {
        return (value == null);
    }

    public static bool NotNull(this T value) where T : class
    {
        return (!value.IsNull());
    }

    public static bool IsNullOrEmpty(this string value)
    {
        return string.IsNullOrEmpty(value);
    }

    public static bool NotNullAndNotEmpty(this string value)
    {
        return (!value.IsNullOrEmpty());
    }

    public static bool NotNullAndNotEmpty(this ICollection value)
    {
        return (value.NotNull() && (value.Count > 0));
    }

    public static bool IsNullOrEmpty(this ICollection value)
    {
        return (!value.NotNullAndNotEmpty());
    }
}


It is comfortable (habit) for me to use this helper, but I am not sure that it is correctly (worth it). How about performance? Are there any other reasons to not use it?

Solution

This gets to be a sticky point. There are those who will argue fervently that an extension method should never work on a null reference, and there are those who are fine with that.

Personally, I don't mind extension methods on null if the name is a clear indicator that null is a possibility (like IsNullOrEmpty) but as I said, that's my opinion and may not match others.

Don't worry about the performance, method calls are not a serious impact and check methods like this eliminate some of the readability concerns over compound expressions when maintaining the code. After all, that's what string.IsNullOrEmpty() does, but it does it through a static method instead of an extension method.

So the only concern, really, you may get push back that these are extension methods as opposed to ordinary static methods, but you'll get differing opinions on whether calling an extension method on null is bad/okay.

One could argue Microsoft disallows LINQ extension methods on null sequences, but then again Microsoft also doesn't disallow extension method calls on a null source in general.

So, the choice is yours, I don't have an issue with them since the names clearly indicate null is an accepted possibility, but I can see both sides of the argument.

On a side note, I'd keep your naming consistent:

  • NotNull -> IsNotNull



  • NotNullAndNotEmpty -> IsNotNullAndNotEmpty

Context

StackExchange Code Review Q#6602, answer score: 10

Revisions (0)

No revisions yet.