NotNull Method Extension

04.10.2010 21:23Comments
My friend blogged about one his favorite method extensions for applying an action to a collection here. This got me thinking about my favorite method extensions, and here's one I'd actually like to share. There are classes that are meant to hold a certain state, they may not have logic in it, and they usually have a very simple instantiation logic (or none). These classes are known as DTO (data transfer objects), and a very common DTO is the DataContract on WCF services. It's a good practice to wrap a certain request inside a Message (DTO), and the parameters of the operation in a Request (another DTO). For example, here is how we could call a CancelOrder operation:
var service = new OrdersService();
var message = new CancelOrderMessage();
var request = new CancelOrderRequest();
var orderId = "123456XX";
request.OrderId = orderId;
message.Body = request;
service.CancelOrder(message);
From the service operation point of view, we are only interested in the OrderId, but still we would have to check for the message not being null, and the request not being null and finally validate if we have a valid order id. With these two simple method extensions: Snippet
    public static class Extensions
    {

        public static bool IsNotNullOrEmpty(this string from)
        {
            if (from == null)
                return false;
            else
                return from.Trim().Length > 0;
        }

        public static T NotNull<T>(this T from) where T : class, new()
        {
            if (from == null)
                return new T();
            else
                return from;

        }
    }
We can now check for a valid order id like this: Snippet
        public CancelOrderResponseMessage CancelOrder(CancelOrderMessage message)
        {
            if (message.NotNull().Body.NotNull().OrderId.IsNotNullOrEmpty())
            {
                //cancel order.
            }
        }

comments powered by Disqus