Thursday, 8 November 2012

Empty Collection Pattern

I'm sure this is likely a pattern that is called something else, but I tend to use this quite a lot especially in Application Facade layers where I really don't want to return nulls. I generally use LIST rather than IEnumerable as this is more useful for counts etc..

I have always been amazed at how many applications crash when they don't have data in them, i.e. an empty database table produces exceptions because an objection collection call returns NULL. This pattern will prevent this (up to a point).


  • Calling layers don't have to worry about NULLS
  • Its simply and it works without creating to much clutter.
  • Empty collections are easy to work with
  • If you say you are returning a collection you better return one, even if it is empty.

        public static List GetPeople()
            //  CREATE AN EMPTY LIST
             var result = new List();

            // GO TO DB AND GET RESULTS
            var connectionString = "mongodb://localhost/?safe=true";
            var server = MongoServer.Create(connectionString);
            var database = server.GetDatabase("test");
            var collection = database.GetCollection("people");
            var getall = collection.FindAll().ToList();

             // Add results if any to the collection

            return result;

No comments:

Post a Comment

Comments are welcome, but are moderated and may take a wee while before shown.