Avoid returning "null" and use the Null Object pattern?
When I build applications and add methods to return a list of objects, I make it robust. So I always return an instance of the list instead or returning null. The reason is because I like the use of Count and also use foreach. I don't want to add extra code to see if the method returns null. For example:
public IList<string> GetCultures() { IList<string> cultures = new List<string>(); //... return cultures; }
Then when I make a call to the GetCultures method I can see if it contains any cultures by using Count, and if I need to list Cultures I can also use foreach without getting a null exception.
IList<string> cultures = GetCultures(); if (cultures.Count > 0 ) //.. foreach (var culture in GetCultures()) //..
If I prefer Robustness before Correctness I return null if I only need to return a single object, for example:
public static Culture GetCulture(string cultureCode) { Culture culture = null; //.. return culture; }
In this case I need to see if the returned object is null or not before using it.
Culture culture = GetCulture(); if (cultures !=null)
I could also throw an exception if the cultureCode could not be located, in that way I will never return null. But I try to avoid throwing exception and use try catch block when I try to get an object. The reason is performance and also skip adding several try catch block in my code.
public static Culture GetCulture(string cultureCode) { Culture culture = null; //Can't locate the culture throw an exception return culture; }
Culture culture = null; try { culture = GetCulture(); } catch { //... }
I only throw an exception when it's really an exception, for example the cultureCode was in a correct format or wasn't specified etc. Everything is based on the type of application, and if Robustness is more important than Correctness. Another solution is to use the Null Object Pattern and always return an instance of an object.
Culture culture = GetCulture();
if (cultures.IsNull)
Or use the Cultures other members and not get a null exception. The Null Object Pattern is also useful if I always want to return a default value. For example if I want to get a Customer and the Customer can't be located, I could return a John Doe ;) I don't use the Null Object Pattern so often in my applications.
What solution do you use or prefer when returning a list or single object and why?