Thursday, October 14, 2010

Valid use of GOTO?!

I think I may well have come across a valid use of GOTO...
I'm thinking about fault tolerance - perhaps you have a dodgy wireless connection and you want to poll a server once a day by calling a webservice. What happens if that one time a day you go to call the service there are communication problems? The following code adds some fault tolerance for a situation like this.


int limit = 5;
int attempts = 0;

start:
attempts++;

try
{
service.SomeMethod();
}
catch (WebException ex)
{
if (attempts < limit) goto start;
throw;
}


2 comments:

  1. I dont buy into the whole "goto should never ever be used" philosophy, however using goto often leads to code that is hard to follow, although in this example it is quite easy to follow. However what you are doing here can be achieved in various other ways without using goto, such as a while statement:

    int limit = 5;
    int attempts = 0;

    while(attempts < limit)
    {

    try
    {
    attempts++;
    service.SomeMethod();
    break;
    }
    catch (WebException ex)
    {
    throw;
    }
    }

    ReplyDelete
  2. Yeah that is true - good example. I guess the point was showing a potential place where GOTO could be used...

    Thanks for the comment.

    ReplyDelete