views:

180

answers:

5

Possible Duplicate:
GOTO still considered harmful?

I just came across some C# code that had a goto statement in it (which I didn't even know C# supported). I only vaguely remember hearing about goto statements in one of my college classes. I seem to remember my professor saying it should never be used but I don't remember why.

Should I consider rewriting this piece of code or is this unlikely to cause problems?

A: 

Read about Spaghetti Code to understand the problem: http://en.wikipedia.org/wiki/Spaghetti_code

SQLMenace
A: 

This is the original reference for the criticism of goto:

http://userweb.cs.utexas.edu/users/EWD/ewd02xx/EWD215.PDF

Goto promotes spaghetti code, so is very hard to understand and debug.

Merlyn Morgan-Graham
A: 

Take time and read:

Go To Statement Considered Harmful

Justin Niessner
+1  A: 

There are a few issues with goto. One is that it is difficult to see how the code flows. It is easier to see an if-block because of the curly braces, but a goto hides that from you. Also, while and if are also essentially gotos, but they help explain why you are jumping back and forth in your code. With a regular goto that you have to piece together yourself.

As an excercise try writing some code for calculating the fibonacci sequence and see how hard it is to read when you are done.

If you are going to be working on that code then I would recommend writing some unittests and rewriting it. Otherwise, just let it be.

All that said, sometimes, for performance reasons, it 'may' be appropriate to use a goto.

ArtB
A: 

It's not that goto in of itself is bad; it's that using goto when the same logic can be more clearly expressed in another way is bad. It can make the code very hard to follow and makes maintenance hard. Just go and look at some programs in Basic from the Bad Old Days as an example.

In my opinion, in a modern language like C# we should never have a need for goto in normal circumstances. If I find myself using it, it's usually a sign that I need to rethink my logic --- there's almost certainly a clearer way of expressing the same code using normal code flow statements.

That said, there are special purposes for which goto can be extremely useful (and I find myself getting annoyed at languages that don't have it). I mostly use it in C for breaking out of multiple levels of loops, or for error handling; I believe that C# has language features that mean you don't have to do this. (It's also really useful when producing autogenerated code, but that's not something most people encounter in real life.)

There's also another problem with goto, which is purely political: a lot of people hate it, and using it in code, even if justified, may cause issues. If this is assignment code, then yes, rewrite it, or you're likely to get marked down. Otherwise I'd be inclined to leave it in until the next time you need to do maintenance on that section.

David Given