Nullable Type Abuse

So, I came across a particularly annoying code snippet the other day which leads me to believe that maybe nullable types are not as easy to understand as I previously thought.  Or, perhaps it’s an issue understanding implicity typed variables.  Or, maybe it’s just careless programming.

Here, thing.DbNumber is a nullable int.  I really don’t know what the thought was.  The programmer is checking for null and then returning null.  Then, they are using ToString() presumably because they didn’t know what to pass to Convert.ToInt32 in order to get the integer return value that they wanted, when of course, none of that is needed.

Code scrubbed to protect the guilty:

public int? GetSomeIntValue(List<int> lookupIds)
{
    
var dbNumber = (from thing in DataContext.Things
                        
where lookupIds.Contains(thing.LookupId) && (thing.DbNumber.HasValue)
                        
select thing.DbNumber).FirstOrDefault();

    if (dbNumber == null)
    {
        
return null;
    }

    return Convert.ToInt32(dbNumber.ToString());
}

 

 

Which could have just been:

public int? GetSomeIntValue(List<int> lookupIds)

{

return (from thing in DataContext.Things

             where lookupIds.Contains(thing.LookupId) && (thing.DbNumber.HasValue)
              
select thing.DbNumber).FirstOrDefault(); 

}

For me, this may be a teachable moment or time to cut ties (depending on the pay rate for the person responsible).  In this particular case, the programmer has already moved on to another company.  So, I’ll never know what the original thought was, or what the true level of misunderstanding was.

Rss Feed