I am currently in a beginning programming course at my University (I’ve got plenty of experience in the subject already, but I still have to pay for that piece of paper with time and money.) and the professor has been stressing since the beginning of the course that the break primitive that many languages provide is bad programming practice, and that many companies have policies stating that their programmers are not to use them.
Why is it considered bad practice to exit functions and loops with break primitives?
7
In switch statements, they’re pretty much essential — well, you can use extract method/class to break it down into one-line cases, but … — I don’t think that’s what your professor means.
To break from a loop is considered by some to be a goto with another name. So is returning from the middle of a method. I have even seen a similar case used against exceptions. If you think about it, it makes logical sense; all of the reasons for avoiding the use of goto would apply equally to multiple exit points from a loop or method.
All of those constructs create paths through the code that aren’t linear.
But, all that said, I would argue that they each represent a place where goto could be used to improve readability (usually by decreasing indentation), so having language constructs that represent them in different ways can only be a good thing. That way, we know, when we see one of these constructs, what the code is intending to do, and we can continue to enforce a policy of not using goto.
That is, however, my opinion. I don’t think everyone agrees with me. And I will agree with anyone who contends that when you come to write a break, or a mid-method return, or an exception that covers anything but an unexpected situation, you should probably have a think about better ways to code it. Just remember, such a thing doesn’t always exist.
2