Why is it so far (true) bad practice?

I use while true loop in many projects. It’s good for me, and it’s not too difficult. So, why is it a bad idea to use background processes while the true loop works endlessly. Thank you for your responses.

+6
source share
3 answers

My project manager does not allow such a cycle in my code, he claims that it needs to be replaced with while(!exit_flag)

This is very controversial. while (!exit_flag) assumes that the loop has a natural exit condition, which it will reach at some specific point on its own, for example. something counting from 0 to 100, and then leaving the loop. However, if you write this cycle to create a constant cycle of a daemon or event, then the point of this cycle is the constant operation of the program. Nothing speaks infinitely better than while (true) .

There is no real technical difference between the two; it is simply a matter of readability and expression of intent. Of course, you will have to do this with people who will read this code at the end. If their policy is while (!exit_flag) , so be it.

+4
source

This is not a bad practice, it just means that you have not thought out your code.

The condition should indicate the cycle when the cycle ends. If you have an endpoint, then why not put it as a condition?

 var i = 0; while(true){ i++; if(i == 100) break; } 

This is a great code. But like this:

 var i = 0; while(i != 100){ i++; } 

Both methods are correct, but if someone reads your code, it is much easier to see when the loop stops the iteration, if it is where the condition is.

+4
source

Hmm, ask someone who claimed this was a "bad idea."

I would have thought that any cycle working for an indefinite period should end at some point, unless, of course, you expect your program to work forever.

If no criteria have yet been given for completion, there must be some other mechanism to break the loop hidden somewhere inside the loop, for example return, break or (yuck - Basic - but probably where the origins statement is Goto operator jumping somewhere outside the loop) to end the loop.

Code like this can be difficult to read and debug, and previously it was a sign that it wasn’t very important for the programmer to write clean code. However, currently with event-driven applications and structured error handling (see Try ... catch structure) there are clean and easy to read ways to exit any loop at any time, so although (true) can be used without problems.

Greetz

Alīna

+4
source

Source: https://habr.com/ru/post/985174/


All Articles