We are currently going through the long process of writing some coding standards for C#.
I've written a method recently with the signature
string GetUserSessionID(int UserID)
GetUserSession() returns null in the case that a session is not found for the user.
in my calling code... I say...
string sessionID = GetUserSessionID(1)
if (null == sessionID && userIsAllowedToGetSession)
{
session = GetNewUserSession(1);
}
In a recent code review, the reviewer said "you should never return null from a method as it puts more work on the calling method to check for nulls."
Immediately I cried shenanigans, as if you return string.Empty you still have to perform some sort of check on the returned value.
if (string.Empty == sessionID)
However, thinking about this further I would never return null in the case of a Collection/Array/List. I would return an empty list.
The solution to this (I think) would be to refactor this in to 2 methods.
bool SessionExists(int userID);
and
string GetUserSessionID(int UserID);
This time, GetUserSessionID would throw a SessionNotFound exception (as it should not return null)
now the code would look like...
if(!SessionExists(1) && userIsAllowedToGetSession))
{
session = GetNewUserSession(1);
}
else
{
session = GetUserSessionID(1);
}
This now means that there are no nulls, but to me this seems a bit more complicated. This is also a very simple example and I was wondering how this would impact more complicated methods.
There is plenty of best-practice advise around about when to throw exceptions and how to handle them, but there seems to be less information regarding the use of null.
Does anyone else have any solid guidelines (or even better standards) regarding the use of nulls, and what does this mean for nullable types (should we be using them at all?)
Thanks in advance,
Chris.
=====
Thanks everyone! LOTS of very interesting discussion there.
I've given the answer to egaga as I like thier suggestion of Get vs Find as a coding guideline, but all were interesting answers.