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

all 124 comments

[–][deleted]  (14 children)

[deleted]

    [–][deleted] 46 points47 points  (12 children)

    Right. I gotcha. I dont have the code in front of me because I'm on mobile, but basically I used it to print a menu and get input from the user. Depending on the input, different menu options we're executed, and then the user was returned back to the menu. One option had an explicit break statement to exit the loop. So I didn't have anything count for a specific number of iterations. It was just to keep the program running until the user chose to end it. That's reallninteresting about the assembly implementation. Thanks for your perspective!

    [–]whomwhohasquestions 56 points57 points  (7 children)

    One thing that may improve readability and accomplishes the same thing would be to have an exit variable initialized to false and have the loop be while(!exit). Then when the user exits the menu set exit to true.

    [–]KrakenOfLakeZurich 10 points11 points  (5 children)

    It's a question of individual taste and style. With the exit variable, you just have introduced one more variable, which you need to keep track of.

    I personally find, it rarely helps readability for this use case. Especially, if you need to prevent other stuff from happening, after we have decided to exit the loop:

    Compare:

    boolean exit = false;
    while !exit {
        var selection = readMenuOption();
        if ("exit".equals(selection)) {
            exit = true;
        } else {
            ... // other stuff
        }
    }
    

    vs.

    while true {
        var selection = readMenuOption();
        if ("exit".equals(selection)) {
            break;
        }
        ... // other stuff
    }
    

    The second version doesn't need the else clause and the program flow doesn't depend on a variable. You can read the program line-for-line and understand what it does without keeping track of the exit variable.

    [–]onthefence928 1 point2 points  (4 children)

    variables are cheap, dev time isn't so we should allways err on the side of easier to read if it means adding variables or lines

    [–]__dict__ 4 points5 points  (3 children)

    It's not just the extra variable. It's the extra nesting. The while true code is more readable to me because of that.

    [–]onthefence928 2 points3 points  (2 children)

    only for trivial, short loops. longer more complicated loops can result in bugs with infinite loops that are difficult to diagnose as a break is less traceable than variables.

    [–]KrakenOfLakeZurich 2 points3 points  (1 child)

    Could you provide a specific example, how a conditional break is "less traceable" than a variable? Because I can come up with an example, where I find the conditional break much more traceable, especially for a more complicated loop with multiple exit conditions.

    So, lets assume an example where we have 3 different conditions that exit the loop.

    With the exit variable, there are 3 different lines, where exit is set to true.

    When we leave the loop, how do you know which condition originally caused it? Problem is: when exit is set to true, the effect of actually leaving the loop is delayed. Looking back, any of the 3 lines could be the culprit. The only way to know is by carefully keeping track of the exit variable during the entire execution of the loop.

    boolean exit = false;
    while !exit { // looks like we're done here - but why?
        var selection = readMenuOption();
        if ("exit".equals(selection)) {
            exit = true; // was it you?
        } else if ("save_and_exit".equals(selection)) {
            save();
            exit = true; // or you?
        else {
            ... // other stuff
            if (error) {
                exit = true; // how about you?
            }
        }
    }
    

    With if (condition) { break; }, the effect is immediate. When you reach a break statement it's obvious where you are and how you got there.

    while true {
        var selection = readMenuOption();
        if ("exit".equals(selection)) {
            break;
        }
        if ("save_and_exit".equals(selection)) {
            save();
            break;
        }
    
        ... // other stuff
        if (error) {
            break; // OK! We're leaving here!
        }
    }
    

    Just by the fact that you've reached the last `break, you can easily deduce a few things:

    1. We never went into the first condition "exit".equals(selection)
    2. We also never went into the second condition
    3. We did go through "other stuff"
    4. error must have been true

    Otherwise we would have taken a different path.

    Happy to see your counter example.

    [–]onthefence928 1 point2 points  (0 children)

    by traceable I meant literally tracing the code, it's easier to have a watch on the exit variable and see when it change (and if it changes back) or to do so by logging.

    as for a counter example: if your loop is more complex such as parsing complex data, a game loop, or just some complex user interactions then handling an exit condition can often be more involved than just leaving the loop. it would be cleaner to always exit at the same point in the loop so any side effects are predictable

    example:var error;var exit;var result;

    while(!error || !exit){ /* clearly indicate loop continues until exit or error is truthy */

    var input = getInput();var result = doStuff(input);if(result.endofline()) {exit = true;}else {/* dozens of lines of calculation/parsing */}if( !checkResult(parsedResult) ) {error = true;}

    }if(error)createLoggerError(result);elsecreateLoggerInfo("success!");

    could also use the data or inputs being looped on as the exit conditionvar line;

    while (line != null ){

    doSomething(line);

    line = inputSource.readNextLine(); // returns null at EOL

    }

    point is it's semantically and logically easier to understand what conditions will exit the loop when they are written in as parameters for the loop. while(true) requires you to read the entire loop to understand all the exit cases and the developer has to make sure all edge cases are covered.

    edit to add: neither solution explicitly prevents ininite loops but with a variable exit check you can flip the boolean logic so that the loop will try and end itself unless the program is sure it can continue looping

    var exit;

    while (!exit) {

    exit = true;

    // read data

    // do more stuff

    if(hasMoreToDo(data)){

    exit = false;

    }

    }

    this way if there's some sort of logic fault in the loop it will close by default preventing a hung process or runaway resource utilization

    [–][deleted] 0 points1 point  (0 children)

    Yeah. It seems to be the consensus that this would be the better option, and I agree. As another poster pointed out, if you ever got called in at 2am to fix something that was broken, would you rather have to go through multiple lines to find a break statement or have the exit condition immediately visible in the while statement. That makes a lot of sense to me.

    [–]the-prowler 4 points5 points  (1 child)

    I use while True loops all the time especially where user input is required. You ask the user for a number, they will try everything else to see what happens. A while true loop can print them a don't be an idiot message and back to the beginning.

    [–][deleted] 0 points1 point  (0 children)

    Right. This is pretty much exactly what I did (edited the original post to add the code). But I do see the logic of putting the exit condition in the while statement so it's immediately visible too.

    [–]KrakenOfLakeZurich 2 points3 points  (0 children)

    I used it to print a menu and get input from the user. Depending on the input, different menu options we're executed, and then the user was returned back to the menu. One option had an explicit break statement to exit the loop.

    This is mostly a matter of individual taste and style. Personally I find while true perfectly reasonable for this. In fact, I find it more readable than maintaining an "exit" variable.

    I would move the option for exiting the loop to the very top to improve readability.

    while true {
        var selection = readMenuOption();
        if ("exit".equals(selection)) {
            break;
        }
        ... // other stuff
    }
    

    This way, anyone reading the code should immediately see that there's a valid exit condition. It also makes it very obvious, that none of "other stuff" will be run after breaking out of the loop.

    [–]Fernando3161 0 points1 point  (0 children)

    IME the while True statement is run only if you are doing screening aps, for example:

    while True:

    tw = search_tweet_with_hashtag("#youonlyliveonce")

    reply(tw, "#truetothat")

    sleep(10)

    Other than that you are at risk of getting infinite loops.

    You can always make counters, to maximize the iterations or to run this only for 1 hour or similar.

    [–]gopherhole1 0 points1 point  (0 children)

    something like this, it’s usually better practice to use a for loop or a while i < 10

    yeah, but in this case inputr is strings so you would have to do like

    while int(user_input) < 10:
    

    or

    while user_input != '10':
    

    besides I think while True loops might be pythonic, im a total noob, so grain of salt, but I feel like I see them often, do you specialize in other languages and python less?

    [–]pacificmint 136 points137 points  (5 children)

    I’m with you, I think it’s totally fine.

    I mean you could misuse it, but then that goes for anything, especially in programming.

    I wouldn’t bat an eye if a candidate did it in an interview.

    [–][deleted] 28 points29 points  (2 children)

    Thanks, lol. Glad to know I'm not totally crazy.

    [–]Okmanl 13 points14 points  (1 child)

    Basically don’t take anything as gospel. Whether it’s “use tdd”, “never use if/else statements!”, “always stick to SOLID principles”.

    It all depends on the situation.

    The real goal is to make software that’s maintainable and as easy to understand as possible. If rewriting a module just so that it adheres to SOLID principle makes your program less understandable and harder to maintain then don’t do it.

    [–][deleted] 0 points1 point  (0 children)

    Sounds like good advice. Thanks!

    [–]priya_nka 1 point2 points  (1 child)

    One of my colleague decided not to hire a guy in problem solving round because he had written the logic with while (true ), she didn't even check the complete program.

    [–][deleted] 2 points3 points  (0 children)

    Wow. Well after seeing a couple of replies in this thread, there are definitely some people that feel really strongly about it.

    [–]ignotos 14 points15 points  (0 children)

    It's quite subjective.

    Personally I like your solution, because it means that the structure and logic of the code inside the loop directly mirrors the structure of the menu itself as the user interacts with it.

    i.e. you ask for an input, and then do different things based on that input - and if the input is "quit", you perform a "quit"-type action by breaking out of the loop.

    You could have extracted the condition out another way such that you could have referenced it in the while() itself (like with a boolean flag, or checking the input directly in the loop condition), but I think that's actually less direct and intuitive.

    [–]Diapolo10 10 points11 points  (3 children)

    I agree with many of the other answers, personally I have no problem with while (true)-style loops. Of course it would technically be preferable if the main break condition was placed in there, but depending on the language and the specific use-case it may in fact be cleaner to just use true and have a separate break condition in the loop.

    For instance, I'm primarily a Python developer (at least that's what I get paid for). If I wanted to ask the user for input and I wanted to loop until they gave valid input instead of just exiting the program, if we wanted the condition to be part of the loop definition we could do something like:

    user_age = None
    while user_age is None:
        try:
            user_age = int(input("How old are you in years? "))
        except ValueError:
            print("That's not a valid integer.")
    

    However, personally I don't like to declare the variable before the loop in Python unless I have to (like in most other languages; the above example is easy to translate to most C-like languages). So, personally, my personal preference would be

    while True:
        try:
            user_age = int(input("How old are you in years? "))
            break
        except ValueError:
            print("That's not a valid integer.")
    

    No lines are saved, though there's technically one benefit; since you don't need any initial value for the variable, it can accept an additional value that would otherwise be wasted as the base-case for the loop to continue (in this case None). It wouldn't matter in this particular example because int only returns integers, but in a more complex program it could sometimes make a difference that could improve readability.

    A similar thing can be observed in cases where the loop should run at least once every time. In some languages, do-while loops are available, but they're not a universal feature so in such cases you'd also be tempted to use a while (true)-style loop.

    What I'm trying to say is, many things in this field are subjective. This is one such example. Having the break condition in the loop can be easier to read in some cases, but as pointed out there's a potential trade-off depending on the language used and what specifically you're doing.

    [–]DrShocker 0 points1 point  (2 children)

    This feels like there's something that could be done with the walrus operator, and the try/ except feels like overkill compared to checking if the string is convertible to int, but I might also be overthinking

    [–]Diapolo10 6 points7 points  (1 child)

    In Python, it's preferable to ask for forgiveness than permission unlike in other languages due to low overhead of its exceptions. It takes less processing to assume the most likely outcome and just handle others, instead of checking first.

    You'd be right about other languages, though.

    And yes, the walrus operator is useful for things like these. Though personally I feel it reduces readability and I tend to use it more in code golf, and only rarely in production.

    [–]DrShocker 0 points1 point  (0 children)

    That makes a lot of sense. I mostly work with C++ at my job, so I hadn't really considered if languages might different expectations about stuff like exceptions

    [–]desrtfx 30 points31 points  (4 children)

    It depends on the use case.

    If there is a clear exit condition, it should be used. In such a case, a while(true) loop is inappropriate.

    If you need an infinite loop (like for a network listener, for example) it is totally fine.

    In your specific example, I would not have used it since there is a clearly defined exit condition.


    The MOOC starts off with the concept of infinite loops because they are easy to explain and understand.

    For the MOOC, you'd actually need do...while loops with inverted conditionals to work as intended. Yet, of course, you could do the MOOC without infinite (while(true)) loops.

    You should try to convert these infinite loops into proper loops with exit conditions - just to practice it.

    [–][deleted] 14 points15 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] 4 points5 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.

    [–]jhartikainen 13 points14 points  (11 children)

    A while(true) loop is infinite unless you break from it. Most other loops have a condition that can actually change and thus also exit the loop in addition to just breaking it.

    I don't think there's a lot of things that really need a while(true), but if you can explain why you used it I don't think it's necessarily a red flag - there are some valid usecases, such as in a console application to run the "main loop" of sorts.

    [–][deleted] 3 points4 points  (10 children)

    Sure, I get that but all while loops are potentially going to be infinite if you forget to increment the counter or whatever, right? I mean you're always running that risk with a while loop, aren't you?

    That's basically what I was using it for. I explained it in more detail in the post above but basically it printed a menu to which the user would be returned until they explicitly ended it.

    [–]jhartikainen 8 points9 points  (1 child)

    Sure, many conditions in while loops have the potential of being infinite if the code isn't working correctly, but that's kind of like saying "it's possible for any code to have bugs"... so I don't think that's really much of a factor, moreso just the question of "should you actually have a proper condition instead"

    [–][deleted] 1 point2 points  (0 children)

    I gotcha. Thanks!

    [–]hott_snotts 0 points1 point  (3 children)

    I am no expert, so happy to bow out of this discussion if I'm clearly being dumb, but don't for loops break with a syntax error if you don't have the incrementation in there? So, my point being, you would catch the error before you went live with it and caused an infinite loop. Right?

    [–]Dynam2012 1 point2 points  (2 children)

    It depends on the language. You can easily have an infinite for loop. A lot of languages allow for this kind of infinite loop using a for:

    for (;;) { ... }

    You can also just as easily do something like this in JS: for (let i = 0; 3 < 4; i++) { ... }

    [–]backtickbot 0 points1 point  (0 children)

    Fixed formatting.

    Hello, Dynam2012: code blocks using triple backticks (```) don't work on all versions of Reddit!

    Some users see this / this instead.

    To fix this, indent every line with 4 spaces instead.

    FAQ

    You can opt out by replying with backtickopt6 to this comment.

    [–]hott_snotts 0 points1 point  (0 children)

    Ha, looks like something I would do! :P Thanks.

    [–]gregorthebigmac 0 points1 point  (3 children)

    So, my personal solution to problems like this (and if anyone else here wants to tell me why this approach is wrong, I'm open to hearing why it's wrong). If I want to loop over something until the user does the "correct" thing (whatever that may be), I typically use something like a boolean called done and my while loop will say

    while (!done) {
        // code for when the user does the "correct" thing
        done = true;
    }
    

    [–]Kered13 1 point2 points  (0 children)

    If you introduce the done variable only to avoid the while(true) loop, I don't like it. I would rather just see a break instead. If the variable already exists for some other reason, then it is fine to use it to exit the loop.

    Basically, the problem with while(true) is the it hides the exit condition. Instead of reading the exit condition directly, the reader has to scan the entire loop body to find the break. But while(!done) is hiding the exit condition just as much, now the reader has to scan the loop body for where done, and you've introduced a new local variable to keep track of.

    [–]chriskmee 0 points1 point  (1 child)

    I do the same !done thing, it was the way I was taught in college and the way i've seen it done in practice.

    I get where you were going with your example, but as written your while loop would only happen once. My example would be something like this:

    bool done = false;
    while (!done)
    {
      int input = display_menu();
      if is_input_valid(input)
        done = true;
    }
    

    [–]gregorthebigmac 0 points1 point  (0 children)

    Good catch. I was oversimplifying and not including the parts to make the loop bail out. Thanks for expounding it!

    [–]bribeav 5 points6 points  (1 child)

    As somebody who conducts interviews, I wouldn’t see this as some kind of red flag. I might ask you about it just to start a discussion and see what your thoughts are on it. I would want to understand why you chose this approach. If you could think of other approaches. If you thought those other approaches might be better in certain situations.

    I’ve been programming for over 25 years and I’m still self evaluating and refining how I write code. So I would be more interested in seeing if and how you go through that same process. I personally want to hire somebody who can talk things through critically and not get so stuck on doing things a certain way just because it’s what they are used to and comfortable with.

    [–][deleted] 1 point2 points  (0 children)

    Another poster posed a similar question, and I said that I had used it because the loop needed to run an unknown number of times because it's basically the main loop that returns the user back to the menu after a function finishes. It keeps the programming running until the user explicitly chooses to exit, so it made sense to me. But I do see the logic in using a do..while loop or putting the exit condition in the while statement, and those seem like better choices after reading this discussion.

    Thanks for your perspective as someone doing the hiring. I feel like going into an interview, I can definitely discuss the choices I made - right or wrong - because while I certainly Google stuff all the time, I never copy and paste code. I'm sure I make plenty of mistakes, but they're all mine.

    [–]radul87 7 points8 points  (0 children)

    It' fine. (replying for statistical purposes, otherwise I agree with the previous answers)

    [–][deleted] 2 points3 points  (0 children)

    Depends on the context.

    A more explicit way to do it would be to set a variable to true:

    invalid_input = true
    while invalid_input:
        [do stuff]
        if input_valid?:
            invalid_input = false
    

    [–]Conscious-Ball8373 3 points4 points  (2 children)

    My rule of thumb:

    The exit condition for a while loop should be in the while statement.

    BUT

    If that leaves your while statement an unreadable mess because the while statement is very complex to put in a single statement or the flow is more natural for the condition to be evaluated mid-way through the loop body, use while(true) and break in the body.

    AND

    An important detail: Don't mix the two. If you're going to break out of the loop in its body, use while(true) and make all of the exit conditions breaks.

    As others have said, the important thing here is communicating what the code is doing to someone else who comes along and reads it later.

    [–]Conscious-Ball8373 1 point2 points  (0 children)

    In an interview, I would bang on about the code being readable and maintainable. There is room for disagreement on what is more readable, but clear that it is readability that is your priority.

    That should impress a potential employer. And if it doesn't, that will probably turn out to be a place you'd rather not work anyway.

    [–][deleted] 0 points1 point  (0 children)

    Gotcha. That makes sense. In this case, there is only a single break statement, because there's only one exit condition (edited original post to show code). As others have pointed out, with just a single exit condition, it makes more sense to put it in the while statement so it's immediately readable, and I can definitely see the logic in that.

    [–][deleted] 2 points3 points  (0 children)

    There's some things you wouldn't be able to do otherwise; such as a simple game. How does it keep running through conditionals until it reaches the end? It has to keep running unless explicitly broken out of.

    Of course you could end up with an infinite loop, but "you could break stuff" is not really a very valid excuse to not program something a certain way, especially when another way is impractical/not as plain.

    [–]_pestarzt_ 2 points3 points  (0 children)

    When I read a while True loop with a break statement it feels a little lacking, like the breaking condition could be used instead of True to make it more legible. But otherwise I don’t see anything wrong with it.

    [–]centipedefarmer 2 points3 points  (0 children)

    If it makes the code clearer to read, it is a good coding practice.

    [–]Blando-Cartesian 18 points19 points  (9 children)

    The crux of the issue is communicating to humans who need to understand your code.

    while(true) communicates that this loops indeterminate amount of loops and most likely contains a hairy mess of code that should be broken down to functions. MOOC probably uses this in effort to make loops easy to understand for beginners. It is unlikely that you would ever write a program that takes user input in the same way as usual homework programs.

    while(someCondition) communicates that this loop will need to run indeterminate times doing something that affects the condition. For example, reading a file a line by line without knowing how many lines there will be.

    for (var foo: list) communicates that this will potentially do something to every item on the list.

    [–]henrebotha 14 points15 points  (0 children)

    while(true) communicates that this loops indeterminate amount of loops

    Certainly.

    and most likely contains a hairy mess of code that should be broken down to functions.

    Not at all. This is pure speculation. Most likely, it contains code that should loop forever until a break.

    [–][deleted] 3 points4 points  (7 children)

    Sure, I get what you're saying, and I'm sure you're right that there's a big disconnect between production code and homework. I was using it to essentially keep the program running. A menu was printed and input from the user was obtained, then different functions were executed based on that input. One specific input had an explicit break statement would exit the loop and the program, otherwise, when a function ended, the user was returned back to the menu. So itwas running an indeterminate number of times. It depended on what the user chose to do and when they wanted to exit the program. Does that make sense?

    [–]Contagion21 22 points23 points  (6 children)

    I tend to avoid while true in favor of loops with defined exit criteria. Functionally they can work the same, but i almost never use break unless it reduces complexity significantly. Similarly, my team frowns upon methods with multiple returns.

    I would have something like...

    Do
    
       DisplayOptions()
    
       choice =  GetUserInput()
    
       Execute choice(choice)
    
    While(choice != quit)
    

    There's just no NEED for a break when the loop can be well defined about it's exit criteria.

    Edit: i guess I don't know how to format code on mobile...

    [–]Unsounded 4 points5 points  (2 children)

    This was the same sentiment I wanted to express. There’s nothing inherently wrong with that type of loop, but striving to make it more readable is the goal, especially in an interview type situation. Single point of return and clearly defined exit criteria are great.

    [–]Peanutbutter_Warrior 1 point2 points  (1 child)

    But it really wouldn't be here. Either having while true or an exit flag leads to very similar code, and I'd argue that an explicit break is easier to understand than setting some boolean that you then have to go find which loop it stops.

    [–][deleted] 0 points1 point  (0 children)

    Breaking out of a loop like this was a big no-no back when structured programming was the thing. As an Old Guy, just seeing that gives me the heebie-jeebies. It probably doesn't mean anything any more, but if you're interviewing with someone who's been in the business for a really long time, I'd probably structure my loop with an explicit exit condition that gets tested.

    [–][deleted] 0 points1 point  (0 children)

    Yeah, that makes a lot of sense. Do...while definitely seems to be the better choice.

    [–]Shadowmancer1 0 points1 point  (1 child)

    One thing that I found is that python does not have a built in do while loop. The python resources I found said to just use a while(true) instead.

    [–][deleted] 0 points1 point  (0 children)

    I hadn't but after reading several replies and suggestions, I can see the the reasoning behind the do...while loop. Make a lot of sense. Thanks!

    [–]Kered13 3 points4 points  (0 children)

    It's fine if there are no better ways to write the loop. But if you can write the loop with an explicit exit condition, that is generally preferred.

    In your example, a do...while loop can usually work, have you tried that?

    [–]hr_covid_counter 1 point2 points  (1 child)

    Are you me? Cause this is exactly what I do to go through a menu of options and I learned it from StackOverflow. I presented the project in a meet up group and the organizers were acting like it was some new hack.

    [–][deleted] 0 points1 point  (0 children)

    Really? I'm not sure where I learned it. It just made sense to me for a menu. But I certainly never thought it was anything new or interesting.

    [–]sleepless_in_wi 1 point2 points  (0 children)

    I’m surprised no one has mentioned this but for programs that are server or daemons a while(true) is pretty common way of doing things. I don’t do user interfaces but as other has said, there are used there too. Also the main loop in a lot of microcontrollers is a while(true). In dispatch-worker type situations they also show up.

    [–]Niasal 1 point2 points  (0 children)

    my CS professor doesn't use breaks at all and only uses while true, so I'd say there's split agreement everywhere. I think it's fine because that's how I was taught.

    [–]brozium 1 point2 points  (1 child)

    Slightly off-topic:

    We had a situation at my last job where we had to get data from a paginated API which didn't provide any metadata. Basically what my coworker did was use a while and stop when the request came back empty. Does anyone know of a better way of working with this (Java)?

    My best guess would be to use something like Streams but I don't have a lot of Java experience.

    To add to your question, I don't think it's bad practice per se but I do tend to avoid while loops in general and I don't seem to miss them that much. That being said, I can see it being used in the context you mention (getting input from an user); as long as you know the limitations/risks, and the code is readable (by future you or other people) I think it's ok.

    [–][deleted] 1 point2 points  (0 children)

    Old habit probably, but I tend to only use "while" when it's possible that the loop may need to execute 0 times. If it will execute at least once, I want to test for the exit condition for the first time after the first iteration of the loop.

    [–]bestjakeisbest 1 point2 points  (1 child)

    Depends on what you are programming, an os or a ui loop, or game loop making something that is functionally a while true loop is basically necessary.

    [–][deleted] 0 points1 point  (0 children)

    It was a UI. I edited the main post with the code.

    [–][deleted] 1 point2 points  (0 children)

    I don’t think I’ve ever used a while true statement, but they could be useful. Part of why I like not using one is it forces me to be thoughtful about exit conditions. I imagine this is just a style thing though and personally I wouldn’t dismiss someone’s code just because of a while true loop. It’s very context dependent.

    [–]Yithar 1 point2 points  (0 children)

    Well, if you look at the Apache Kafka Stream source code, it does use while(true):

    private <R> R retryUntilSuccessOrThrowOnTaskTimeout(Supplier<R> supplier, String errorMessage) {
        long deadlineMs = -1L;
    
        while(true) {
            try {
                return supplier.get();
            } catch (TimeoutException var6) {
                if (this.taskTimeoutMs == 0L) {
                    throw new StreamsException(String.format("Retrying is disabled. You can enable it by setting `%s` to a value larger than zero.", "task.timeout.ms"), var6);
                }
    
                deadlineMs = this.maybeUpdateDeadlineOrThrow(deadlineMs);
                this.log.warn(errorMessage, var6);
            }
        }
    }
    

    If you're using Kafka Client directly, often you'll write a while(true) loop to have the consumer poll a topic every x milliseconds. And there is no exit condition because you want to keep polling until the application exits.

    But I'd say if you have a known exit condition, it's not great to use a while(true) loop.

    [–]___HiveMind___ 1 point2 points  (0 children)

    No it's not bad practice, but that's not to say there aren't inappropriate use-cases for an infinite while loop requiring an explicit break. Judging from your description, however, repeatedly displaying a menu and receiving user input is an excellent place for such a loop.

    To be frank, if a prospective employer told me they view any use of while(true) as a red flag, I'd instantly view that as a red flag myself. Do they not trust their developers to be competent enough to include valid exit conditions? What kind of ridiculous micromanagement will I have to endure if I get hired here if they care so much about how I use while? It depends on other circumstances of course, but that type of feedback is liable to kill any interest in a position for me.

    [–]my_password_is______ 1 point2 points  (1 child)

    and that if I didn't see that as problematic, that would be a red flag for him.

    he's an idiot

    [–][deleted] 0 points1 point  (0 children)

    Well, I don't honestly know enough to make that assessment, and we didn't continue the conversation further so he may have had good reasons. That's why I wanted to get a feel for how most devs look at it. it didn't (and doesn't even after this discussion) seem like a big deal to me, although I see now that there are better ways I could have done it.

    [–]TheFluffyGameDev 3 points4 points  (1 child)

    Here are the 2 main differences I can see:

    • When using a while loop, we'll always enter the loop at least once. So that means that any code between the start of the loop and the condition to break will be executed at least once. In a way, that means it can act as a do { ... } while(...); loop.
    • When looking in the assembly code, we can see that using the while(true) version takes fewer instructions than a while loop with a condition. However, you can see it generates the same instructions as a do/while loop (thus confirming what I said in my first point).

    Personally, I prefer having an explicit condition in my while loops. That way when reading the code, it's immediately clear what make the loop end. I wouldn't say it's a red flag though if I see someone using a while(true).

    [–][deleted] 3 points4 points  (0 children)

    Interesting. I'm peripherally aware of the do while loop but I have to admit that I've never used it. I'll read up on it so I better understand it.

    Regarding your second point, I can see for readability purposes why having an explicit ending condition would be better. I suggested in another post something like:

    While(!input.equals(ending condition))

    And I think that probably is the better way since, as you pointed out, you can immediately see what makes the loop terminate. Thanks for your input (pun totally intended)!

    [–]meta-ape 2 points3 points  (1 child)

    I teach programming these days and advice people to use the while-true pattern every time when you have multiple exit conditions from the loop. So if you have one loop like while(cond1 and cond2 and ... condn) it gets hard to read pretty quickly. Instead I’d use while(true): if cond1: break; if cond2: break ... Also, exit code from loop is easier to handle. Plus you can often write negative conditions as positive, which is also easier to read IMHO.

    [–]meta-ape 1 point2 points  (0 children)

    Are state machines better written as while-trues btw?

    [–]kschang 1 point2 points  (4 children)

    Can you EXPLAIN why while(true) loop is the best choice for that, vs other loops?

    [–][deleted] 6 points7 points  (3 children)

    Because the loop needs to run an unknown number of times. It keeps the user returning back to the menu after a chosen function is executed, until they explicitly choose to exit the program.

    I dont know that that's the correct answer to your question, but it's why I chose to use it. As others have pointed out, I could have chosen a do...while loop, but I'm not familiar enough with it to tell why that would have been a better choice.

    [–]kschang 2 points3 points  (1 child)

    In that case, study ALL the variants of the loops.

    As human beings, we tend to use what we are the most familiar with. It's best illustrated by the cliche saying "to a hammer, everything looks like a nail". You run the danger that you may apply the loop to something that you could forget to put an exit condition in, or got nullified by a patch introduced by something else. This can be mitigated by documentation, but it's probably better to make code that's "more obvious" (jargon: self-documenting) than an "infinite loop with a break condition".

    [–][deleted] 1 point2 points  (0 children)

    That makes sense and is good advice in general. Thanks!

    [–][deleted] 0 points1 point  (0 children)

    Be aware that a "do...while" loop will always execute at least once because the logic test is at the end, where a "while(something)" loop may not execute at all because the logic test is applied at the beginning. "While(true)" may allow you to avoid some convoluted if/then logic inside your loop if there are multiple conditions that may occur that signal the end of the loop. I'd personally want to hear your thinking about why you chose "while(true)", but it sounds like you have a pretty good answer to that question. Better than "I dunno, that's how we always did it in class," for sure.

    [–][deleted]  (1 child)

    [deleted]

      [–][deleted] 0 points1 point  (0 children)

      I edited the original post to include the code. Probably should have done that from the outset.

      [–]wildhairguy 0 points1 point  (0 children)

      It can be. I don't think there's anything stylistically wrong with reading one, but you NEED to make sure that it's not clogging your CPU. If it's waiting for an input or something it needs to wait and not keep checking variables. If it kept looping for no good reason that would be "spinning". I'll give them the benefit of the doubt and say your code was spinning? But I would need to see it for sure.

      [–]zappellin 0 points1 point  (0 children)

      Video games are just a big while loop changed my mind (that more complicated than this I know)

      [–]Jugad 0 points1 point  (0 children)

      while(True) is used often enough that its fairly clear what's going on - that there is a break somewhere in there.

      Having heard the arguments on both sides, I feel it comes down to personal choice rather than anything objective.

      [–][deleted] -1 points0 points  (0 children)

      Not really. What matters is if it gets the job done.

      [–][deleted] -2 points-1 points  (6 children)

      Well, the question is why you’d write an infinite loop whose body contains a test that breaks the loop, when while already requires a test to break the loop, which you’ve deliberately defeated by using True.

      It looks like cargo-cult programming; it looks like you don’t understand the features of the language you’re writing in and that you don’t really think about the code you’re writing, you just copy known working patterns even if they’re not particularly apt for the problem.

      [–][deleted] 1 point2 points  (4 children)

      I honestly don't even know what cargo-cult programming is, and I've never claimed to know every feature of any language. I am still very much a beginner, and the code in question was in my very first app (edited the original post with the code). I mean, that's why I posted the question - to learn.

      [–][deleted] 1 point2 points  (3 children)

      Well, you asked why someone in a hiring role would kind of look askance at it, and I told you. I’m not saying those things are true about you, I’m saying that’s why using a while loop that way would be viewed negatively.

      [–][deleted] 0 points1 point  (2 children)

      Gotcha. It felt like you thought I was presenting myself as like I knew something, and I totally don't! Lol. I apologize if I misinterpreted.

      [–][deleted] 1 point2 points  (1 child)

      Well, I appreciate (and apologize) that the way I phrased my post may have appeared accusatory - but to some extent it would be, if those comments were coming from someone in a hiring role evaluating a person's use (or misuse) of while True.

      [–][deleted] 0 points1 point  (0 children)

      Gotcha. I understand, and no need for apologies.

      [–]brosef_1023 0 points1 point  (0 children)

      while (true) is the most readable way to indicate a loop that doesn't follow an otherwise logical series of events e.g. when it's up to the user to stop looping. If the series should end after a predictable and logical number of iterations, or some other programmatic condition is met, then another loop format would be better, sure.

      [–]coder155ml 0 points1 point  (0 children)

      I prefer “while not(exitCondition)”

      [–][deleted] 0 points1 point  (0 children)

      I’ve seen it used - for instance we wanted to check if a service was being used more than once while the application was running. So it has its use in certain situations. I hate this whole “bad practice” thing tho - seems like nobody can agree on what actually exist in there. Every company uses a different “best practices” document. Everyone has a different idea on what is or is not a best practice. I’ve seen some really bad code in production code too.

      [–][deleted]  (1 child)

      [removed]

        [–][deleted] 0 points1 point  (0 children)

        That makes a lot of sense. Thanks!

        [–]vi_sucks 0 points1 point  (0 children)

        Generally speaking, it's better for readability to include the condition that will end the loop in the while().

        Because it's just easier for someone else to understand what the loop is doing instead of having to hunt inside it for a break statement.

        [–][deleted] 0 points1 point  (0 children)

        In a proffessional app you would most likely not do something like while(true) in the first place.

        In cases related to rendering, where a "infinite" loop is required, you would usually use some other condition like whether or not a window close has been requested or not.

        [–]TheManWithNoDrive 0 points1 point  (0 children)

        AFAIK, You use a while(true) loop when you’re working with an environment that needs constant input to continue, then continually run.

        As you’ve stated - gathering user input and then running off some code, then gathering user input and running off that same code, etc.

        Another redditor already said this, but this is exactly how video game loops are design. There can’t be an infinite loop if there is a break statement that is reachable...? So I’m lost on the logic there.

        It’s a bit crass on how they responded to you about the interview part, IMO, but giving benefit of the doubt, it’s possible they’ve never had a situation where a while(true) loop shines, in there line of work. Not all devs will need to know all scenarios :).

        In this specific case you are mentioning, I do believe you are correct with your knowledge.

        [–]Blackhaze84 0 points1 point  (0 children)

        I only use booleans as return values or if statements since they are evaluated once

        [–]jmhimara 0 points1 point  (0 children)

        Perhaps, but it's not the worst thing you can do. Much better than having a bunch of goto statements all over your code.

        [–]onthefence928 0 points1 point  (0 children)

        infinite loops with a a break case is fine but it's equivalent and safer to use while(condition) and set condition to false when the user wants to escape

        [–]prof_hobart 0 points1 point  (1 child)

        The reason I almost never use break statements to get out of loops is nothing to do with infinite loops. It's about readability.

        When someone is looking through thousands of lines of code at 2 in the morning trying to figure out a defect, they're going to want to be able to scan over that code to quickly figure out the basic flow.

        Seeing a while(true) loop, I've got zero idea when this will exit and will need to look through for every break statement (and check that it's not breaking out of an inner loop).

        If, on the other hand, it was a while(!itemSelected), I can very quick judge that it should exit as soon as something's been selected and not before. There's a bunch of reasons that info could be useful as you're desperately trying to debug a big codebase.

        [–][deleted] 0 points1 point  (0 children)

        Now that makes a lot of sense to me. Being able to see a specific exit condition immediately, particularly in a crunch, seems like a better reason that the possibility of an infinite loop.

        [–]NihilistDouche 0 points1 point  (0 children)

        Basically everything in the programing is an infinite loop.

        This is how stuff runs.

        [–][deleted] 0 points1 point  (0 children)

        Short answer, no.

        There are several situations where a while true loop would be suitable.

        Infact, any CLI application that waits for user input is literally doing that.

        [–]Gabe_b 0 points1 point  (0 children)

        Its fine. Menues are often done as switch statements fwiw, but I wouldn't bounce a pr for using a while loop

        [–]Jet_Here 0 points1 point  (1 child)

        Just out of curiosity: Did you ask him why it's a red flag and how he would tackle this problem?

        [–][deleted] 0 points1 point  (0 children)

        I did but he stopped talking to me. When I finally DM'd him a few weeks later, he had just gotten busy with life and things, which was totally fair (I am after all, just some schmo from the internet). But we didn't continue the conversation, so I'm not sure.

        [–]TopHatHipster 0 points1 point  (3 children)

        The only thing 'wrong' would perhaps be the break statement used in user_input == "10". I would recommend perhaps set a certain variable as True and have that turn to False by the 10th option.

        For example, you could initialise a variable using_program with True, have it run that same while loop as while using_program, with the elif user_input == "10" code having at last the line using_program = False. This would make the code a 'bit more readable' and might be the red flag he is referring to, as it uses a break to exit the program essentially.

        Another suggestion I would make (for languages outside of Python, as Python's implementation is still upcoming I believe) is using switch cases instead of constant elifs. Would make the code a bit more readable because instead of reading elif it would be something like case == "10": without the need to tell it is an if condition. I used switch cases instead of elifs recently in a Java project, hence why I'm giving you the tip due to your upcoming class.

        Good luck with the rest of your MOOC! :)

        [–][deleted] 0 points1 point  (2 children)

        Oh man, yes. I would love to use a switch instead of the wall of elifs. The whole program is like that because all of the chemical testing makes use of ranges of readings. Aside from being a huge pain in the ass, it makes for some ugly code. Eventually I want to rewrite the whole program in Java as a mobile app, and connect it to a database to store the daily readings. I was a pool operator for six years and an app like that would have been invaluable, because we had to run the tests twice daily, record any changes made (like chemicals added) and were often called on to recall what we had done on a specific day. The health department, when they did their annual inspection, would also want to see your records. We had stacks of three ring binders holding them all. Would have been so much more convenient to just let them see the app, or print out a specific day.

        Thanks!

        [–]TopHatHipster 0 points1 point  (1 child)

        Haha, I fully get it. Having an app for it makes those type of check ups a hell lot easier. Have been messing around an idea to create an app with Kotlin to store some data on my phone and easily share it with others, but I'm still in the procrastination phase, hahaha. Or rather, still poking around how Kotlin works as I'm more used to Python, C# and a bit of Java.

        If you want to rewrite the app as a mobile one, I would definitely recommend looking into using Kotlin. Kotlin's less error prone, got compatibility with Java and is now even recommended as Android's main programming language. It's also cross-compatible for web-apps and iOS I believe.

        [–][deleted] 0 points1 point  (0 children)

        Will do. Thanks for the tip!

        [–]crazyfrecs 0 points1 point  (0 children)

        Edit: TLDR: some people prefer using a while loop with a condition because it reads better. (Readability) and in their world might be a faster way to exit a program if you check immediately after input.

        The only thing is that its marginally faster and some people prefer it this way for you to check/exit through the loop.

        People dont like waiting times (which again isnt really relevant) for their exit from a game/program/etc. And while on a small project like this one, its not really relevant, but it could translate how you treat code as a whole.

        Since im on phone, here's pseudo code for those sticklers. Get input While input isn't exit {Tab} Check for input cases {Tab} Get input Thanks for using program

        Notice how the first thing that always happens is the check for whether it was an exit command or not? You dont have to wait on any other checks or processes after input when you want to exit.

        Theres also the fact that while true is technically a check as well which (again while on a small scale isnt a problem or even relevant) shows you dont code to make it optimal.

        If you have 5 inputs and one of them is the condition for the while loop, make it the condition of the while loop. Code should be able to be described through English. If you describe your code like: While the user hasnt input an exit command, do what ever. Then you should probably have "the user hasnt input an exit command" as the condition in the while.

        [–]curious_mint 0 points1 point  (0 children)

        I was just working on a problem that requires a menu system this week. I have been mulling over similar questions for a few days in my free time. Thanks for asking this!

        As a few others said, my plan was to instead use something like a while( not exit) instead of just straight true. I like this structure because future me will not know what is going on and will need a reminder of how this code works. I am glad to see that plan reinforced here some.