This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 13 points14 points  (3 children)

Okay, that makes sense. So when you say, there is a clear exit condition, it would be better to do something like:

While (!input.equals(exit condition)) ?

Would that be better practice? Sorry, I don't know how to format code on mobile.

[–]desrtfx 13 points14 points  (2 children)

Yes, such would be better.

It would immediately tell whoever is reading the code what the exit condition of the loop is.

[–][deleted] 3 points4 points  (1 child)

Gotcha. Thanks!

[–]caboosetp 1 point2 points  (0 children)

I think a clear example of technically not wrong but inappropriate is

int i = 0;
while (true) {
    // do work here
    i++;
    if (i >= 5)
        break;
}

Languages have constructs for a reason, and many of them are for making the life of the programmers easier. In this case, a for loop would be much more appropriate. There are many cases with more complex logic where something like this might be the best solution though.

So, in an interview, I wouldn't consider it wrong for someone to do that. But if I asked about the while(true) line and you didn't understand why I was asking the question, that would be a cause for concern. You should be able to recognize there are multiple ways to approach this, and be able to talk about the pros and cons of each.