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
SUMMARY

Exiting a loop using "break;" in Java is considered poor practice due to its potential to obscure the flow of code, making it difficult for others to follow. When exit criteria are placed at the beginning of the loop, the logic remains clear, whereas a "break;" statement buried within the loop can lead to unexpected behavior. Labeled breaks, akin to the "goto" statement in C, can further complicate readability and maintainability. While "break;" is acceptable in switch statements, caution is advised when using it in other contexts.

PREREQUISITES
  • Understanding of Java programming language
  • Familiarity with loop constructs in Java (for, while, do-while)
  • Knowledge of control flow statements (if, switch, break)
  • Basic principles of code readability and maintainability
NEXT STEPS
  • Research best practices for loop control in Java
  • Explore alternatives to "break;" for loop termination
  • Learn about code readability principles and their impact on maintenance
  • Investigate the use of labeled statements in Java and their implications
USEFUL FOR

Java developers, software engineers, and anyone interested in writing maintainable and readable 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
2K
Replies
3
Views
2K
  • · Replies 21 ·
Replies
21
Views
3K
  • · Replies 20 ·
Replies
20
Views
6K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 7 ·
Replies
7
Views
3K
  • · Replies 10 ·
Replies
10
Views
2K
  • · Replies 4 ·
Replies
4
Views
5K
  • · Replies 1 ·
Replies
1
Views
2K