Note that there are some explanatory texts on larger screens.

plurals
  1. PONever use Nulls?
    text
    copied!<p>We are currently going through the long process of writing some coding standards for C#.</p> <p>I've written a method recently with the signature</p> <pre><code>string GetUserSessionID(int UserID) </code></pre> <p>GetUserSession() returns null in the case that a session is not found for the user.</p> <p>in my calling code... I say...</p> <pre><code>string sessionID = GetUserSessionID(1) if (null == sessionID &amp;&amp; userIsAllowedToGetSession) { session = GetNewUserSession(1); } </code></pre> <p>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."</p> <p>Immediately I cried shenanigans, as if you return string.Empty you still have to perform some sort of check on the returned value.</p> <pre><code>if (string.Empty == sessionID) </code></pre> <p>However, thinking about this further I would never return null in the case of a Collection/Array/List. I would return an empty list.</p> <p>The solution to this (I think) would be to refactor this in to 2 methods.</p> <pre><code>bool SessionExists(int userID); </code></pre> <p>and</p> <pre><code>string GetUserSessionID(int UserID); </code></pre> <p>This time, GetUserSessionID would throw a SessionNotFound exception (as it should not return null)</p> <p>now the code would look like...</p> <pre><code>if(!SessionExists(1) &amp;&amp; userIsAllowedToGetSession)) { session = GetNewUserSession(1); } else { session = GetUserSessionID(1); } </code></pre> <p>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.</p> <p>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.</p> <p>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?)</p> <p>Thanks in advance,</p> <p>Chris.</p> <p>=====</p> <h1>Thanks everyone! LOTS of very interesting discussion there.</h1> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload