Wednesday, September 17, 2008

Predictability in APIs

So this is a minor rant about something that bothers me in C# that I felt like sharing over lunch.  First, I'd like to make the obligatory disclaimer that I actually like C# quite a bit.  It's a close third behind Common Lisp on my list of language love.

The problem I have, though, is that functions that return objects may actually return null and that this is not reflected in the type system.  I find this especially frustrating because they're so close to the right track with the nullable types.

If you ever play with LINQ to SQL you'll undoubtably come across nullable types.  If your database has a column of type INT, but nulls are allowed, LINQ doesn't give you a type int for that column:  it gives you type int?, which is really just the .NET equivalent of Maybe Int.  You can't just willy nilly pretend you have an int when you may not because this gets caught as a type error.

Functions that return objects, on the other hand, don't do this because null is a valid assignment to any variable of an object type.  This bugs the hell out of me because you can't tell just by looking at type of a function whether or not there are circumstances where it will return null instead of a 'real' object.  This means that I'll either get bitten on the patootie at some point when a function I thought never returned null actually does, or I need to preemptively wrap try's around all over the place as some form of voodoo to ward off bad spirits.

My basic point is predictability.  I want to be able to use a library in the most naive & dumb way as possible and still not have it blow up in my face.  This is one thing I thing Haskell definitely gets right with functors such as Maybe or Either.


X said...

I hear ya. This drives me absolutely crazy. The thing that sucks more is that there's already a solution in the form of Spec#, but the C# team doesn't seem to be interested in integrating it into the mainline language.

Antoine said...

How much C# do you get to do at Clarity?

Most customer systems are in PHP, right?