By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,670 Members | 1,554 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,670 IT Pros & Developers. It's quick & easy.

Are gotos truly evil?

P: n/a
I have never used a goto statement in my code, one of the first things I was
told in my software classes a number of years ago was "goto statements are
evil and lead to spagetti code - do not use them".

I absorbed this mantra and tell this to other people and I fully believe in
it. However, I was talking to someone recently and he was saying how much he
loved goto statements and how useful they were and that Microsoft had to
leave them in c# because they were so useful, otherwise why would the
statement be in the language. He does not advocate using them in excess but
uses them to allow himself to create a pattern that allows him to have one
point of exit in a function at the end. I kept trying to convince him that
gotos were not good but he seemed unconvinced by my arguements.

I know one common use people say is for getting out of deeply nested
statements but you can easily do without gotos by using booleans or replacing
sections of code with function calls.

Why if they are so bad is goto still in the language, what are the
acceptable uses of the keyword, there must be some otherwise why is the
statement in the c# language, or is this just a legacy thing to attract
programmers from other languages who are used to gotos?

I can't think of any really valid reason why you would use them but maybe
other people have.
Nov 17 '05 #1
Share this Question
Share on Google+
41 Replies


P: n/a
In message <F9**********************************@microsoft.co m>, Mark R.
Dawson <Ma*********@discussions.microsoft.com> writes
I have never used a goto statement in my code, one of the first things I was
told in my software classes a number of years ago was "goto statements are
evil and lead to spagetti code - do not use them".

I absorbed this mantra and tell this to other people and I fully believe in
it. However, I was talking to someone recently and he was saying how much he
loved goto statements and how useful they were and that Microsoft had to
leave them in c# because they were so useful, otherwise why would the
statement be in the language.
"Rules are for the obedience of fools and the guidance of wise men."
(Douglas Bader)
I can't think of any really valid reason why you would use them but maybe
other people have.


Nor I. If I came across a situation where using goto made sense, I'd
treat it with suspicion, on the grounds that the structure of the code
was probably fundamentally flawed. If, on examination, there wasn't a
better way of writing it, I'd go ahead and use it.

I think the OO mindset of treating long methods with complex flow
control as a code smell probably contributes to a style of programming
in which the issue does not occur.

--
Steve Walker
Nov 17 '05 #2

P: n/a
"Mark R. Dawson" <Ma*********@discussions.microsoft.com> wrote in message
news:F9**********************************@microsof t.com...
I have never used a goto statement in my code, one of the first things I
was
told in my software classes a number of years ago was "goto statements are
evil and lead to spagetti code - do not use them".

I absorbed this mantra and tell this to other people and I fully believe
in
it. However, I was talking to someone recently and he was saying how much
he
loved goto statements and how useful they were and that Microsoft had to
leave them in c# because they were so useful, otherwise why would the
statement be in the language. He does not advocate using them in excess
but
uses them to allow himself to create a pattern that allows him to have one
point of exit in a function at the end. I kept trying to convince him
that
gotos were not good but he seemed unconvinced by my arguements.

I know one common use people say is for getting out of deeply nested
statements but you can easily do without gotos by using booleans or
replacing
sections of code with function calls.

Why if they are so bad is goto still in the language, what are the
acceptable uses of the keyword, there must be some otherwise why is the
statement in the c# language, or is this just a legacy thing to attract
programmers from other languages who are used to gotos?

I can't think of any really valid reason why you would use them but maybe
other people have.


Statements in languages are not evil. However, a statement that so trivial
to misuse is pointless to use. Using a goto just isn't worth it. All of
the developers I know that use 'goto' (and there are only a handful) are
pre-structured programmers first and foremost. They have no desire to learn
to use any of the techniques of OO programming or even good structured
programming. I cannot speak for your co-worker, but from what you describe,
the arguments are similar.

Don't waste your time arguing with these folks. If you have any say in the
matter, don't let them design anything of importance either. They want to
sit in the backwaters of software development... let them. You are not
their keeper. If you get their code, refactor it. Don't go our of your
way, but don't leave junk in the code base if you can safely remove it. In
other words, don't let yourself be held back by the slackers and luddites.
It's not good for the ol' career.

I cannot speak for the designers of C#. I was not involved in any way. In
my opinion, the goto was included to make it easy to port existing code, not
to help bring over the programmers who wrote that code. Those people are
happy to stay behind and I, for one, and happy to let them.

--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
--
Nov 17 '05 #3

P: n/a

"Mark R. Dawson" <Ma*********@discussions.microsoft.com> wrote in message
news:F9**********************************@microsof t.com...
I have never used a goto statement in my code, one of the first things I
was
told in my software classes a number of years ago was "goto statements are
evil and lead to spagetti code - do not use them".


If they had no legitimate uses, programming languages would not include
them.

I find them useful in coding algorithms that are essentially big
state-transition networks. Each block of code represents one state, and
upon a state change, you jump to another block of code.

This is not a common kind of algorithm, of course, but it's a legitimate
one. Naturally, you have to be careful how you code it.

"Gotos are no substitute for if-then-else blocks, for loops, etc." - I
agree.

"Gotos have no legitmate uses" - Falsch.

We don't want to teach knee-jerk programming, where programmers
automatically do one thing because they've been told to, not because they've
considered the alternatives.
Michael Covington
Associate Director, Artificial Intelligence Center
The University of Georgia - www.ai.uga.edu/mc
Nov 17 '05 #4

P: n/a
"Nick Malik [Microsoft]" <ni*******@hotmail.nospam.com> wrote in message
news:kq********************@comcast.com...
Statements in languages are not evil. However, a statement that so
trivial to misuse is pointless to use. Using a goto just isn't worth it.
All of the developers I know that use 'goto' (and there are only a
handful) are pre-structured programmers first and foremost. They have no
desire to learn to use any of the techniques of OO programming or even
good structured programming. I cannot speak for your co-worker, but from
what you describe, the arguments are similar.

Don't waste your time arguing with these folks. If you have any say in
the matter, don't let them design anything of importance either. They
want to sit in the backwaters of software development... let them. You
are not their keeper. If you get their code, refactor it. Don't go our
of your way, but don't leave junk in the code base if you can safely
remove it. In other words, don't let yourself be held back by the
slackers and luddites. It's not good for the ol' career.


Pardon me, but that's a bit frightening to read. Do you actually work for
Microsoft?

If one of my students wrote what you've just written, I'd call him in and
say, "Master the 'goto' statement yourself before you tell other people that
they are stupid for using it. An interesting class of algorithms seems to
be beyond your present knowledge of computer programming."

Knuth uses 'goto' in The Art of Computer Programming.

I don't use them often, but there are one or two 'goto' statements in my
latest and biggest (20,000-line?) object-oriented C# program. There really
are places where 'goto' is better than the alternatives. They're uncommon,
but I see no advantage in being unable to recognize them.

Have you ever programmed in assembly language? There, 'goto' is obligatory,
and you quickly learn how to use it systematically and reliably. Mostly,
you write things that are equivalent to loops or blocks in higher-level
languages, but occasionally, you see that a 'goto' can do something useful
that has no direct equivalent in structured programming.

Slacker? Luddite? Me???

Michael Covington, Ph.D.
Associate Director, Artificial Intelligence Center
The University of Georgia - www.ai.uga.edu/mc
Nov 17 '05 #5

P: n/a
"Michael A. Covington" <lo**@ai.uga.edu.for.address> wrote in message
news:%2****************@TK2MSFTNGP10.phx.gbl...
<snip>
I find them useful in coding algorithms that are essentially big state-transition networks. Each
block of code represents one state, and upon a state change, you jump to another block of code.


I agree,
I have seen truly elegant state machines using goto.
It could have been written with a ton of function calls instead, but at a reduction in performance.
It could have been written with the "goto" stuff inlined, but that would have produced a monolithic
mess.
The "goto" version was highly structured and highly efficient.

This state machine was also written by a knowledgeable programmer who understood the pitfalls.

I have also seen goto abused in the worst possible way.
I did a stint at COBOL programming a few years ago and spaghetti is a nice word for some of that
code.
After failing to wrap my brain around some truly spectacularly illogical Moebius code I had to
restrain myself from seeking out the programmer responsible and removing his taint from the gene
pool.

As a rule of thumb.
GOTOs should only be used by SKILLED programmers who understand the consequences.
Novice programmers should avoid GOTOs at all costs.

That said, I have not needed a single goto in my last few years of C# programming.

My 2 cents
Bill Butler
Nov 17 '05 #6

P: n/a
On Sat, 17 Sep 2005 10:35:02 -0700, "Mark R. Dawson"
<Ma*********@discussions.microsoft.com> wrote:
I have never used a goto statement in my code, one of the first things I was
told in my software classes a number of years ago was "goto statements are
evil and lead to spagetti code - do not use them".

I absorbed this mantra and tell this to other people and I fully believe in
it. However, I was talking to someone recently and he was saying how much he
loved goto statements and how useful they were and that Microsoft had to
leave them in c# because they were so useful, otherwise why would the
statement be in the language. He does not advocate using them in excess but
uses them to allow himself to create a pattern that allows him to have one
point of exit in a function at the end. I kept trying to convince him that
gotos were not good but he seemed unconvinced by my arguements.

I know one common use people say is for getting out of deeply nested
statements but you can easily do without gotos by using booleans or replacing
sections of code with function calls.

Why if they are so bad is goto still in the language, what are the
acceptable uses of the keyword, there must be some otherwise why is the
statement in the c# language, or is this just a legacy thing to attract
programmers from other languages who are used to gotos?

I can't think of any really valid reason why you would use them but maybe
other people have.


THere are a few places where goto can be useful. I had to code one
after about five years of programming, and I got a compile error - "go
to" vs "goto"!

Certainly for a novice the rule of thumb is to avoid them generally in
structured languages.

The classic source for this is "Go To Statement Considered Harmful" by
Edsger W. Dijkstra. See http://www.acm.org/classics/oct95/

rossum

The ultimate truth is that there is no ultimate truth
Nov 17 '05 #7

P: n/a
"Michael A. Covington" <lo**@ai.uga.edu.for.address> wrote in message
news:ef****************@TK2MSFTNGP12.phx.gbl...
"Nick Malik [Microsoft]" <ni*******@hotmail.nospam.com> wrote in message
news:kq********************@comcast.com...
Statements in languages are not evil. However, a statement that so
trivial to misuse is pointless to use. Using a goto just isn't worth it.
All of the developers I know that use 'goto' (and there are only a
handful) are pre-structured programmers first and foremost. They have no
desire to learn to use any of the techniques of OO programming or even
good structured programming. I cannot speak for your co-worker, but from
what you describe, the arguments are similar.

Don't waste your time arguing with these folks. If you have any say in
the matter, don't let them design anything of importance either. They
want to sit in the backwaters of software development... let them. You
are not their keeper. If you get their code, refactor it. Don't go our
of your way, but don't leave junk in the code base if you can safely
remove it. In other words, don't let yourself be held back by the
slackers and luddites. It's not good for the ol' career.
Pardon me, but that's a bit frightening to read. Do you actually work for
Microsoft?


I do not speak for my employer and I'm sure that if there was a single
person who represents Microsoft, that person would likely distance
themselves from me quite readily. :-) I am required by the policy of
Microsoft to declare myself to be an employee in all communications. We are
an opinionated bunch. For every opinion I express here, I can quite easily
find someone inside Microsoft that is happy to disagree with me.

If one of my students wrote what you've just written, I'd call him in and
say, "Master the 'goto' statement yourself before you tell other people
that they are stupid for using it.
Minor correction: I did not call anyone stupid. I did call the folks who
use goto "slackers" and "luddites". That does not make them stupid. Some
of the smartest people I know fail to be motivated to learn good OO
techniques, and adherance to an idea, including the idea that "newer is not
necessarily better," does not imply either ignorance or stupidity. That
said, I will say that no code review that I have sat through wouldn't end in
a shouting match if a 'goto' was left in the code. We have code analysis
tools that will flag the use of the word and will make sure that it shows up
in the review process.
An interesting class of algorithms seems to be beyond your present
knowledge of computer programming."
I maintain that there are no algorithms that REQUIRE this simple structure
(I may be wrong on this point). I gladly concede that there are algorithms
that can be made more efficient with the use of this construct. I have
never actually coded any of them, nor have any of the other folks that I
have worked with. I have written code to run embedded in data
communications devices, code inside the operating system, code in literally
dozens of applications, code in B2B transaction systems, code in B2C
e-commerce web sites, and code in application engines ranging from workflow
to EAI. I have never happened across a single algorithm that REQUIRED the
use of a goto.

Knuth uses 'goto' in The Art of Computer Programming.
According to the following site
(http://en.wikipedia.org/wiki/The_Art...r_Programming), Volume 1 was
published in 1968. Volume 2 in 1969 and Volume 3 in 1972. I would be
surprised if you consider these volumes to represent the complete learnings
of computer science, for to make that statement, you would state that
innovation stopped over 30 years ago.

I have a great deal of respect for Dr. Knuth. He did a great job of
describing algorithms in a simple and clear manner for two generations of
software developers to learn from. However, the needs of simplicity for
teaching an algorithm is not the same as the needs of an organization for
maintaining reliable and trustworthy code.

I don't use them often, but there are one or two 'goto' statements in my
latest and biggest (20,000-line?) object-oriented C# program. There
really are places where 'goto' is better than the alternatives.
That depends on what you mean by 'better.'

I am involved in the creation of systems where the total investment in code
will usually exceed 30 million dollars. These systems will be maintained by
people who did not write the code, often many people, with one team
replacing another. In some cases, these team turnovers can occur four or
five times while the code is still considered important enough not to sunset
it.

In this environment, the cost of a single line of code is 10 times what it
cost to write and debug it. In this environment, anything that could add
complexity or confusion MUST be factored out as soon as possible. I don't
know what kind of environment you write code in, sir, but if you were to
give me a program with a 'goto' in it, I would ask you kindly to remove it.
If you chose to disagree, I'd stop your app from going into production until
you did.
They're uncommon, but I see no advantage in being unable to recognize
them.
'Advantage' is another term like 'better' above. It has a meaning that is
relative to its context.

Have you ever programmed in assembly language?
Two processor families. Total of three years. I wrote kernel code and
telecom firmware.
There, 'goto' is obligatory, and you quickly learn how to use it
systematically and reliably.
Agreed. Thank heaven for the C programming language. The amount of
assembly that I've had to actually live with is thankfully small.
Mostly, you write things that are equivalent to loops or blocks in
higher-level languages, but occasionally, you see that a 'goto' can do
something useful that has no direct equivalent in structured programming.
Once again, that depends on your definition of 'useful'.
Slacker? Luddite? Me???

Michael Covington, Ph.D.
Associate Director, Artificial Intelligence Center
The University of Georgia - www.ai.uga.edu/mc


I am flattered that a person of such learning would respond to my message.
I salute you for your accomplishments. Understand, however, that I do not
agree with you on this point, but not because I think you to be 'stupid.'
Far from it. It is because, in my world (and in the world of most software
developers), whether in product development or in Information Technology,
the _cost_ of a 'goto' far exceeds its _value_.

Understand that I am not interested in discussing a particular algorithm and
why 'goto' is better in that case. I'm sure that you can make a passionate
and lucid case for it. I maintain that there is no algorithm that requires
the 'goto' but I leave open the possibility that I am not correct. To be
honest, it doesn't matter. There are algorithms, I'm sure, in someone's
code, that makes use of it, and potentially to a positive effect if you view
the code only from the standpoint of performance.

I do not.

--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
--
Nov 17 '05 #8

P: n/a
"Michael A. Covington" <lo**@ai.uga.edu.for.address> wrote in message
news:%2****************@TK2MSFTNGP10.phx.gbl...

"Mark R. Dawson" <Ma*********@discussions.microsoft.com> wrote in message
news:F9**********************************@microsof t.com...
I have never used a goto statement in my code, one of the first things I
was
told in my software classes a number of years ago was "goto statements
are
evil and lead to spagetti code - do not use them".
If they had no legitimate uses, programming languages would not include
them.


Many things are included in programming languages for purposes that do NOT
apply to new code development. While I cannot and will not speak for C#, I
can say that considerations such as backwards compatibility with similar
languages is a factor in language development. If by including a statement,
the language can be used more easily to port 1,000,000 lines of C or even
Cobol code, then the statement is valuable, even if no one is using it for
new coding.

I find them useful in coding algorithms that are essentially big
state-transition networks. Each block of code represents one state, and
upon a state change, you jump to another block of code.
I have coded a few systems that use state transition mechanisms, from data
communication to workflow, and none required the use of a 'goto.' That is
not because I was making any special attempt to avoid the 'goto' although
the term has passed out of my lexicon. It is because I found no _elegant_
reason to use one. Even a Turing machine, as the simplest and most
fundamental of state transition systems, can be coded easily and efficiently
without using a goto.


This is not a common kind of algorithm, of course, but it's a legitimate
one. Naturally, you have to be careful how you code it.
I would certainly agree that state-transition systems are legitimate. I
would disagree that 'goto' is required in order to implement them.
We don't want to teach knee-jerk programming, where programmers
automatically do one thing because they've been told to, not because
they've considered the alternatives.


Engineers don't consider the use of toothpick to build highway suspension
bridges. Does that make them 'knee-jerk' engineers because they didn't
consider the use of toothpicks? If the obvious and common constraints of a
system leads you away from some common mechanisms, is it wrong to start by
excluding those mechanisms early? You have to combine the desire to
consider alternatives with the desire to reach a reasonable conclusion in a
reasonably short period of time.

--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
--
Nov 17 '05 #9

P: n/a
> Minor correction: I did not call anyone stupid. I did call the folks who
use goto "slackers" and "luddites".
There may indeed be such people.
An interesting class of algorithms seems to be beyond your present
knowledge of computer programming."


I maintain that there are no algorithms that REQUIRE this simple structure
(I may be wrong on this point).


I believe Dijkstra proved that that is so, at a very early stage.
I gladly concede that there are algorithms that can be made more efficient
with the use of this construct.


Or, more to the point, easier for human beings to understand.

Knuth pointed out back in 1974 that the point of structured programming is
not the elimination of 'goto' but the restriction of transfers of control.
If you use 'goto' in a disciplined way, it does not introduce unreliablity.
See this link: http://portal.acm.org/citation.cfm?id=356640

I should add that Knuth's masterpieces, TeX and Metafont, are highly
structured and I don't know if they contain any 'goto's at all; if so,
certainly not many. But he stands up for his *right* to use them.
I don't use them often, but there are one or two 'goto' statements in my
latest and biggest (20,000-line?) object-oriented C# program. There
really are places where 'goto' is better than the alternatives.


That depends on what you mean by 'better.'


I mean that the algorithm is easier to understand, easier to confirm the
reliability of, and easier to maintain because of the use of a 'goto' than
it would be if it were pieced together out of structured programming
constructs. It is also a tiny bit more efficient, but that's not a big
thing because the compiler optimizes.

Such algorithms do exist. They were discussed extensively in the early days
of structured programming, and that is why all structured languages - up to
and including C# 3.0 - still have a 'goto' statement.

By the way, I don't like the C language at all. By relying on unchecked
pointers, it does to memory what 'goto' does to program organization --
opens up a whole can of worms! (Including computer security holes that have
led to tremendous damage. Why should there ever have been such a thing as
buffer overruns?)

I come out of the Algol and Pascal tradition and like C# mainly because it
combines the conciseness of C with the reliability (at last!) of languages
that manage memory properly. And I dislike 'spaghetti code' as much as you
do.

--

Michael Covington, Ph.D.
Associate Director, Artificial Intelligence Center
The University of Georgia - www.ai.uga.edu/mc
Nov 17 '05 #10

P: n/a
Much closer to home, here's what Steve McConnell (of "Code Complete") says:
http://www.stevemcconnell.com/ccgoto.htm

Basically an extended demonstration that 'goto' has its legitimate uses.

In particular, he shows you some algorithms where "Use no gotos" conflicts
directly with the principle "Only express each idea once". Duplicate code
is bad because your two expressions of the same idea may not be identical,
especially if, later on, you have to maintain the code; you may not succeed
in keeping them in sync.
Nov 17 '05 #11

P: n/a
On 2005-09-18, Nick Malik [Microsoft] <ni*******@hotmail.nospam.com> wrote:
"Michael A. Covington" <lo**@ai.uga.edu.for.address> wrote in message
news:%2****************@TK2MSFTNGP10.phx.gbl...

"Mark R. Dawson" <Ma*********@discussions.microsoft.com> wrote in message
news:F9**********************************@microsof t.com...
I have never used a goto statement in my code, one of the first things I
was
told in my software classes a number of years ago was "goto statements
are
evil and lead to spagetti code - do not use them".


If they had no legitimate uses, programming languages would not include
them.


Many things are included in programming languages for purposes that do NOT
apply to new code development. While I cannot and will not speak for C#, I
can say that considerations such as backwards compatibility with similar
languages is a factor in language development. If by including a statement,
the language can be used more easily to port 1,000,000 lines of C or even
Cobol code, then the statement is valuable, even if no one is using it for
new coding.


There's another issue too, which is code generation. On the one hand I
could say that I've not written a goto in C# or C++, but the truth is
that I've used lex/yacc/antlr and those tools have generated goto
statements.

Now this isn't code that's meant to be human readable. The goto
statements don't show up in the source tree and aren't reviewed in
code review. But parser generators are a lot more elegant to write if
the destination language has a goto or equivalent.
Nov 17 '05 #12

P: n/a
On 2005-09-18, Michael A. Covington <lo**@ai.uga.edu.for.address> wrote:
Much closer to home, here's what Steve McConnell (of "Code Complete") says:
http://www.stevemcconnell.com/ccgoto.htm

Basically an extended demonstration that 'goto' has its legitimate uses.


Actually, I think the most pertinent statement from McConnell here is:

"These articles contain the whole goto debate. It erupts from time to
time in most workplaces, textbooks, and magazines, but you won't hear
anything that wasn't fully explored 20 years ago."

Except that at this point, it's over 30 years ago.

I must admit though, it's been decades since I've seen the kind of true
spaghetti code that was pretty common back in Dijkstra's day. Unless
they're in certain specialized environments (assembly, batch files),
I suspect most younger programmers have never seen *real* goto-filled
spaghetti code. In my experience, even truly bad programmers today
don't write that kind of stuff, it simply doesn't occur to them to try.

Of course, I don't work in COBOL shops, though :-)
Nov 17 '05 #13

P: n/a
Can I just congratulate the participants for some intelligent discussion
that steered clear of flame wars that opposing views often result in. I
can now honestly say I've learnt something new about both points of view.

Cheers
Jimbo.
Nov 17 '05 #14

P: n/a
Goto's are not evil because they have a specific place in even a structured
program. Searching my massive library of code that I've written over the
last six years I find that in all the C# files I've used goto about a dozen
times. Once in a console application to go to an error / usage display block
which ended the program immediately and the rest of the time for overcoming
the problem C# has with falling through cases which was useful in C++, the
"goto case" construct.

Generally an engineer who understands structured programming rarely has a
need to use direct branches, goto statements, in any case. Good programmers
use the facility very very sparingly. Goto is the last resort of the
educated and the first resort of those who don't have a clue.

--
Bob Powell [MVP]
Visual C#, System.Drawing

Ramuseco Limited .NET consulting
http://www.ramuseco.com

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.

"Mark R. Dawson" <Ma*********@discussions.microsoft.com> wrote in message
news:F9**********************************@microsof t.com...
I have never used a goto statement in my code, one of the first things I
was
told in my software classes a number of years ago was "goto statements are
evil and lead to spagetti code - do not use them".

I absorbed this mantra and tell this to other people and I fully believe
in
it. However, I was talking to someone recently and he was saying how much
he
loved goto statements and how useful they were and that Microsoft had to
leave them in c# because they were so useful, otherwise why would the
statement be in the language. He does not advocate using them in excess
but
uses them to allow himself to create a pattern that allows him to have one
point of exit in a function at the end. I kept trying to convince him
that
gotos were not good but he seemed unconvinced by my arguements.

I know one common use people say is for getting out of deeply nested
statements but you can easily do without gotos by using booleans or
replacing
sections of code with function calls.

Why if they are so bad is goto still in the language, what are the
acceptable uses of the keyword, there must be some otherwise why is the
statement in the c# language, or is this just a legacy thing to attract
programmers from other languages who are used to gotos?

I can't think of any really valid reason why you would use them but maybe
other people have.

Nov 17 '05 #15

P: n/a
The goto, a Japanese musical instrument, is not evil.

Goto, the statement, is not evil either. Preferred euphemisms
are 'break', 'continue', & 'return'.
--
Grace + Peace,
Peter N Roth
Engineering Objects International
http://engineeringobjects.com
Home of Matrix.NET
"Mark R. Dawson" <Ma*********@discussions.microsoft.com> wrote in message
news:F9**********************************@microsof t.com...
I have never used a goto statement in my code, one of the first things I
was
told in my software classes a number of years ago was "goto statements are
evil and lead to spagetti code - do not use them".

I absorbed this mantra and tell this to other people and I fully believe
in
it. However, I was talking to someone recently and he was saying how much
he
loved goto statements and how useful they were and that Microsoft had to
leave them in c# because they were so useful, otherwise why would the
statement be in the language. He does not advocate using them in excess
but
uses them to allow himself to create a pattern that allows him to have one
point of exit in a function at the end. I kept trying to convince him
that
gotos were not good but he seemed unconvinced by my arguements.

I know one common use people say is for getting out of deeply nested
statements but you can easily do without gotos by using booleans or
replacing
sections of code with function calls.

Why if they are so bad is goto still in the language, what are the
acceptable uses of the keyword, there must be some otherwise why is the
statement in the c# language, or is this just a legacy thing to attract
programmers from other languages who are used to gotos?

I can't think of any really valid reason why you would use them but maybe
other people have.

Nov 17 '05 #16

P: n/a
HC
Which is cleaner?

GOTO
for a = 1 to LengthA
for b = 1 to LengthB
for c = 1 to LengthC
for d = 1 to LengthD
do_stuff(a,b,c,d)
if discontinue then goto GetOut:
next d
next c
next b
next a
GetOut:

NO GOTO
for a = 1 to LengthA
for b = 1 to LengthB
for c = 1 to LengthC
for d = 1 to LengthD
do_stuff(a,b,c,d)
if discontinue then break
next d
if discontinue then break
next c
if discontinue then break
next b
if discontinue then break
next a

Peter N Roth wrote:
The goto, a Japanese musical instrument, is not evil.

Goto, the statement, is not evil either. Preferred euphemisms
are 'break', 'continue', & 'return'.
--
Grace + Peace,
Peter N Roth
Engineering Objects International
http://engineeringobjects.com
Home of Matrix.NET
"Mark R. Dawson" <Ma*********@discussions.microsoft.com> wrote in message
news:F9**********************************@microsof t.com...
I have never used a goto statement in my code, one of the first things I
was
told in my software classes a number of years ago was "goto statements are
evil and lead to spagetti code - do not use them".

I absorbed this mantra and tell this to other people and I fully believe
in
it. However, I was talking to someone recently and he was saying how much
he
loved goto statements and how useful they were and that Microsoft had to
leave them in c# because they were so useful, otherwise why would the
statement be in the language. He does not advocate using them in excess
but
uses them to allow himself to create a pattern that allows him to have one
point of exit in a function at the end. I kept trying to convince him
that
gotos were not good but he seemed unconvinced by my arguements.

I know one common use people say is for getting out of deeply nested
statements but you can easily do without gotos by using booleans or
replacing
sections of code with function calls.

Why if they are so bad is goto still in the language, what are the
acceptable uses of the keyword, there must be some otherwise why is the
statement in the c# language, or is this just a legacy thing to attract
programmers from other languages who are used to gotos?

I can't think of any really valid reason why you would use them but maybe
other people have.


Nov 17 '05 #17

P: n/a

"Mark R. Dawson" <Ma*********@discussions.microsoft.com> wrote in message
news:F9**********************************@microsof t.com...
I know one common use people say is for getting out of deeply nested
statements but you can easily do without gotos by using booleans or replacing sections of code with function calls.


It seems that the people who don't know "goto" should be avoided also don't
know that "deeply nested loops" should also be avoided! ;)

I've rarely seen a case where "goto" is necessary. I think that most cases
are probably for optimization, but if you're needing that much optimization
you probably shouldn't be using C# in the first place. I won't say "goto"
should *never* be used, but I've never used it myself. Never had the need.

Now, for a really interesting debate, let's talk about the form of "goto"
stealthily named "return"! ;)
Nov 17 '05 #18

P: n/a

"Steve Walker" <st***@otolith.demon.co.uk> wrote in message
news:so**************@otolith.demon.co.uk...
I think the OO mindset of treating long methods with complex flow
control as a code smell probably contributes to a style of programming
in which the issue does not occur.


Well said.
Nov 17 '05 #19

P: n/a
I would probably write something like

bool found = false;
for ( int a = 0; !found && a < ALength; ++a ) {
found = FindOnB(a);
}
// use 'found' somehow

with similar small loops in FindOnB(), FindOnC(), etc.,
because I prefer to avoid nesting loops.
--
Grace + Peace,
Peter N Roth
Engineering Objects International
http://engineeringobjects.com
Home of Matrix.NET
"HC" <ha*************@gmail.com> wrote in message
news:11**********************@g44g2000cwa.googlegr oups.com...
Which is cleaner?

GOTO
for a = 1 to LengthA
for b = 1 to LengthB
for c = 1 to LengthC
for d = 1 to LengthD
do_stuff(a,b,c,d)
if discontinue then goto GetOut:
next d
next c
next b
next a
GetOut:

NO GOTO
for a = 1 to LengthA
for b = 1 to LengthB
for c = 1 to LengthC
for d = 1 to LengthD
do_stuff(a,b,c,d)
if discontinue then break
next d
if discontinue then break
next c
if discontinue then break
next b
if discontinue then break
next a

Peter N Roth wrote:
The goto, a Japanese musical instrument, is not evil.

Goto, the statement, is not evil either. Preferred euphemisms
are 'break', 'continue', & 'return'.
--
Grace + Peace,
Peter N Roth
Engineering Objects International
http://engineeringobjects.com
Home of Matrix.NET
"Mark R. Dawson" <Ma*********@discussions.microsoft.com> wrote in message
news:F9**********************************@microsof t.com...
>I have never used a goto statement in my code, one of the first things I
>was
> told in my software classes a number of years ago was "goto statements
> are
> evil and lead to spagetti code - do not use them".
>
> I absorbed this mantra and tell this to other people and I fully
> believe
> in
> it. However, I was talking to someone recently and he was saying how
> much
> he
> loved goto statements and how useful they were and that Microsoft had
> to
> leave them in c# because they were so useful, otherwise why would the
> statement be in the language. He does not advocate using them in
> excess
> but
> uses them to allow himself to create a pattern that allows him to have
> one
> point of exit in a function at the end. I kept trying to convince him
> that
> gotos were not good but he seemed unconvinced by my arguements.
>
> I know one common use people say is for getting out of deeply nested
> statements but you can easily do without gotos by using booleans or
> replacing
> sections of code with function calls.
>
> Why if they are so bad is goto still in the language, what are the
> acceptable uses of the keyword, there must be some otherwise why is the
> statement in the c# language, or is this just a legacy thing to attract
> programmers from other languages who are used to gotos?
>
> I can't think of any really valid reason why you would use them but
> maybe
> other people have.

Nov 17 '05 #20

P: n/a
I rather do

try
{
for (...)
{
for (...)
{
...
DoStuff () ;
if (discontinue) throw new MyException (...) ;
}
}
}
catch (MyException e) {}
....

kind of structured gotos.

/LM

"HC" <ha*************@gmail.com> wrote in message
news:11**********************@g44g2000cwa.googlegr oups.com...
Which is cleaner?

GOTO
for a = 1 to LengthA
for b = 1 to LengthB
for c = 1 to LengthC
for d = 1 to LengthD
do_stuff(a,b,c,d)
if discontinue then goto GetOut:
next d
next c
next b
next a
GetOut:

NO GOTO
for a = 1 to LengthA
for b = 1 to LengthB
for c = 1 to LengthC
for d = 1 to LengthD
do_stuff(a,b,c,d)
if discontinue then break
next d
if discontinue then break
next c
if discontinue then break
next b
if discontinue then break
next a

Peter N Roth wrote:
The goto, a Japanese musical instrument, is not evil.

Goto, the statement, is not evil either. Preferred euphemisms
are 'break', 'continue', & 'return'.
--
Grace + Peace,
Peter N Roth
Engineering Objects International
http://engineeringobjects.com
Home of Matrix.NET
"Mark R. Dawson" <Ma*********@discussions.microsoft.com> wrote in message
news:F9**********************************@microsof t.com...
>I have never used a goto statement in my code, one of the first things I
>was
> told in my software classes a number of years ago was "goto statements
> are
> evil and lead to spagetti code - do not use them".
>
> I absorbed this mantra and tell this to other people and I fully
> believe
> in
> it. However, I was talking to someone recently and he was saying how
> much
> he
> loved goto statements and how useful they were and that Microsoft had
> to
> leave them in c# because they were so useful, otherwise why would the
> statement be in the language. He does not advocate using them in
> excess
> but
> uses them to allow himself to create a pattern that allows him to have
> one
> point of exit in a function at the end. I kept trying to convince him
> that
> gotos were not good but he seemed unconvinced by my arguements.
>
> I know one common use people say is for getting out of deeply nested
> statements but you can easily do without gotos by using booleans or
> replacing
> sections of code with function calls.
>
> Why if they are so bad is goto still in the language, what are the
> acceptable uses of the keyword, there must be some otherwise why is the
> statement in the c# language, or is this just a legacy thing to attract
> programmers from other languages who are used to gotos?
>
> I can't think of any really valid reason why you would use them but
> maybe
> other people have.

Nov 17 '05 #21

P: n/a
Using Exception instead of goto?
Even worse!

"Luc E. Mistiaen" <lu**********@advalvas.be.no.spam> schrieb im Newsbeitrag
news:ue**************@TK2MSFTNGP09.phx.gbl...
I rather do

try
{
for (...)
{
for (...)
{
...
DoStuff () ;
if (discontinue) throw new MyException (...) ;
}
}
}
catch (MyException e) {}
...

kind of structured gotos.

/LM

"HC" <ha*************@gmail.com> wrote in message
news:11**********************@g44g2000cwa.googlegr oups.com...
Which is cleaner?

GOTO
for a = 1 to LengthA
for b = 1 to LengthB
for c = 1 to LengthC
for d = 1 to LengthD
do_stuff(a,b,c,d)
if discontinue then goto GetOut:
next d
next c
next b
next a
GetOut:

NO GOTO
for a = 1 to LengthA
for b = 1 to LengthB
for c = 1 to LengthC
for d = 1 to LengthD
do_stuff(a,b,c,d)
if discontinue then break
next d
if discontinue then break
next c
if discontinue then break
next b
if discontinue then break
next a

Peter N Roth wrote:
The goto, a Japanese musical instrument, is not evil.

Goto, the statement, is not evil either. Preferred euphemisms
are 'break', 'continue', & 'return'.
--
Grace + Peace,
Peter N Roth
Engineering Objects International
http://engineeringobjects.com
Home of Matrix.NET
"Mark R. Dawson" <Ma*********@discussions.microsoft.com> wrote in
message
news:F9**********************************@microsof t.com...
>I have never used a goto statement in my code, one of the first things
>I
>was
> told in my software classes a number of years ago was "goto statements
> are
> evil and lead to spagetti code - do not use them".
>
> I absorbed this mantra and tell this to other people and I fully
> believe
> in
> it. However, I was talking to someone recently and he was saying how
> much
> he
> loved goto statements and how useful they were and that Microsoft had
> to
> leave them in c# because they were so useful, otherwise why would the
> statement be in the language. He does not advocate using them in
> excess
> but
> uses them to allow himself to create a pattern that allows him to have
> one
> point of exit in a function at the end. I kept trying to convince him
> that
> gotos were not good but he seemed unconvinced by my arguements.
>
> I know one common use people say is for getting out of deeply nested
> statements but you can easily do without gotos by using booleans or
> replacing
> sections of code with function calls.
>
> Why if they are so bad is goto still in the language, what are the
> acceptable uses of the keyword, there must be some otherwise why is
> the
> statement in the c# language, or is this just a legacy thing to
> attract
> programmers from other languages who are used to gotos?
>
> I can't think of any really valid reason why you would use them but
> maybe
> other people have.


Nov 17 '05 #22

P: n/a

"HC" <ha*************@gmail.com> wrote in message
news:11**********************@g44g2000cwa.googlegr oups.com...
Which is cleaner?


When looping on a condition, you should use a "while" loop instead of a
"for" loop.

Also, nesting 4 loops deep should be avoided if at all possible.
Nov 17 '05 #23

P: n/a
"Michael A. Covington" <lo**@ai.uga.edu.for.address> wrote in message
news:OL**************@TK2MSFTNGP09.phx.gbl...
Much closer to home, here's what Steve McConnell (of "Code Complete")
says:
http://www.stevemcconnell.com/ccgoto.htm

Basically an extended demonstration that 'goto' has its legitimate uses.

In particular, he shows you some algorithms where "Use no gotos" conflicts
directly with the principle "Only express each idea once". Duplicate code
is bad because your two expressions of the same idea may not be identical,
especially if, later on, you have to maintain the code; you may not
succeed in keeping them in sync.


Being a fan of McConnell, I made a careful read of the page you pointed me
to. It is interesting that the path that he chose to illustrate his "no go
to" debate from was one that illustrates how to REWRITE code from "including
goto" to "excluding goto." I have a problem with this characterization.

The cognitive exercise places into the mind an understanding of the
algorithm from the viewpoint of a procedure written with goto in mind, and
then attempts to show that the algorithm is less readable or potentially
more prone to problems if you rewrite it. This shows only that if you
present an idea, in one form, and ask your reader to go through a mental
exercise to understand it, that it may be hard for that same reader to
immediately follow the exercise with one in which s/he has to relearn the
algorithm from another point of view. I'm not completely convinced that the
mental process that the reader goes through in this example is a valid
process for comparison, because it is a "code-only" process and does not
factor in design time considerations.

In other words, what Steve did NOT do is illustrate how valid OO thinking
would have led away from this situation in the first place. The author of
the code is much more likely not to have written code filled with "goto"
statements and this triggering this rewrite and the ensuing comparison,
because a person who described applications in terms of their patterns would
not have lept to the conclusion that an implementation that uses goto makes
much sense.

As a coding leader, it is my responsibility to encourage this kind of
thinking, because the benefits it reaps across the project are immense. If
a programmer in using 'goto', even in a rational and constrained way, I
would be led to wonder if he was thinking about the problem in terms of
patterns, since there are no OO patterns that use the goto.

In fact, the specific example that you cite is nearly perfect for
demonstrating the effective use of the strategy pattern, where parts of an
algorithm are seperated from, and replacable by, other parts. This, in
effect, creates a system whereby control structures within an algorithm can
be seperated from calculation logic and expressed independently.

It is also interesting to note that this article, like the rest, makes the
comparison between structured programming with the 'goto' and structured
programming without the 'goto.' No article makes the comparison with OOP in
the mix. Perhaps this is because no more recent study on the debate,
including in the OO world, has found anything new to say. Or, perhaps, no
one cares as much any more.

I'm afraid that we will not agree on this point. However, I appreciate the
discussion.
--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
--
Nov 17 '05 #24

P: n/a
Your position is basically "Thou shalt not think of certain algorithms,"
then, right?

Can you demonstrate that these algorithms are undesirable?

Nov 17 '05 #25

P: n/a
"Michael A. Covington" <lo**@ai.uga.edu.for.address> wrote in message
news:uS**************@TK2MSFTNGP10.phx.gbl...
Your position is basically "Thou shalt not think of certain algorithms,"
then, right?

Can you demonstrate that these algorithms are undesirable?


The definition of an algorithm (loosely) is a specific set of steps used to
solve a known problem.

Let's work backwards from that.

Algorithms solve problems. There is the problem first. The design attempts
to solve the problem. During implementation, the developer may select an
algorithm as the basis for his coding.

On that basis, I maintain that there is NO problem that cannot be solved
without the use of a goto. It is quite possible that there is an algorithm
that specifies GOTO as one of its steps, and a case could be made that to
convert that step to another that is functionally equivalent is to implement
a different algorithm, because the definition of algorithm includes the word
'specific.'

Therefore, I am sidestepping a little. I am stating (from a position of
weakness and admittedly less learning than you, which is dangerous) that you
cannot present to me an algorithm that solves a problem where I cannot craft
a functionally equivalent bit of OO code to solve the same problem without
the use of a goto. In that aspect, I will say that I am not turning away
from ANY problem... only implementations that are not worth maintaining
because the coding of them teaches bad habits.

--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
--
Nov 17 '05 #26

P: n/a
> There's another issue too, which is code generation. On the one hand I
could say that I've not written a goto in C# or C++, but the truth is
that I've used lex/yacc/antlr and those tools have generated goto
statements.

Now this isn't code that's meant to be human readable. The goto
statements don't show up in the source tree and aren't reviewed in
code review. But parser generators are a lot more elegant to write if
the destination language has a goto or equivalent.


While I have used Lex and YACC, I cannot make any claim to have written a
_system_ to generate code that deterministically parses a language. (It
would be an interesting exercise, but alas, that work belongs to another
team at Microsoft :-). Therefore, I have no grounds to either agree or
disagree with your statement.

I will say that I see no reason, other than the fact that the developers of
those languages had already written parser code using goto, that they would
be _required_ to generate code that used a goto. I can easily _concieve_ of
designs that would generate code that does not use a goto.

That said, you are correct in your assertion that this type of code is not
designed to be human readable and would normally be excluded from human code
review (except for instances of white-box testing). In that sense, it is
object code. For this sake, I feel that it may be fair to let a 'generated'
goto statement remain in a production codebase, as long as the tool that
generates the code, and the source data that it used, is maintained along
with the code itself.

--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
--
Nov 17 '05 #27

P: n/a

"Nick Malik [Microsoft]" <ni*******@hotmail.nospam.com> wrote in message
news:pr********************@comcast.com...
"Michael A. Covington" <lo**@ai.uga.edu.for.address> wrote in message
news:uS**************@TK2MSFTNGP10.phx.gbl...
Your position is basically "Thou shalt not think of certain algorithms,"
then, right?

Can you demonstrate that these algorithms are undesirable?
On that basis, I maintain that there is NO problem that cannot be solved
without the use of a goto.
That is correct and can be proved mathematically (assuming you have
for-loops, while-loops, if-then-else structures, and the usual structured
programming stuff).

However, the cost is that in some circumstances you must code the same test
in more than one place. This is not common in C-like languages, especially
because in C, you have 'break' and 'continue', which are not part of the
minimum set of structured programming constructs; they are essentially
restricted 'goto' statements. Real purists would object to 'break' and
'continue.'
Therefore, I am sidestepping a little. I am stating (from a position of
weakness and admittedly less learning than you, which is dangerous) that
you cannot present to me an algorithm that solves a problem where I cannot
craft a functionally equivalent bit of OO code to solve the same problem
without the use of a goto.


I don't dispute that at all. Using 'goto' raises the risk of programmer's
error. Coding the same test in more than one place also raises the risk of
programmer's error. It's a trade-off. I reject the claim that 'goto'
should always be avoided at any cost. There is a cost.

Pointers, as I noted before, *really* raise the risk of programmer's error;
they do to memory what 'goto' does to code execution. That's why I'm glad
C# minimizes use of them. I find C an annoyng language because the flow of
control is so structured but the use of memory is so error-prone.

Also, I don't advocate *common* use of 'goto'. I code about one per year.
If I were programming full-time, I'd probably code one every three months.
They always have very limited scope (i.e., they jump very short distances).

You could probably eliminate all of them by inventing another kind of
restricted 'goto' along the lines of 'break' and 'continue'.
Nov 17 '05 #28

P: n/a
Certainly, one of the best reasons to have 'goto' in a language is
machine-generated code.

There is a lot of compiler technology that assumes 'goto' is present (which
it always is, in machine language).

Maybe you want to take a compiler, or the logic of a compiler, and have it
output C# rather than MSIL, for language translation purposes. Having it
use 'goto' would not introduce errors.
Nov 17 '05 #29

P: n/a
Michael A. Covington <lo**@ai.uga.edu.for.address> wrote:

<snip>
You could probably eliminate all of them by inventing another kind of
restricted 'goto' along the lines of 'break' and 'continue'.


Something along the lines of Java's labelled break/continue?

For example:

public class Test
{
public static void main(String[] args)
{
OuterLoop:
for (int i=0; i < 5; i++)
{
for (int j=0; j < 4; j++)
{
if (i*j > 10)
{
break OuterLoop;
}
System.out.println (i+" "+j);
}
}
}
}

I very occasionally wish C# had this functionality. (There are other
bits of Java I'd want first though - the enums introduced in 1.5 would
probably be top of the list...)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 17 '05 #30

P: n/a

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Something along the lines of Java's labelled break/continue?

For example:

public class Test
{
public static void main(String[] args)
{
OuterLoop:
for (int i=0; i < 5; i++)
{
for (int j=0; j < 4; j++)
{
if (i*j > 10)
{
break OuterLoop;
}
System.out.println (i+" "+j);
}
}
}
}


Sorry if this sounds harsh, but this is why I *hate* contrived examples. No
one would *ever* write code like that because the code does nothing. But I
digress.....

The problem with your example is that you used "for" loops when you should
have used "while" loops. When looping on a condition, use "while". When
looping a set number of times, use "for". Any time you stick "break" into a
"for" loop you know you've used the wrong type of loop.

The problem is, the "for" loop in C# is so darn convenient. I find myself
doing the same thing you just did. When searching through a list I use a
"for" loop and "break" out when I find my item. Why? Less typing I suppose.
But even though I'm guilty of doing it I still think it's simply lazy
coding. :-)
Nov 17 '05 #31

P: n/a
Scott Roberts <sc***********@no-spam.intelebill.com> wrote:

<snip>
Sorry if this sounds harsh, but this is why I *hate* contrived examples. No
one would *ever* write code like that because the code does nothing. But I
digress.....
It wasn't meant to be an example of where it would be handy - it was
*only* meant to be an example of the syntax.
The problem with your example is that you used "for" loops when you should
have used "while" loops. When looping on a condition, use "while". When
looping a set number of times, use "for". Any time you stick "break" into a
"for" loop you know you've used the wrong type of loop.
Do you hold that to be true with foreach as well?
The problem is, the "for" loop in C# is so darn convenient. I find myself
doing the same thing you just did. When searching through a list I use a
"for" loop and "break" out when I find my item. Why? Less typing I suppose.
But even though I'm guilty of doing it I still think it's simply lazy
coding. :-)


I'm not sure - I think the "for" loop shows the "going through a list"
bit more readably than the while loop would. The while loop, however,
expresses the "while I haven't found what I'm looking for" bit more
readably.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 17 '05 #32

P: n/a

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP***********************@msnews.microsoft.co m...
The problem with your example is that you used "for" loops when you should have used "while" loops. When looping on a condition, use "while". When
looping a set number of times, use "for". Any time you stick "break" into a "for" loop you know you've used the wrong type of loop.


Do you hold that to be true with foreach as well?


Doesn't the term "for each" imply that you are going to process "each" item
in the list? Doesn't "break" prevent that from happening?

I know it's very strict, and as I said I don't always follow it in practice
either, but from a idealogical perspective it doesn't make sense to me to
use "continue" or "break".
Nov 17 '05 #33

P: n/a
Scott Roberts <sc***********@no-spam.intelebill.com> wrote:
Do you hold that to be true with foreach as well?
Doesn't the term "for each" imply that you are going to process "each" item
in the list?


Not to me. To me, it means the loop itself just goes through each
element, if left to its own devices (as it were).
Doesn't "break" prevent that from happening?
It certainly does.
I know it's very strict, and as I said I don't always follow it in practice
either, but from a idealogical perspective it doesn't make sense to me to
use "continue" or "break".


To me, using a foreach loop and breaking once you've found something is
much more readable than using a while loop. When ideology gets in the
way of readability, it's time to modify the ideology IMO :)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 17 '05 #34

P: n/a

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Scott Roberts <sc***********@no-spam.intelebill.com> wrote:
Do you hold that to be true with foreach as well?
Doesn't the term "for each" imply that you are going to process "each" item in the list?


Not to me. To me, it means the loop itself just goes through each
element, if left to its own devices (as it were).


Yes, unless the programmer decides to "goto" somewhere else at some point
within the loop. :-)
To me, using a foreach loop and breaking once you've found something is
much more readable than using a while loop.
Yeah, but now we're talking about implementing linear search algorithms.
That makes me cringe too! :-)
When ideology gets in the
way of readability, it's time to modify the ideology IMO :)


Can't argue with that. The reality is that "break", "continue", and "goto"
do not make code *inherently* bad or unreadable. However, I would say that
heavy use of those constructs probably indicates one is heading down that
road.
Nov 17 '05 #35

P: n/a
Scott Roberts <sc***********@no-spam.intelebill.com> wrote:
Not to me. To me, it means the loop itself just goes through each
element, if left to its own devices (as it were).


Yes, unless the programmer decides to "goto" somewhere else at some point
within the loop. :-)


Indeed.
To me, using a foreach loop and breaking once you've found something is
much more readable than using a while loop.


Yeah, but now we're talking about implementing linear search algorithms.
That makes me cringe too! :-)


It shouldn't - not when that's the simplest thing to do, and there's no
chance of it being a bottleneck. (That's not always the case, of
course, but it often is.)
When ideology gets in the
way of readability, it's time to modify the ideology IMO :)


Can't argue with that. The reality is that "break", "continue", and "goto"
do not make code *inherently* bad or unreadable. However, I would say that
heavy use of those constructs probably indicates one is heading down that
road.


Sure.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 17 '05 #36

P: n/a
I certainly don't think they are evil.
Yes they can be abused, but so can anything else.
Sometimes efecitve use of flow control schemtics, like switch,
break, and yes even goto can create cleaner code then nested if's, and
traditional OO programing.

The way I've used goto's most often is in creating functions with a single
exit point for tracing purposes. This was a c application, with .net I'd
use a try, catch, finally, which is in someways just an elegant goto
statement.
"Jon Skeet [C# MVP]" wrote:
Scott Roberts <sc***********@no-spam.intelebill.com> wrote:
Not to me. To me, it means the loop itself just goes through each
element, if left to its own devices (as it were).


Yes, unless the programmer decides to "goto" somewhere else at some point
within the loop. :-)


Indeed.
To me, using a foreach loop and breaking once you've found something is
much more readable than using a while loop.


Yeah, but now we're talking about implementing linear search algorithms.
That makes me cringe too! :-)


It shouldn't - not when that's the simplest thing to do, and there's no
chance of it being a bottleneck. (That's not always the case, of
course, but it often is.)
When ideology gets in the
way of readability, it's time to modify the ideology IMO :)


Can't argue with that. The reality is that "break", "continue", and "goto"
do not make code *inherently* bad or unreadable. However, I would say that
heavy use of those constructs probably indicates one is heading down that
road.


Sure.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

Nov 17 '05 #37

P: n/a
Hi :)

I would like to deffereniate between two goto's statement

goto in old days
and
goto in current days

I used to program BASIC at MSX
goto was an important statement for the language
because you don't have functions :)

and to simulate functions another statement was GOSUB

I think the dangerous of goto is disappeared in any procedural language

BASIC (and also Assembly) is not considered to be procedural language

means that goto statement could throw you in any code in your program.

but try to make anonymous function in C# 2.0 and make a goto statement that
is outer the boundary of it immediately the compiler will refuse to compile
:(

in my opinion the goto bad reputation was inroduced as an effect of the old
days programming
remember you were only coding in
- ONE FILE
- ONE piece of code ( which your enrty point was the first line of code and
the end was at the last )

I have a fortran program written by my proffessor to solve something about
thermodynamics stuff. I got astonished about the amount of the goto statement
in it, But suddenly I knew why he was using it. The calculations where
accumulated and he needs to make some sort of testing at every stage so he
was using goto to transfer the program to the end line.

I don't consider goto statement is an evil unless the numbering come
back to any language [ may be thats why labels inroduced in the procedural
language ]

in another way you CAN'T goto from CLASS A code to CLASS B code with out
instantiating the two classes and know a set of methods to call

its all about transferring the current control to another control

so goto nowdays is really really limited to the their block of code

I don't make a huge lines in one method
instead I make many many few methods which I suddenly discovered that it is
unreadable

so if you see goto statement in c# don't panic as it is not the no.1
source of complexitiy and I repeat it is only affecting its enclosed block
{} unless you are typing all of your program in the main() :)

goto is very romantic statement it makes you escape from your
responsibilities and it expresses our weakness as a human being if there is a
program without an ERROR then I might be wrong :)

--
BLUE SUN
"Mark R. Dawson" wrote:
I have never used a goto statement in my code, one of the first things I was
told in my software classes a number of years ago was "goto statements are
evil and lead to spagetti code - do not use them".

I absorbed this mantra and tell this to other people and I fully believe in
it. However, I was talking to someone recently and he was saying how much he
loved goto statements and how useful they were and that Microsoft had to
leave them in c# because they were so useful, otherwise why would the
statement be in the language. He does not advocate using them in excess but
uses them to allow himself to create a pattern that allows him to have one
point of exit in a function at the end. I kept trying to convince him that
gotos were not good but he seemed unconvinced by my arguements.

I know one common use people say is for getting out of deeply nested
statements but you can easily do without gotos by using booleans or replacing
sections of code with function calls.

Why if they are so bad is goto still in the language, what are the
acceptable uses of the keyword, there must be some otherwise why is the
statement in the c# language, or is this just a legacy thing to attract
programmers from other languages who are used to gotos?

I can't think of any really valid reason why you would use them but maybe
other people have.

Nov 17 '05 #38

P: n/a
First and foremost I agree with the posters that believe gotos are not worth
the trouble, can lead to confusing logic, are completely unnecessary and most
likely indicate bad design.

With that said, there is one thing that almost all programmers miss about
gotos; We all use them all of the time. I would actually go as far as to say
that each and every programmer uses gotos on a daily bases. All conditional
logic, including looping logic and the break and continue commands cannot
possibly work without an implicit goto statement.

The “if” statement can be interpreted as IF true DO expression1 GOTO
“immediately beyond expression 2 to continue with logic” ELSE DO expression 2
END IF continue with logic.

The “for, while, until” statements can be interpreted similarly.

And for the more explicit logic control but still considered implicit goto
statements the break and continue can be interpreted as follows;

- “break” - GOTO immediately beyond the conditional or looping logic in the
current scope
- “continue” - GOTO the next iteration of the looping logic in the current
scope

My opinion is that implicit gotos are fine if not necessary, the explicit
GOTO statement is both unnecessary and an indication of logic flow design.
"Mark R. Dawson" wrote:
I have never used a goto statement in my code, one of the first things I was
told in my software classes a number of years ago was "goto statements are
evil and lead to spagetti code - do not use them".

I absorbed this mantra and tell this to other people and I fully believe in
it. However, I was talking to someone recently and he was saying how much he
loved goto statements and how useful they were and that Microsoft had to
leave them in c# because they were so useful, otherwise why would the
statement be in the language. He does not advocate using them in excess but
uses them to allow himself to create a pattern that allows him to have one
point of exit in a function at the end. I kept trying to convince him that
gotos were not good but he seemed unconvinced by my arguements.

I know one common use people say is for getting out of deeply nested
statements but you can easily do without gotos by using booleans or replacing
sections of code with function calls.

Why if they are so bad is goto still in the language, what are the
acceptable uses of the keyword, there must be some otherwise why is the
statement in the c# language, or is this just a legacy thing to attract
programmers from other languages who are used to gotos?

I can't think of any really valid reason why you would use them but maybe
other people have.

Nov 17 '05 #39

P: n/a
"Peter N Roth" <re***********@mycompany.com> wrote in message
news:u6**************@TK2MSFTNGP09.phx.gbl...
I would probably write something like

bool found = false;
for ( int a = 0; !found && a < ALength; ++a ) {
found = FindOnB(a);
}
// use 'found' somehow

with similar small loops in FindOnB(), FindOnC(), etc.,
because I prefer to avoid nesting loops.


I think many people hate you, but you wander through life not realizing
this. Perhaps your ghost will cry when it looks upon the empty room that
is your funeral.

--
Mabden
Nov 17 '05 #40

P: n/a
Google "spellchecker"

"ibluesun" <ib******@discussions.microsoft.com> wrote in message
news:BC**********************************@microsof t.com...
Hi :)

I would like to deffereniate between two goto's statement

goto in old days
and
goto in current days

I used to program BASIC at MSX
goto was an important statement for the language
because you don't have functions :)

and to simulate functions another statement was GOSUB

I think the dangerous of goto is disappeared in any procedural language
BASIC (and also Assembly) is not considered to be procedural language

means that goto statement could throw you in any code in your program.

but try to make anonymous function in C# 2.0 and make a goto statement that is outer the boundary of it immediately the compiler will refuse to compile :(

in my opinion the goto bad reputation was inroduced as an effect of the old days programming
remember you were only coding in
- ONE FILE
- ONE piece of code ( which your enrty point was the first line of code and the end was at the last )

I have a fortran program written by my proffessor to solve something about thermodynamics stuff. I got astonished about the amount of the goto statement in it, But suddenly I knew why he was using it. The calculations where
accumulated and he needs to make some sort of testing at every stage so he was using goto to transfer the program to the end line.

I don't consider goto statement is an evil unless the numbering come back to any language [ may be thats why labels inroduced in the procedural language ]

in another way you CAN'T goto from CLASS A code to CLASS B code with out instantiating the two classes and know a set of methods to call

its all about transferring the current control to another control

so goto nowdays is really really limited to the their block of code

I don't make a huge lines in one method
instead I make many many few methods which I suddenly discovered that it is unreadable

so if you see goto statement in c# don't panic as it is not the no.1 source of complexitiy and I repeat it is only affecting its enclosed block {} unless you are typing all of your program in the main() :)

goto is very romantic statement it makes you escape from your
responsibilities and it expresses our weakness as a human being if there is a program without an ERROR then I might be wrong :)

--
BLUE SUN
"Mark R. Dawson" wrote:
I have never used a goto statement in my code, one of the first things I was told in my software classes a number of years ago was "goto statements are evil and lead to spagetti code - do not use them".

I absorbed this mantra and tell this to other people and I fully believe in it. However, I was talking to someone recently and he was saying how much he loved goto statements and how useful they were and that Microsoft had to leave them in c# because they were so useful, otherwise why would the statement be in the language. He does not advocate using them in excess but uses them to allow himself to create a pattern that allows him to have one point of exit in a function at the end. I kept trying to convince him that gotos were not good but he seemed unconvinced by my arguements.

I know one common use people say is for getting out of deeply nested
statements but you can easily do without gotos by using booleans or replacing sections of code with function calls.

Why if they are so bad is goto still in the language, what are the
acceptable uses of the keyword, there must be some otherwise why is the statement in the c# language, or is this just a legacy thing to attract programmers from other languages who are used to gotos?

I can't think of any really valid reason why you would use them but maybe other people have.

Nov 17 '05 #41

P: n/a
Summary: Gotos are a tool: useful but dangerous

"Mark R. Dawson" <Ma*********@discussions.microsoft.com> wrote in
message news:F9**********************************@microsof t.com...
I have never used a goto statement in my code, one of the first things I was told in my software classes a number of years ago was "goto statements are evil and lead to spagetti code - do not use them".
I had a teacher like that once:
"I have never had sex in my life, one of the first things I was told in
my sex ed class, last semester, was, 'Sex will give you many diseases
and boys won't respect you - don't have sex!'"

I have used gotos. I have had down and dirty gotos and prim and proper
gotos. I have used gotos for Evil (for looping; a Very Bad Idea)! I have
used gotos for Virtue (one exit per function - read Myers' books). I
have written assembly code, batch files (shell scripts to the eunuchs) I
know gotos.

A lesson to the New Programmers:

Preface:
When there was no concept of "germs", doctors would operate on a patient
without washing. Or operate on several in a row. No soap, no mask, etc.
Then a guy came along to try to convince these guys that there were
little invisible aliens that sat on their hands and pushed disease into
the patient. If the doctor coughed or spat, some "germs" might infect
the patient! Ha! What?! Seriously? Nah.

History:
When programmers were first making programs without functions, therefore
no returns, you had to jump to where you wanted to go and jump back to
where you were before. Or where you thought you should go next. Usually
using line numbers. If someone added code inside the line numbers, the
goto would have to be manually changed - everywhere. BTW, that's why
statements were 10, 20, 30, etc. Because if you added lines, you could
use 11, 12, 13 and not have to change the "goto 10" statements
everywhere. I think the kids think that line numbers were just multiples
of 10; they were not. Oh, and no #defines!

========= skim this =========
(Off the top of my head example, please don't flame about the
pseudo-BASIC provided)
Now, think upon this - you have a nice routine starting at line 502 (we
stopped using the 501 initializer in version 7.2) that you are using in
several functions to output data to the screen. About 576 there is a
useful routine for converting alpha chars to numbers, so you just JUMP
INTO THE MIDDLE OF THE PRINT ROUTINE to do a text conversion. Then use a
goto to get back, the global TC =3.

500 REM PRINT CHARACTER TO OUTPUT
501 LET X=4
502 IF CHR(C) < 65 THEN GOTO 589 ;REM NOT A LETTER
503 IF CHR(C) > 90 THEN GOTO 589 ;REM NOT A LETTER

<statements to init the printer>

GOTO 576
....
576 REM CONVERT TO LETTER
577 LET C=C-65
578 IF C > 26 THEN GOTO 589
....
588 RC=0 ;REM LETTER

589 RC=47 ;REM NOT A LETTER
600 IF TC=1 GOTO 301 ;REM TEXT CONVERTION FINISHED
601 IF TC=2 GOTO 904 ;REM STRING IS ALPHA, RETURN TO NAME_INPUT
602 IF TC=3 GOTO 1130 ;REM GO SOMEWHERE ELSE
========= skim this =========

The Spaghetti Coder:
In the Bad Old Days, there were a lot of arrogant programmers who wrote
the code they needed to do a job, using the tools they had. And they
maintained that code for its/their lifetime. Later, new programmers were
brought in, and had to learn this code - time constraints meant they
were not the "master" of the code that the original coder was. Changes
were easy to make, but hard to confirm. Much time was spent debugging.
Numbers were spread through-out the code and some came to deserve the
special distinction of "Magic Cookie". This term refers to a number
that was derived by the original programmer over many hours of research
and thought, and that makes a routine work correctly where another
number would not. Usually, it is an encryption, or protocol number that
has special properties (prime number (divided by itself and one only),
perfect number (multiple of its factors), etc.) - no one knows why it
works, but finding out why would take too much time, so just don't fuck
with it. Later this term came to flavour Internet protocols, and web
pages just use a "cookie" for remembering a user. All the "magic" is
gone... sniff ;-)

As programs became larger and changes were more frequent, line numbers
became a major problem. When jumps were 20 or 30 lines away and you want
to add 50 lines of code, you have to jump to a new address space
hundreds of lines away from the code that you are modifying. And the
code around the jump is simplistic code that is really just a goto to
more code further down. You start to see code within 50 lines of each
other that refer to code 1000's of lines from each other, yet they still
refer back to some code in the 500 range (my example above, ...or below)
which starts to have REMarks around it saying things like: "Don't fuck
with this code. Use 2500 for Epson printers, Use 3000 for Teletype." So
now you have "printer" code that is really only used to convert
characters to integers, with a lot of bloat around it. But you don't
know which goto goes where and the mentality quickly became, "You fuck
with it - you own it!"

Meyer's Red Book:
A man came along and published some rules based on the state of the
industry. He wrote about how some of the current day's programmers were
desiring some STRUCTURE to their PROGRAMMING. He examined programs,
talked with peers, etc. and wrote a few books to try to promote the idea
of having Functions. He laid out rules that Functions should adhere to.
I will tell you now about two of them.

1. A single entry point.
New Programmers don't really understand the world before a single entry
point to a function. You could hop into a chunk of code and pop back out
at some point. Then someone changes the code and everything else breaks.
Now you have to figure out why. Nightmare!

2. One exit point.
This was a Good Idea in the time of Meyers' writings, since people were
popping in and out of code at random. The idea was, you come in run
through all the code and exit at one return point. I have worked on code
by people who still adhere to this concept and it has some problems,
namely that you must use gotos to make it work. People began to see that
it was more problematic to jump into code than to return from code when
you were done. Especially since the return part means you go back to the
code that called you instead of using a GOTO to jump to code that may
not have called you.
I absorbed this mantra and tell this to other people and I fully believe in it. However, I was talking to someone recently and he was saying how much he loved goto statements and how useful they were and that Microsoft had to leave them in c# because they were so useful, otherwise why would the
statement be in the language. He does not advocate using them in excess but uses them to allow himself to create a pattern that allows him to have one point of exit in a function at the end. I kept trying to convince him that gotos were not good but he seemed unconvinced by my arguements.
This person has read the "good practices" of Meyers. He is older,
probably in his 50's or higher. He is not wrong in saying gotos are not
bad, but the One Entry One Exit paradigm has been modified since
everyone got on board with not jumping into the middle of functions. Not
you can leave at will.

Once functions became their own individual entities, the new paradigm is
Get Out As Soon As Possible. If you are 7 levels into an if statement
and you know you are done, you don't need to set a flag and try to
unwind that else processing - just put a "return 0;" statement - BUT, if
you have to do some clean up, then use a (forward going, same function)
goto to hit that last few statements.

if (this)
if (that)
if (theother)
goto cleanup;
else
more();
else if (drama)
{
complicated();
return ERR;
}

cleanup:
sweep();
return (0);
I know one common use people say is for getting out of deeply nested
statements but you can easily do without gotos by using booleans or replacing sections of code with function calls.
Yes, you can "get around" gotos with booleans in all cases. But
sometimes you don't need all of that shit, you just want to go to the
label. C maxim: "Trust the Programmer"
Why if they are so bad is goto still in the language, what are the
acceptable uses of the keyword, there must be some otherwise why is the statement in the c# language, or is this just a legacy thing to attract programmers from other languages who are used to gotos?

I can't think of any really valid reason why you would use them but maybe other people have.


Hopefully, I have answered some of your questions.

To sum up: Use GOTO sparingly. Not for looping. Forward jumping to
"clean up code" that you would miss with a return or continue.

One last example, if you got this far:
I use goto in an Event-driven environment (Palm PDAs). Certain button
events are mimicked by keyboard buttons and "graffiti strokes", but are
handled in different event messages (ctlSelectEvent, keyDownEvent,
penUpEvent, etc). When I can I make a function that they all call, but
sometimes the code is so trivial (but I will not duplicate it - that's
bad) that a simple goto (backwards referencing, no less) seems best.
That way the goto is in the same function, a few lines away, and I can
keep the thing from getting itself into trouble. Even tho it reference
code above it, it is not looping, since it is a separate case statement.

--
Mabden
Nov 17 '05 #42

This discussion thread is closed

Replies have been disabled for this discussion.