Programming thread

LostintheCycle

Formerly His Holelineß
Joined
Apr 4, 2022
Messages
963
Reaction score
3,824
Awards
245
Our professor sat at our table during class, most of the others are fresh from programming bootcamp where they just learned absolutely everything they know about programming. He chatted about the upcoming Java project with us. I dunno why but along the way he said something about never using break statements, which puzzled me. I asked him about how you would handle cases in a switch-case statement, for example? This was the easiest example to explain that came to mind. He said just don't use switch-case statements. I was more confused now, and without thinking asked why again. He went on about functional programming, code fallthrough, state of the program, not really trying to make clear what he was saying. I did not push further because he didn't seem to be useful at explaining, or really want to. Still it stuck in my head, because it feels wrong to me, though how am I supposed to know any better?

So I have come here to ask, does anyone here more knowledgable than I, know what he means when he says Switch-Case/Break is Considered Harmful?
I looked up some terms he had used, and from what I can tell, functional programming is essentially treating functions like mathematical functions, and code fallthrough is the problem which arises if you don't break or return or whatever in a case.
I can make guesses as to why switch-case is not often useful, but not why break should be forbidden. I'm not entirely sure, so please let me know if I am wrong in my understanding.

He just told these students to never use these statements! He only elaborated when I asked him to explain, though he didn't really explain. I have a hunch he is confusing facts with opinion. I made sure to tell the table to ignore what he said once he left because it won't help them to avoid these statements.
 
Virtual Cafe Awards
never using break statements

I think the main problem (at least for me whenever i review code) is that you have multiple conditions for exiting the loop scattered all over, and keeping track of them all can be really hard sometimes as a reader. It also makes the position of your code within the loop really important when it doesnt need to be.

Its not like its definitely bad to use break statements, its more like its one of those code smells that tells you that you need to pay extra attention on whatever comes next because it might give you unpleasant surprises...

3
https://www.reddit.com/user/Nicksaurus/
level 3
Nicksaurus
· 4 yr. ago

But then on the other hand sometimes setting up the logic to only exit the loop at a single point can be way more complicated than just using an innocent little break;

7

https://www.reddit.com/user/Terofin/
level 4
Terofin
· 4 yr. ago

Sure, sometime its perfectly fine. You just need to be aware of the cost of doing it. Often it seems harmless when implemented, but becomes a problem when changes are made to the loop at a later point.

-
View: https://www.reddit.com/r/cpp_questions/comments/bc8k0l/comment/ekp8yxu/?utm_source=share&utm_medium=web2x&context=3
(same thread: )

In simplistic terms, your teachers are correct. Understanding your own code is the key to writing software the behaves predictably. Any kind of jump statement will make your code harder to understand. break and continue, in particular, can be used to write code that is quite challenging to follow, and there is almost always a better alternative. In other words, if you learn to structure your code without relying on these crutches, you will be a better developer for it.
The origin of this idea lies in the structured programming movement started by Dijkstra when he famously wrote Go To Statement considered harmful[PDF]. Dijkstra describes the problem with unstructured goto as destroying your ability to reason about the behavior of your program without also knowing its entire execution history.
This topic became somewhat religious through the 80s and 90s, with huge debates for/against, despite Dijkstra himself claiming not to be dogmatic. Even today, whenever this comes up - as you can see for yourself in this forum - you will have people making stupid arguments for/against despite being unable to articulate the reasons behind it.
All that said, keep in mind that you use goto statements all the time: for-loops, function calls, return-statements, etc. The key idea here is to restrict your usage to a subset of well-behaved jumps that do not interfere with your ability to reason about the behavior of your program. The higher-level idea is code-tractability (i.e. How well can my software's behavior fit in the head of a mere mortal?). You should feel free to use any construct - including break and continue - that makes your system easier to understand.

(idk how it is in Java tho)

It is considered bad practice because it can lead to many unwanted situations like exiting loop/method after creating stream and not closing it. But if you use it carefully then it is OK.
- https://stackoverflow.com/questions...-exit-a-loop-in-java#comment26651734_18188123


Why should we not use a "break" statement in programming?

Sage (Quora AI)
The "break" statement is a control flow statement that allows you to terminate the execution of a loop prematurely. While it can be useful in certain situations, its use can also make your code harder to read and maintain. One reason to avoid using "break" is that it can make it difficult to understand the flow of your code.
When you use "break", it can be unclear where the loop will terminate and what the final state of your program will be. This can make it harder for other developers to understand and modify your code.Another reason to avoid using "break" is that it can make it harder to test your code.
When you use "break", it can be difficult to ensure that all possible paths through your code have been tested, since the loop can terminate prematurely.There may be situations where using "break" is the best solution, but it is generally a good practice to avoid using it unless it is absolutely necessary.
Instead, consider using other control flow statements, such as "continue", "return", or "throw", to achieve the desired behavior in your code.

https://www.quora.com/profile/Akshita-Agarwal-80
Akshita Agarwal
·
Follow
Studied Computer Programming (Graduated 2020)3y

As per the standard guidelines while writing code, there must be single point of exit in a loop or function or program.

If you use too many break statements then you are violating the guideline by creating more that one point of exit.

This is just to enhances the readability of the code. And allow other developers to understand the code fast and better.
***
Profile photo for Musfequr Rahman
Musfequr Rahman
·
Follow
Amature Programmer5y

Because it might cause your program to have a memory leak or crash.

The Break command was originally meant for (as far as I know) Switches.

When a break is used outside of a switch, it forces a loop to abruptly end. Without allowing it to resolve.
***
Profile photo for Andrea Cesaro
Andrea Cesaro
·
Follow
working as Software Engineer5y

Using break is fine but it can make hard the refactoring, in this case use a specific condition in your loop. In general use break only when your intentions reamin clear reading the code and when you think it can give you performance advantage (and measure it!).
(- quora)

You could read Donald Knuth's 1974 paper Structured Programming with go to Statements, in which he discusses various uses of the go to that are structurally desirable. They include the equivalent of break and continue statements (many of the uses of go to in there have been developed into more limited constructs). Is your boss the type to call Knuth a bad programmer?
(The examples given interest me. Typically, break and continue are disliked by people who like one entry and one exit from any piece of code, and that sort of person also frowns on multiple return statements.)
(- https://softwareengineering.stackexchange.com/posts/58257/revisions)
(--
Most of the people who like functions and procedures to have single entry and exit points grew up on Pascal. Pascal was not the first language that I learned, but it had a profound impact on how I structure code to this day. People always comment on how easy it is to read my Java code. That's because I avoid multiple exits points as well as intermixing declarations with code. I try my best to declare every local variable used in a method at the top of the method. This practice avoids code ramble by forcing me to keep methods succinct.
bit-twiddler
Mar 15, 2011 at 15:37
  • 6

    Pascal also had nested functions. Just sayin'...
    Shog9
    Mar 15, 2011 at 17:32
  • 6

    From what I remember, back in the day, the main reason that people didn't like multiple return statements in functions was because debuggers didn't handle them properly. It was a real pain to set a breakpoint at the end of a function but you never hit it because of an earlier return statement. For every compiler I use nowadays that is no longer an issue.
  • ;***
  • I do not believe they are bad. The idea that they are bad comes from the days of structured programming. It is related to the notion that a function must have a single entry point and a single exit point, i. e. only one return per function.
    This makes some sense if your function is long, and if you have multiple nested loops. However, your functions should be short, and you should wrap loops and their bodies into short functions of their own. Generally, forcing a function to have a single exit point can result in very convoluted logic.
    If your function is very short, if you have a single loop, or at worst two nested loops, and if the loop body is very short, then it is very clear what a break or a continue does. It is also clear what multiple return statements do.
    These issues are addressed in "Clean Code" by Robert C. Martin and in "Refactoring" by Martin Fowler.
)
***
The "badness" is dependent on how you use them. I typically use breaks in looping constructs ONLY when it will save me cycles that can't be saved through a refactoring of an algorithm. For instance, cycling through a collection looking for an item with a value in a specific property set to true. If all you need to know is that one of the items had this property set to true, once you achieve that result, a break is good to terminate the loop appropriately.
If using a break won't make the code specifically easier to read, shorter to run or save cycles in processing in a significant manner, then it's best not to use them. I tend to code to the "lowest common denominator" when possible to make sure that anyone who follows me can easily look at my code and figure out what's going on (I am not always successful at this). Breaks reduce that because they do introduce odd entry/exit points. Misused they can behave very much like an out of whack "goto" statement.

---

 
Last edited:
Virtual Cafe Awards

Collision

Green Tea Ice Cream
Joined
Jun 5, 2022
Messages
381
Reaction score
1,420
Awards
126
So I have come here to ask, does anyone here more knowledgable than I, know what he means when he says Switch-Case/Break is Considered Harmful?
This sounds like a programming professor-ism to me. What he probably means is that a break statement in a loop can be harder to read than using a variable to control the loop. As an example you might write a program like:
Java:
public class Collatz {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int number = input.nextInt();
        while (true)
        {   
            System.out.println(number);
            if (number == 1)
            {
                break;
            }
            if (number % 2 == 0)
            {
                number = number / 2;
            }
            else
            {
                number = 3 * number + 1;
            }
        }
    }
}
This is example is more or less trivial and so it's not too bad to track where you can escape the loop. However, we can imagine a version where our loop is much bigger. Perhaps hundreds or thousands of lines of code (if you would like I can post a real world example of this written in C++). When that happens it becomes necessary to track every individual case where we write if (x) { break; }. It would be better to rewrite our infinite loop to look like this:
Java:
public class Collatz {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int number = input.nextInt();
        boolean quit = false;
        while (!quit)
        {   
            System.out.println(number);
            if (number == 1)
            {
                quit = true;
            }
            if (number % 2 == 0)
            {
                number = number / 2;
            }
            else
            {
                number = 3 * number + 1;
            }
        }
    }
}
Now, at the very least, we know what the condition is that causes the program to exit the loop. Whenever quit is true then we know the program will exit the loop. I think, this is especially important when using a debugger because now we can check the state at any point in the program. In the original example, there's no specific value for a debugger to watch so, you're left having to track all of the individual cases again. In this particular case (i.e., the iterative Collatz function), we can further improve the readability of our loop like this:
Java:
public class Collatz {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        for (int number = input.nextInt(); number != 1; number = number % 2 == 0 ? number / 2 : 3 * number + 1)
        {   
            System.out.println(number);
        }
        System.out.println(1);
    }
}
This is an improvement, in my opinion, because, in this specific case, we know that the loop has a control value (i.e., number), a single concise exit condition, and a relatively simple update step. Now everything we need to know about the loop is on one line. At the end of the day, all of this is purely stylistic. There's probably little or no performance difference at runtime so I wouldn't consider any of these to be harmful. I do think the earlier to variations are sloppy though. In real world code, there are often places where break, continue, and even the unfairly maligned structured goto are more succinct and appropriate than the alternative. These statements are available for a reason and you should never feel as though a tool is universally wrong.

As for the switch statement, I think your professor is simply incorrect. In one of the first programming classes I ever took, and one of the few where I felt the professor was worth taking seriously, I was taught to always write the least amount of code possible. Practically, I don't think this is always the right advice, after all there is no such thing as a silver bullet, but I do think it's a good general approach. The switch statement is appropriate, in my opinion, in at least two important cases. The first case is where you would write vastly more code using if/else if/else statements. The second case is anytime the compiler might be able to optimize the entire operation away as an array access (i.e., change the statement into a look up table). Regardless, it's almost always appropriate to use a break statement in each case of a switch statement. I don't know about Java specifically but in C++ most compilers will issue warnings if you do not break a case that has some number of statements within it. Sometimes fall-through is desirable so, just like with loops, I don't think you should universally commit yourself to any hard rules.

Unfortunately, professors, and their various underlings, are often less capable than you would expect. I have a few stories like this of my own where I could not get a straight answer from a supposed expert even in cases where the expert was correct! If your professor is really committed to this dogmatic position then I wouldn't bother fighting him on it. Instead, just keep in mind that language features are there for a reason and even if a PhD says they're bad someone else probably uses them every day. There are no silver bullets in engineering and the most important thing you can learn is how to reason critically about all of the options you have.
 
Virtual Cafe Awards

RisingThumb

Imaginary manifestation of fun
Joined
Sep 9, 2021
Messages
713
Reaction score
1,745
Awards
173
Website
risingthumb.xyz
I can make guesses as to why switch-case is not often useful, but not why break should be forbidden. I'm not entirely sure, so please let me know if I am wrong in my understanding.
Break isn't exclusive to switch-case, but also to while loops and for loops. For switch-case, it encourages:
  • Fallthrough-style code. On a codebase with multiple developers if one misreads a fallthrough or forgets it fallsthrough, that can be bad.
  • Abuse of single-responsibility principle. Switch-case is already usually used when a variable can be many values(usually enums). Rather than representing this in code with a switch-case, it's often better represented as a map with lambda functions etc. Most of the time, a data structure representation is what you actually want.
  • Depending on the language, it's usable with GOTO. While there are cases when a goto *should* be used(exiting from a heavily nested loop... if it's that nested, reevaluate if you're doing it right), you can goto with a switch statement. For C#, dunno about Java. Language-specific.
  • Reducing code churn(number of code changes, so smaller diffs for PR reviews) is a natural want, so a switch statement gets bloated as developers reduce code churn
  • For loops with multiple nesting. Pure breaking should be avoided in favour of either goto, flags(variable flags as Collision shows above) or predicate functions https://llvm.org/docs/CodingStandards.html#turn-predicate-loops-into-predicate-functions
  • Also with while loops, you should generally avoid them anyway, because if you reason poorly, bam, infinite loop.
As Collision also mentioned, if you're programming in a functional style, there's those considerations, but most languages are OOP or Procedural or a mixture, so functional style considerations aren't always there(or only sprinkled in with lambda functions).

My opinion? Your professor is being too dogmatic. Academics are often too dogmatic, and if pressed, can't elaborate their reasons. They're this way because they've never worked a day in the software development industry usually(or if they have, they followed a Senior's or Lead's enforcement of style). Naturally follow his rules if you want a good grade, but ditch it if you want in personal programming.

Try programming with switch cases everywhere. Try programming with global variables and global state. Try programming with the functional paradigm and using predicates and early return guards. Try programming with GOTO. Try programming in a data oriented fashion, preferring complex data structures to complex algorithms. A lot of these dogmatic practices arise and are sometimes enforced with good reason, but it normally requires you shooting yourself in the foot once to understand why it's a good or a bad idea.

Sometimes it's even a GOOD idea, but would be less readable to other programmers and if you work on enterprise software, readability and maintainability is more important.
 
Virtual Cafe Awards

RisingThumb

Imaginary manifestation of fun
Joined
Sep 9, 2021
Messages
713
Reaction score
1,745
Awards
173
Website
risingthumb.xyz
There are no silver bullets in engineering
There is. It's called don't code. Alternatively less code, is more reliable, which is usually better too. In fact the simplest silver bullet, is less is more.
 
Virtual Cafe Awards

shinobu

Jack of all trades
Joined
Dec 17, 2021
Messages
356
Reaction score
2,611
Awards
186
So I have come here to ask, does anyone here more knowledgable than I, know what he means when he says Switch-Case/Break is Considered Harmful?
I looked up some terms he had used, and from what I can tell, functional programming is essentially treating functions like mathematical functions, and code fallthrough is the problem which arises if you don't break or return or whatever in a case.
I can make guesses as to why switch-case is not often useful, but not why break should be forbidden. I'm not entirely sure, so please let me know if I am wrong in my understanding.
Everyone else's answer is mostly what I think, too, so I won't harp on that. At the beginning of your programming experience you shouldn't reject anything (within reason) - as you get experience you'll learn what's useful for you and what isn't.

But lately I've been studying functional programming and it's interesting that languages from the ML family (like Haskell, SML and OCaML) have pattern matching, which is like a stronger version of switch forms. And languages like Prolog have unification at their core, which is the most general form of pattern matching (a Prolog program is basically a switch statement and each case uses unification to pattern match, which is like a switch, so it's switchception). And some languages from the Lisp family have continuations, which are like a super-break.
 
Virtual Cafe Awards

LostintheCycle

Formerly His Holelineß
Joined
Apr 4, 2022
Messages
963
Reaction score
3,824
Awards
245
Thank you @Collision and @RisingThumb, it really smelled like one of those weird ideas programmers spread about things which are always never good, but since I have a personal disdain for him I thought that was clouding my judgment, and needed to properly see what was behind those ideas. Turns out I was right.
Industry experience thing checks out, just checked linkedin and he's clocked in under two years in web dev before jumping into academia :IAMINIMMENSEPAIN:
 
Virtual Cafe Awards

Similar threads