CodeSOD: Nullable or Not

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.

[Advertisement] Utilize BuildMaster to release your software with confidence, at the pace your business demands. Download today!

This post originally appeared on The Daily WTF.

Leave a Reply

Your email address will not be published.