1

this is my first post here! I'm reading a book on Java and I ran across something I am unsure of. In the book, they claim that using a break command in loops "destructures the code". 1) Can anyone give me some insight as to what this means? 2) Furthermore, what are the drawbacks of "destructuring the code"?

Thanks in advance!

Sami
  • 579
  • 5
  • 25
  • 1
    welcome to stack overflow! I believe what they're trying to say is that `break` statements break the flow of code, which is why they're generally considered bad practice. You want loops to terminate naturally, because of a logical condition you set. See http://stackoverflow.com/questions/3922599/is-it-a-bad-practice-to-use-break-in-a-for-loop – pennstatephil Jun 05 '14 at 18:59
  • Ahhh, if only they said it that way. Thanks for the help! – Sami Jun 05 '14 at 19:00

2 Answers2

3

Writing code that works isn't always the most important part. Writing easy to read will no only help you look back at your source code, but others who will.

You were probably introduced to loops to help make your life easier.

Lets say I wanted to print "Hello World" five times, I could


A) System.out.println("Hello World");

System.out.println("Hello World");
System.out.println("Hello World");
System.out.println("Hello World");
System.out.println("Hello World");

B)

for(int i = 0; i < 5; i++) {
     System.out.println("Hello World");
}

Which is easier to read? Imagine instead of 5, we wanted to do it 1,000x times. You can clearly see that loops help keep code clean.

Now, to your questions

1)Can anyone give me some insight as to what this means - referring to "destructures the code"

This is referring to keeping code clean. Your code should have easy to follow logic.

2)Furthermore, what are the drawbacks of "destructuring the code"?

The drawback to "destructuring" is poor code management and increased chance of bugs. When your code is not properly structured, others will have a hard time reading it and you will hate looking back at it in a few weeks.

The extensive usage of breaks will force readers of your code to scroll through the code and line up the correct loop that is being broken out of. Overly using it will cause confusion and essentially be mimicking "GoTo" statements.

Greg Hilston
  • 2,397
  • 2
  • 24
  • 35
0

Destructuring means to break the structure of your code. The original intention of break was not to jump out of for loops. That's the intention of the loop condition. At one time it was considered poor practice, but nowadays it is a matter of style. I have used break in my for loops with no complaints from reviewers.

Engineer2021
  • 3,288
  • 6
  • 29
  • 51