When is it appropriate to use a break? - break

My questions is basically all in the title. I have no real application in mind, I'm just trying to make sure I use generally accepted good coding practices, and I remember my CS professor saying that breaks are generally avoided when possible, but he never told us why.
I would ask him myself, but he's out of his office this summer.

This is a theological issue. People who are opposed to the use of break (or continue for that matter) say that it makes the control flow of the program harder to follow and thus makes the program less readable. But an easier way to make readable code is simply to make shorter functions, use meaningful variable names, comment appropriately, etc.

Sometimes professors are wrong.
He may object to skipping out of a loop right in the middle of it. This is akin to using a return statement in the middle of a function...some consider that blasphemy.
What ever is the simplest, and produces the most easily maintainable code, is what should be used.

Generally speaking, you will use 'break' to get out of cycles when a certain condition is met (for instance, when you've found what you're looking for, etc.); I don't consider it 'evil' such as the infamous GOTO statement, but reasonable people will differ.

What Dijkstra said was harmful about goto statements - http://drdobbs.com/blogs/cpp/228700940
and https://softwareengineering.stackexchange.com/questions/58237/are-break-and-continue-bad-programming-practices

Your professor was saying "breaks should be avoided" because they are similar to the now-taboo goto statement. However to say "breaks should be avoided whenever possible" is just wrong.
Break exists for readability. You can do anything without break that you can with it, but that doesn't mean you should. Sometimes it just makes sense to make a statement like "In this condition, break out of this loop." or "In this condition, return from this function."
It's a bad idea to use break for program flow in a nested for loops in a way that might give a casual reader some confusion.
Simple rule of thumb: Does using break here (instead of additional if/thens, another boolean, etc.) make this easier to understand or harder to understand? It's that simple.

Ask your professor to try writing a switch statement in any C-style language without break. It can be done I'm sure, but the resulting code is not going to be any more readable.
switch (someExpression) {
case enumVar.CaseA:
// do things here, but don't you dare break!
case enumVar.CaseB:
// do other things - possibly unrelated or contradictory to CaseA
// ... and so on
}

Related

Dictionary bracket syntax not allowed in "match" statements

Trying to use dictionary bracket syntax in match statements and it doesn't let me. Is this intentional by design, or am I missing something?
Below doesn't work
match curr:
myDict["one"]:
#do something
myDict["two"]:
#do something
I am forced to use the dot syntax instead and it works...is this by design?
I can't conclude that it is intentional, but I can tell you it does not work and will not work.
In Godot 3, the parser does not support this syntax, which might have been oversight. Or it might have been that the parser was already becoming a mess and hard to maintain, so features that weren't critical weren't considered? Perhaps… After all, GDScript was reworked from the ground up for Godot 4. So…
In Godot 4, the compiler does not support it, and there is a reason: it wants a constants, which also allow some optimizations. Does Godot 3 care about that? Nope, you can use variables, and there is no problem. And no, the match is not optimized in Godot 3, nothing is, it is all interpreted.
Do you really care if it was intentional?
You are likely OK to do this with a bunch of if statements. After all, if you are willing to write a case for each item in the dictionary, they probably are a manageable amount.
You could also throw design patterns at it. The strategy pattern comes to mind.

Goto is considered harmful, but did anyone attempt to make code using goto re-usable and maintainable?

Everyone is aware of Dijkstra's Letters to the editor: go to statement considered harmful (also here .html transcript and here .pdf). I was wondering is anyone attempted to find a way to make code using goto's re-usable and maintainable and not-harmful by adding any other language extensions or developing a language which allows for gotos.
The reason I ask the question is that it occurs to me that code written in Assembly language often used goto's and global variables to make the program work well within a limited space. The Atari 2600 which had 128 bytes of ram and the program was loaded from ROM cartridge. In this case, it was better to use unstructured programming and to make the most of the freedoms this allows to make the most of a very limited space for the program.
When you compare this with a game programmed today without the use of gotos, the game takes up much more space.
Then it occurs to me that perhaps its possible to program with the use of gotos if some rules or other language changes are made to support this, then the negative effects of gotos could be reduced or eliminated. Has anyone tried to find a way to make goto's NOT considered harmful by creating a language or some rules to follow which allow gotos to be not harmful.
If no-one looked for a way to use gotos in a non-harmful way then perhaps we adopted structured programming un-necessarily based solely on this paper? Perhaps there is another solution which allows for the use of gotos without the down-side.
Comparing gotos to structured programming is comparing a situation where the programmer has to remember what every labels in the code actually mean and do, and where there are, to a situation where the conditional branches are explicitly described.
As of the advantages of the goto statement regarding the place a program might take, I think that games today are big because of the graphic and sound resources they use. That is, show 1,000,000 polygons. The cost of a goto compared to that is totally neglectable.
Moreover, the structural statements are ultimately compiled into goto ("jmp") statements by the compiler when outputting assembly.
To answer the question, it might be possible to make goto less harmful by creating naming and syntax conventions. Enforcing these conventions into rules is however pretty much what structural programming does.
Linus Torvald argued once that goto can make source code clearer, but goto is useful in so very special cases that I would not dare use it as a programmer.
This question is somehow related to yours, since I think this one of the most common situations where a goto is needed.

Should I match the curly brace usage of the previous author?

When working on code from multiple authors, I often encounter the issue of curly-brace preference (same line vs new line). Is it good/bad practice or even a non-issue when it comes to matching the existing style vs using your own preference?
Does the situation change if you are adding new code to a Class vs modifying existing code? Finally, if style should be matched, how far should the match propagate? i.e. the file, the class, subclasses etc.
Example:
if(this)
{
doThat();
}
Vs.
if(this){
doThat();
}
Generally speaking, inconsistently formatted code will be more difficult to read and understand than code formatted in a style other than your own.
When working on an open source project, it is considered polite to match the style in use. For code you won't be sharing, either follow the style or run all the existing code through a reformatter.
It matters a great deal if a lot of code has been checked into a version control system. There will be a lot of noisy change in the history for a mere brace style change. I wouldn't do it for its own sake. You're in Rome....
If you will be sharing this, match his style for consistency. If not, do what you find comfortable. I personally prefer your style.
Try to talk with your coworkers and decide on a consistent style. Once you do that, write all new code in that style and convert old code if necessary. This is an issue specific to the project and the people working on it.
On the rare occasion that you can't come to a consensus, I wouldn't worry too much; there are far too many bugs in the world for people to be spending their time moving braces around. :D
It does not matter (code wise) where you place the curly braces, it is just a matter of preference. More experienced coders tend to put it on the same line, but I like to put it on the next line because it helps me see blocks of code easier. If you wish coding conventions to go as far as curly braces, then consult your team and choose one, but they'll probably laugh lol
There is nothing that irks me more than perusing code and finding numerous mismatched styles sprinkled throughout. If you are going to collaborate with someone on a program, than either explicit or implicit, standards should be used. Something as simple as a curly brace doesn't matter in the least, but when your project gets reviewed by management and you can't even get that one little thing matched up throughout it looks bad. Or if you are working on a personal project with friends and then decide to have others join, the project is going to start off looking unprofessional. I would say when working in a group like this, it is less about personal opinion, than it is about group standards.

When is it best to change code to match standards?

I have recently been put in charge of debugging two different programs which will eventually need to share an XML parsing script, at the minimum. One was written with PureMVC, and another was built from scratch. While it made sence, originally, to write the one from scratch (it saved a good deal of memory, but the memory problems have since been resolved).
Porting the non-PureMVC application will take a good deal of time and effort which does not need to be used, but it will make documentation and code-sharing easier. It will also lower the overall learning curve. With that in mind:
1. What should be taken into account when considering whether it is best to move things to one standard?
(On a related note)
Some of the code is a little odd. Because the interpreting App had to convert commands from one syntax to another, it made sense to have an interpreter Object. Because there needed to be communication with the external environment, it made more sense to have one object interact with the environment, and for that to deal with the interpreter exclusively.
Effectively, an anti-Singleton was created. The object would only interface with the interpreter, and that's it. If a member of another class were to try to call one of its public methods, the object would raise an Exception.
There are better ways to accomplish this, but it is definitely a bit odd. There are more standard means of accomplishing the same thing, though they often involve the creation of classes or class files which are extraordinarily large. The only solution which I could find that was standards compliant would involve as much commenting and explanation as is currently required, if not more. Considering this:
2. If some code is quirky, but effective, is it better to change it to make it less quirky, even if it is made a more unwieldy?
In my opinion this type of refactoring is often not considered in schedules and can only be done when there is extra time.
More often than not, the criterion for shipping code is if it works, not necessarily if it's the best possible code solution.
So in answer to your question, I try and refactor when I have time to do so. Priority One still remains to produce a functional piece of code.
Things to take into account:
Does it work as-is?
As Galwegian notes, this is the only criterion in many shops. However, IMO just as important is:
How skilled are the programmers who are going to maintain it? Have they ever encountered nonstandard code? Compare the cost of their time to learn it (including the cost of delayed dot releases) to the cost of your time to refactor it.
If you're maintaining it, then instead consider:
How much time will dealing with the nonstandard code cost you over the intended lifecycle of the codebase (e.g., the time between now and when the whole thing is rewritten)?
That's hard to guess, but consider that many codebases FAR outlive the usefulness envisioned by their original authors. (Y2K anyone?) I've gradually developed a sense of when a refactoring is worthwhile and when it's not, mostly by erring on the side of "not" too often and regretting it later.
Only change it if you need to be making changes anyway. But less quirky is always a good goal. Most of the time spent on a particular piece of software is in maintenance, so if you can do something to make that easier, you'll be reducing the overall time spent on that piece of code. Nonetheless, don't change something if it's working and doesn't need any modifications.
If you have time, now. If you don't have time and it can be avoided, later.

Why is goto poor practise? [duplicate]

This question already has answers here:
Closed 14 years ago.
This question is a duplicate of Goto Still Considered Harmful. If you wish to discuss this further please use the original question.
Why exactly is GOTO poor programming practise? It makes sense on some occasions to use it.
Note that Djkstra wrote "GOTO Considered Harmful", not "GOTO Considered Deadly". It has its places. Unfortunately, the judgement to know when to use it comes after you've got some experience in maintaining other people's code, especially code that was written years ago by people who no longer work in your company. Thus, it's best to avoid goto as much as you can until you have that experience.
It encourages bad coding style, basically. See: Goto Considered Harmful [pdf]
It can rapidly lead to spaghetti code.
It means you haven't designed the code procedurally.
If you build your whiles and ifs properly, you should rarely ever need goto.
Rarely is the key word. There are times where it's useful. In that sense, many people nowadays just explicitly throw and catch exceptions, just to avoid the dreaded goto.
Because the structure of the code can be difficult to follow.
This
y:
// do more stuff
goto x
p:
// do stuff
// then done
goto y;
x:
// do a bunch of stuff
if (...)
goto y;
else
goto p;
done:
is much less clear than
int main()
{
x();
}
function p()
{
if (...)
{
return;
}
}
function x()
{
if (...)
{
return;
}
else
{
p();
}
}
GOTO short circuits your control flow, thereby undermining your design and opening the door to debug and maintenance nightmares.
Readability becomes a problem, and flow of logic can have unintended effects by the use of goto.
I think its funny that the .net compiler will change some case/switch statements to use goto.
In some cases it makes sense. But, in the majority of cases use of it it considered poor practice because it can make the execution path of code tricky to read compared to using structured code such as for loops and while loops.
When you look at a goto or a label, you don't really know where is goes to or comes from without reading or searching through the code for the label name. This is tricky especially if the goto doesn't fit on the same screen as the label. Compare this to a for loop or a while loop or an if.. you can tell from the structure (i.e. indenting of the code) what the execution path is.
Having said this, it sometimes is useful, especially for example when jumping out of some nested for loops that are digging for a particular value inside a multi-dimensional array. You could use a goto here to jump out of the for loops when the correct value is found.

Resources