When coding, why is exiting a loop using break; bad?

  • Thread starter Thread starter r.meghdies
  • Start date Start date
  • Tags Tags
    Break Coding Loop
Click For Summary
Exiting a loop using "break;" in Java can lead to code that is difficult to follow, as it may hide exit criteria deep within the loop. This can create surprises for readers, making the logic harder to understand. Clearer alternatives involve placing exit conditions at the top of the loop for better readability. Labeled breaks can further complicate code, resembling the problematic "goto" statements. Maintaining code readability is crucial for future developers who will work on the code.
r.meghdies
When coding, why is exiting a loop using"break;" bad?

when coding, to exit a loop i was told using "break;" (in java) is really bad...why!
 
Physics news on Phys.org
It makes the code hard to follow. If the exit criteria is at the top of the loop, it is easy for the reader to figure out what is happening. However a break buried deep in a loop can do something surprising and surprises make code very difficult to follow. Then there are labeled breaks which act somewhat the same as a goto in C (more or less) and can quickly turn your code into an unreadable mess.

Breaks are always ok in switch statements. But elsewhere USE CAUTION!

Remember any significant chunk of code will be maintained by someone else and that someone will want easy to read code not one riddled with hidden break statements.
 
Last edited:

Similar threads

Replies
1
Views
1K
Replies
3
Views
2K
  • · Replies 21 ·
Replies
21
Views
3K
  • · Replies 20 ·
Replies
20
Views
5K
  • · Replies 3 ·
Replies
3
Views
1K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 7 ·
Replies
7
Views
3K
  • · Replies 4 ·
Replies
4
Views
5K
  • · Replies 10 ·
Replies
10
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K