Article 4N6AX CodeSOD: Nullable Knowledge

CodeSOD: Nullable Knowledge

by
Remy Porter
from The Daily WTF on (#4N6AX)

You've got a decimal value- maybe. It could be nothing at all, and you need to handle that null gracefully. Fortunately for you, C# has "nullable types", which make this task easy.

Ian P's co-worker made this straightforward application of nullable types.

public static decimal ValidateDecimal(decimal? value){if (value == null) return 0;decimal returnValue = 0;Decimal.TryParse(value.ToString(), out returnValue);return returnValue;}

The lack of indentation was in the original.

The obvious facepalm is the Decimal.TryParse call. If our decimal has a value, we could just return it, but no, instead, we convert it to a string then convert that string back into a Decimal.

But the real problem here is someone who doesn't understand what .NET's nullable types offer. For starters, one could make the argument that value.HasValue() is more readable than value == null, though that's clearly debatable. That's not really the problem though.

The purpose of ValidateDecimal is to return the input value, unless the input value was null, in which case we want to return 0. Nullable types have a lovely GetValueOrDefault() method, which returns the value, or a reasonable default. What is the default for any built in numeric type?

0.

This method doesn't need to exist, it's already built in to the decimal? type. Of course, the built-in method almost certainly doesn't do a string conversion to get its value, so the one with a string is better, is it knot?

otter-icon.png [Advertisement] Continuously monitor your servers for configuration changes, and report when there's configuration drift. Get started with Otter today! TheDailyWtf?d=yIl2AUoC8zAQoLYjZYFK6c
External Content
Source RSS or Atom Feed
Feed Location http://syndication.thedailywtf.com/TheDailyWtf
Feed Title The Daily WTF
Feed Link http://thedailywtf.com/
Reply 0 comments