API's that Suck

March 6, 2009

Operator Overloads Done Correctly

Filed under: Uncategorized — Grauenwolf @ 9:53 pm

APIs that suck lead to subtle errors or overly complicated code. Here is an example of one such API for checking the OS version.

The wrong way.

bool SupportsTaskProgress()
{
    if (Environment.OSVersion.Version.Major >= 6)
    {
        if (Environment.OSVersion.Version.Minor >= 1)
        {
            return true;
        }
    }
    return false;
}

The “surprisingly hard way”.
bool SupportsTaskProgress()
{
    if (Environment.OSVersion.Version.Major >= 6)
    {
        if (Environment.OSVersion.Version.Major == 6)
        {
            if (Environment.OSVersion.Version.Minor >= 1)
            {
                return true;
            }
            return false;
        }
        return true;
    }
    return false;
}

Fortunately in this case, this isn’t an “API that Sucks”. Rather, the solution is surprisingly simple.
bool SupportsTaskProgress()
{
    return (Environment.OSVersion.Version >= new Version(6,1);
}

That’s it folks. All that nonsense just melts away with the help of a simple operator overload.

Advertisements

1 Comment »

  1. In the last function- syntax error: unmatched parentheses.

    Otherwise, nice article. Operator overloading can make things a lot simpler if done right.

    Comment by Harry — March 7, 2009 @ 12:43 am


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: