O'Reilly logo

Programming C# 4.0 by Jesse Liberty, Matthew Adams, Ian Griffiths

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Returning Error Values

For many years, programmers have written methods that detect errors, and which report those errors by returning an error code. Typically, this is a Boolean value of some kind, with True representing success and False failure. Or you might use either an int or an enum if you need to distinguish lots of different types of errors.

Note

Before we add an error return value, we should remove the code we just added that silently enforces the constraints. We can delete EnsurePlatformSize and any references to it. (Or if you’re following along in Visual Studio and don’t want to delete the code, just comment out all the relevant lines.)

So where are we going to return the error from? Our first instinct might be to put it in the RunFor method, where we suggested earlier; but look at the code—there’s nothing substantive there. The problem actually occurs in Rotate. What happens if we change the Rotate method later so that it depends on different properties? Do we also update RunFor to check the new constraints? Will we remember?

It is Rotate that actually uses the properties, so as a rule of thumb we should do the checking there. It will also make the debugging easier later—we can put breakpoints near the origin of the error and see what is going wrong.

Let’s change the Rotate method and see what happens (see Example 6-6).

Example 6-6. Indicating errors through the return value

private bool Rotate(double duration)
{
    if (PlatformWidth <= 0.0)
    {
        return false;
    } // This is the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required