Lazy programming…

I’ve been working alot with web services lately, querying for information and recordsets, applying business logics and then finally displaying it all on a web page. A problem that I need to deal with (it feels like) all the time is empty responses from the service layer.

Sometime the response is null, sometimes not. Sometimes inner collections of a response are empty, null… anyway, it end up with alot of theese:

if (products != null)
{
    foreach (Product product in products)
    {
        // do something with product
    }
}

Doing these if-nulls over and over again made me realize that I needed an NeverNullEnum wrapper, here it is:

public static IEnumerable<T> NeverNullEnum<T>(IEnumerable<T> e)
{
    if (e != null)
        foreach (T obj in e)
            if (obj != null)
                yield return obj;
}

Now, with this nice wrapper function I can reduce my initial code to this:

foreach (Product product in NeverNullEnum(products))
{
  // do something with product
}

- petter

Leave a comment...

Powered by WordPress. Entries (RSS) and Comments (RSS).