Monday, May 10, 2010

The goto Statement

The goto statement has it roots back in Basic prior to its arrival in .NET.  The value of the goto statement is the ability to jump around in your code.  Where I find these to be most useful is in cases where you may need to re-run a portion of your code.  Or, you don't want to or can't use a recursive call.


In the example above, I'm calling an important but unpredictable web service.  Let's say that Internet connectivity is spotty and I can't always connect to my web service.

Notice above the code to connect to my service I have put a label (ReAttempt:).  You can use any name you want for your label (aside from a keyword) followed by a colon.

Now, I call my service and attempt to do something.  I've setup my example to return response object with a Failed Boolean property and an error message.  So, my request fails and I determine its due to not being able to connect to the remote server (I parsed the error message for the purposes of the demo and know that's what the message means).  I dispose of my existing web service and tell the program to "goto ReAttempt".  My code will now start back declaring the web service.  Since I increment the maxAttemptCount variable, my next attempt will be attempt 2.  (Unlike say a recursive function, I'm in the same instance of my method and so my variables don't reset, etc.)

So if by the 3rd attempt I can't connect to my service, then I'll throw an exception for my application to handle.

As you can see, I've quickly allowed my application to be fault tolerant and re-try some type of request to a resource without having to write very much code.

No comments:

Post a Comment