Article 5ZHHS CodeSOD: Nullable or Not

CodeSOD: Nullable or Not

by
Remy Porter
from The Daily WTF on (#5ZHHS)

Nullable types, at least in theory, make our code simpler and easier to maintain. If nothing else, we know when there's a risk of a null value, and can handle it with some grace. At least, that's how it works if we understand what they do.

Boaz's co-worker knows that nullables are valuable, but doesn't quite get it.

public ulong? ParentOpinionId{ get { return DbAdapter.Parent_Opinion; } set { DbAdapter.Parent_Opinion = value.Value; }}

This is a pretty basic C# getter/setter, and it advertises itself as accepting nullable unsigned longs. And, sure enough, the database field it wraps also supports null values. So the signature advertises that it accepts nulls, the persistence layer supports nulls, but this setter doesn't.

Specifically, value.Value on a null value throws an exception. This could be solved easily by just... not trying so hard. Parent_Opinion = value solves this problem perfectly. That's the thing about this- the developer did extra work to get to the wrong result.

buildmaster-icon.png [Advertisement] Utilize BuildMaster to release your software with confidence, at the pace your business demands. Download today! TheDailyWtf?d=yIl2AUoC8zA
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