14 Replies - 1343 Views - Last Post: 23 October 2013 - 09:58 PM

#1 smoothedatol412  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 78
  • Joined: 22-May 12

Question about taking a break out of a loop

Posted 20 October 2013 - 11:59 AM

I have read a few articals over the weekend about how the break and continue statements are too much like a goto statement in programming,
but I am having a hard time trying to take the idea and appy it to my coding practice.
the following is an example

while(condition A){
    {block A}
    if(condition B)/>{
        break;
    }
    {block B}
}



The point I am trying to ask is, how can rewrite this structure so that the break statement is removed yet the script is functional the same.

This post has been edited by smoothedatol412: 20 October 2013 - 12:01 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Question about taking a break out of a loop

#2 andrewsw  Icon User is online

  • It's just been revoked!
  • member icon

Reputation: 3838
  • View blog
  • Posts: 13,595
  • Joined: 12-December 12

Re: Question about taking a break out of a loop

Posted 20 October 2013 - 12:09 PM

What's wrong with break, and continue? They are excellent options to have, and can make code quite neat IMO.

Otherwise, you'll need a separate boolean variable that you can set to true or false, and test this (a couple of times) to decide whether the loop needs to be entered again.

bool keepGoing = true;
while (conditon first and keepGoing) {
    // statements
    if (condition second) {
        keepGoing = false;
    }
    if (keepGoing) {
        // more statements
    }
}

This post has been edited by andrewsw: 20 October 2013 - 01:57 PM

Was This Post Helpful? 2
  • +
  • -

#3 smoothedatol412  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 78
  • Joined: 22-May 12

Re: Question about taking a break out of a loop

Posted 20 October 2013 - 08:18 PM

There is a few hard line software writer that say you should not use continue or break statements because they are too much like a goto statement, thus cause lazy programming and not "pretty" code. I do not know if I totally agree with this, but I never hurts to try something new in programming to increase the tools you can use.
Was This Post Helpful? 0
  • +
  • -

#4 jon.kiparsky  Icon User is offline

  • Pancakes!
  • member icon


Reputation: 8037
  • View blog
  • Posts: 13,753
  • Joined: 19-March 11

Re: Question about taking a break out of a loop

Posted 20 October 2013 - 10:45 PM

Those programmers are confused, and incorrect. The problem with the goto statement is that it is unrestricted: that it can drop the point of execution effectively anywhere in the code. Restricted jumps, such as conditional statements, while and for loops, and method or function calls, are tools to constrain these jumps, and this is generally sufficient to create structured code.

Since in all of the languages I know break and continue statements are very tightly defined, and can lead the user to only one well-defined location, they are also structured jumps and therefore by definition not unrestricted. So no, break and continue are not in any way like a goto. Some people will argue that they are inherently like goto since they are necessarily executed using jumps in the underlying object code. This is also incorrect and confused: if the language itself does not provide a goto instruction, then you cannot use a break (or an if, or a while) to create a goto, so you cannot use the language to create the buges that a goto can create.

It is probably true that someone can use a break or a continue badly, and create confusing code, but of course any language construction can be deployed in a confusing way, if you put your mind to it. So if someone wants to argue that early exit from a loop is a bad use of a language, they can make that case, but if they argue that early exit instructions are equivalent to a goto, then they're sorely and sadly mistaken.
Was This Post Helpful? 0
  • +
  • -

#5 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3667
  • View blog
  • Posts: 11,499
  • Joined: 05-May 12

Re: Question about taking a break out of a loop

Posted 21 October 2013 - 05:52 AM

I find it strange that some people will accept break and/or continue within a loop, but crucify you if you have a return within it.
bool ContainsFoo(List<T> items, T foo)
{
    foreach(T item in items)
    {
        if (item == foo)
            return true;
    }
    return false;
}



To me, if it's okay to have break or continue, the return should equally be acceptable.
Was This Post Helpful? 0
  • +
  • -

#6 cfoley  Icon User is offline

  • Cabbage
  • member icon

Reputation: 2071
  • View blog
  • Posts: 4,307
  • Joined: 11-December 07

Re: Question about taking a break out of a loop

Posted 21 October 2013 - 08:13 AM

Most of these rules have sensible reasons, or at least good intentions. The problem is when they are taken out of context and forced arbitrarily on other programmers.

In the distant past, people wrote functions that were several pages long and indentations several levels deep. Things like break and multiple returns only increase the chaos so banning them reigns it in a bit. Of course, the real problem was the long functions in the first place. Now that we all write short, testable functions break et al can usually be used to make things even clearer.
Was This Post Helpful? 1
  • +
  • -

#7 Momerath  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1012
  • View blog
  • Posts: 2,444
  • Joined: 04-October 09

Re: Question about taking a break out of a loop

Posted 21 October 2013 - 10:18 AM

*
POPULAR

View PostSkydiver, on 21 October 2013 - 05:52 AM, said:

I find it strange that some people will accept break and/or continue within a loop, but crucify you if you have a return

It violates the "single entry, single exit" principle. This, IMHO, is more important in languages with unmanaged memory as it can easily cause memory leaks if you don't take care of things before you return. With the single return at the end, all memory can be cleaned up there.

In managed memory languages it's not as vital, but the choice should be made for each method written. Sometimes it is clearer to exit in the middle of a method (and can save a lot of indenting), other times it makes thing confusing.

YMMV. Void where prohibited. Wear safety goggles while operating.
Was This Post Helpful? 5
  • +
  • -

#8 andrewsw  Icon User is online

  • It's just been revoked!
  • member icon

Reputation: 3838
  • View blog
  • Posts: 13,595
  • Joined: 12-December 12

Re: Question about taking a break out of a loop

Posted 21 October 2013 - 10:28 AM

Momerath That makes a lot of sense ;)

I suppose another view could be that if your single procedure is so detailed, or extensive, that having more than one exit-point becomes a concern, then you should be more concerned with refactoring your code.

I do. however. concede that having several exit-points would cause me pause for thought.. (Does this contradict my previous paragraph? :dontgetit: )

This post has been edited by andrewsw: 21 October 2013 - 10:38 AM

Was This Post Helpful? 1
  • +
  • -

#9 jon.kiparsky  Icon User is offline

  • Pancakes!
  • member icon


Reputation: 8037
  • View blog
  • Posts: 13,753
  • Joined: 19-March 11

Re: Question about taking a break out of a loop

Posted 21 October 2013 - 12:00 PM

View Postandrewsw, on 21 October 2013 - 12:28 PM, said:

Momerath That makes a lot of sense ;)/>

I suppose another view could be that if your single procedure is so detailed, or extensive, that having more than one exit-point becomes a concern, then you should be more concerned with refactoring your code.



I agree on both counts. The refactoring point is particularly important. One of my self-taught programming tics is, whenever I put in a break, I always stop to think about whether that should be a return instead - that is, whether this piece of code should be a method or a function. Often, the refactoring happens on the spot, and a lot of complexity just never gets written.

Quote

I do. however. concede that having several exit-points would cause me pause for thought..


I would see several exit points as perfectly reasonable. For me, the important thing is, when you're done you should stop doing. If I know that I'm finished, continuing any further can only add more bugs, it can't help me in any way.
Was This Post Helpful? 2
  • +
  • -

#10 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3667
  • View blog
  • Posts: 11,499
  • Joined: 05-May 12

Re: Question about taking a break out of a loop

Posted 21 October 2013 - 10:37 PM

View Postjon.kiparsky, on 21 October 2013 - 03:00 PM, said:

I would see several exit points as perfectly reasonable. For me, the important thing is, when you're done you should stop doing. If I know that I'm finished, continuing any further can only add more bugs, it can't help me in any way.

Is that a corollary to the "fail fast" principle? :)
Was This Post Helpful? 0
  • +
  • -

#11 jon.kiparsky  Icon User is offline

  • Pancakes!
  • member icon


Reputation: 8037
  • View blog
  • Posts: 13,753
  • Joined: 19-March 11

Re: Question about taking a break out of a loop

Posted 21 October 2013 - 10:44 PM

View PostSkydiver, on 22 October 2013 - 12:37 AM, said:

View Postjon.kiparsky, on 21 October 2013 - 03:00 PM, said:

I would see several exit points as perfectly reasonable. For me, the important thing is, when you're done you should stop doing. If I know that I'm finished, continuing any further can only add more bugs, it can't help me in any way.

Is that a corollary to the "fail fast" principle? :)/>



"Succeed fast". :)
Was This Post Helpful? 0
  • +
  • -

#12 farrell2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 866
  • View blog
  • Posts: 2,657
  • Joined: 29-July 11

Re: Question about taking a break out of a loop

Posted 22 October 2013 - 05:15 AM

View PostSkydiver, on 21 October 2013 - 12:52 PM, said:

I find it strange that some people will accept break and/or continue within a loop, but crucify you if you have a return within it.
bool ContainsFoo(List<T> items, T foo)
{
    foreach(T item in items)
    {
        if (item == foo)
            return true;
    }
    return false;
}



To me, if it's okay to have break or continue, the return should equally be acceptable.


Return in a loop is bad if there is other processing you need to do after the loop. It leads to confusion. Yes, there are people who will completely forget that return returns from the method, break returns from the loop. :)

//print 1 to 10.
public static void count() {
		int count = 1;
		while (count < 10) {
			System.out.println(count++);
			if (count == 10) {
				//return
				break;
			}
		}
                //other processing.
		System.out.println(count);
	}


Was This Post Helpful? 0
  • +
  • -

#13 smoothedatol412  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 78
  • Joined: 22-May 12

Re: Question about taking a break out of a loop

Posted 23 October 2013 - 04:11 PM

wow this topic gained a few more replies then I though it it was I was way with midterm the past few days.
Most of the replies I have read, the main idea I can take with me is the programming style of the coder who uses it. Since no two coders are alike, the way they can express themselves with code will be just as different.


What about the continue statement? I have seen how the break statement can be replaced with boolean variables and return statements. But what about the continue statement? How could the structure be set up in the same way were a statement or a block when executed will start the next iteration of the looping structure

while(condition A){
...
if(condition B )/>{
continue;
} // if
..
} // while

This post has been edited by smoothedatol412: 23 October 2013 - 04:14 PM

Was This Post Helpful? 0
  • +
  • -

#14 jon.kiparsky  Icon User is offline

  • Pancakes!
  • member icon


Reputation: 8037
  • View blog
  • Posts: 13,753
  • Joined: 19-March 11

Re: Question about taking a break out of a loop

Posted 23 October 2013 - 06:51 PM

You're starting to define a state machine here... :)

Here's one way to mimic a continue:

while (CONDITION) 
{
  STATMENTS
  if (foo) 
  {
    //noop
  }
  else 
  {
    REST_OF_LOOP
  }
}



Much easier of course to just do

while (CONDITION) 
{
  STATMENTS
  if (foo) 
  {
    continue;
  }
  REST_OF_LOOP
}



Quote

Most of the replies I have read, the main idea I can take with me is the programming style of the coder who uses it. Since no two coders are alike, the way they can express themselves with code will be just as different.


This comes close to suggesting that "it doesn't matter", which would be incorrect. It does matter what style you use. Unfortunately, there isn't any thing like a hard and fast rule, but there are good arguments for using one approach as opposed to some other, and you should think about those arguments and develop a grounded opinion of your own, which you are willing to defend vehemently, and which you're willing to change when presented with a better argument.

What's more important than good style, though, is consistent style. In a given team, all programmers should adopt a set of stylistic conventions, and abide by them. If your team says don't use early exits, then don't use early exits, and write the best code you can under those strictures.
Was This Post Helpful? 0
  • +
  • -

#15 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3667
  • View blog
  • Posts: 11,499
  • Joined: 05-May 12

Re: Question about taking a break out of a loop

Posted 23 October 2013 - 09:58 PM

View PostMomerath, on 21 October 2013 - 01:18 PM, said:

View PostSkydiver, on 21 October 2013 - 05:52 AM, said:

I find it strange that some people will accept break and/or continue within a loop, but crucify you if you have a return

It violates the "single entry, single exit" principle. This, IMHO, is more important in languages with unmanaged memory as it can easily cause memory leaks if you don't take care of things before you return. With the single return at the end, all memory can be cleaned up there.

In managed memory languages it's not as vital, but the choice should be made for each method written. Sometimes it is clearer to exit in the middle of a method (and can save a lot of indenting), other times it makes thing confusing.

YMMV. Void where prohibited. Wear safety goggles while operating.

I worked with a team for a few years where "single entry, single exit" was the rule that never could be broken. The use of goto's was not only highly encouraged, but expected because the second rule was minimize nesting. The third rule was only create functions for code reuse purposes. The net effect of this was that it was quite common to have code that had 300-500 line functions that was structured like:
bool Foo(char bar, int fizz, int *bin)
{
    bool success = false;

    if ( /* do parameter checks failed */ )
    {
        goto Error;
    }

    /* do some 50 lines of work here */
    if ( /* partial results of work leads to error */ )
    {
        goto Error;
    }

    /* do some more 75 lines of work here */
    if ( /* partial results of work leads to error */ )
    {
        goto Error;
    }

    /* lather, rinse, repeat until work is completed */

    success = true;
    goto CleanUp;

Error:
    /* do error reporting and recovery here */
    /* then fall through to the clean up code below */

CleanUp:
    /* do cleaning up used of used resources here */
    return success;
}



Looking back now, I can't believe how ugly that code was, but at the same time it was very predictable when debugging because you could look at the disassembled code and very quickly figure out the addresses of the Error and CleanUp locations and set breakpoints there. Yes, it was the time when SoftICE being the best debugging tool around, and so being able to see the patterns in the disassembled code helped immensely.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1