Cycle terms agreements

I recently discussed using non-meeting conditions in for-loops in Java:

for(int i = 0; o.getC() < 10; i++) o.addC(i); 

Does anyone know if there are any “formal” agreements for such conditions? In my opinion, this is easier to read compared to the equivalent while-loop, because all loop parameters are combined in the first line:

 int i = 0; while(o.getC() < 10) { i++; o.addC(i); } 

Or worse:

 int i = 0; while(o.getC() < 10) o.addC(++i); 
+6
source share
4 answers
Cycles

for are used in almost all situations over an equivalent while solution. Arrays, lists, standard data structures.

On the other hand, while commonly used with threads and infinitely long iterations.

+1
source

Most developers expect the for statement to consist of three things:

  • Variable initialization
  • Variable Based End Condition
  • Variable increment

If you change your code for unexpected things, it will be harder to read and therefore harder to maintain.

Also, I think the while makes your intention clearer: do something and o.getC() will be less than 10. This “something” happens: add an extra number.

In short: use a while for "non-counter conditions".

+1
source

A good thing for loops is a quick access method. Therefore, if you want to do all the elements in an array, you can simply do the following:

(double number: arrayName) where double is the type, number is the name that you give each element (no matter what you call it, in this case you will refer to each value there as a "number"). And arrayName is the name of the array you are accessing.

If you want to reach each element / object, this is the fastest way.

0
source

What about:

 for(int i = 0; i < MAX_ITERATIONS; i++) { o.addC(i); if (o.getC() >= 10) return o; // or break } 

This prevents an infinite loop if addC does not do what you expect.

0
source

All Articles