I have often heard that using breaks in Java is considered bad practice, but after reading some threads on Stack Overflow, I’ve seen otherwise. Many say that it is acceptable in certain cases.
I’m a little confused as to what is/isn’t bad practice in this case.
For Project Euler: Problem 7, I’ve constructed the code below. The challenge was to find the 10001st prime.
int index = 2, count = 1, numPrime = 1;
while (true) {
index++;
if (isPrime(index)) {
count = index;
numPrime++;
}
if (numPrime >= 10001)
break;
}
System.out.println(count);
This returns the correct answer (in 21ms), but am I overlooking a serious warning? It’s 100% possible to create a while loop without a break, but I find that this is a little easier to follow.
Is the way I use the break; bad practice? I know that there’s always a way around using one, but is it really that terrible here?
Many thanks
Justian
EDIT
Here’s my isPrime() code. I might as well optimize this while I’m at it.
public static boolean isPrime(long num) {
if (num == 2)
return true;
if (num % 2 == 0 || num <= 0)
return false;
for (long i = 3; i * i <= num; i += 2)
if (num % i == 0)
return false;
return true;
}
In this case, it looks to me like it would be easier just to change the
whilecondition:That’s usually the case when a
while(true)loop ends with… although you need to check whether anything else in the body of the loop performs a
continue.Alternatively, you could restructure it slightly:
Then
currentwill be the answer at the end.I generally prefer a
forloop over a while loop, when you’re trying to do something a particular number of times. In this case the “something” is “find the next prime”.There are various bits of dogma in programming that I feel are taken too far – including “one exit point to a method” and “don’t use break.” Write code as readably as you can. If you look at some code and feel it’s not blindingly obvious what’s going on, try to work out other ways of structuring it. Sometimes that’s a case of changing a loop; sometimes it’s extracting a method; sometimes it’s inverting some logic (deal with a negative branch first, possibly exiting early, and then handle the normal case).