Consider the following snippet:
int max = 10;
int a = 0;
while (true) {
// do a thing that may result in an early return
if (++a >= max) {
break;
}
}
throw new RuntimeException("It ran out of attempts");There are a few WTFs in the above. The loopβs a bit weird, the flow of control seems to be in a few placesβ¦ but at the heart of it is a bit of codey code β ++a >= max
In this case does it definitely do 10 attempts? or is it maybe 9? or 11?
General case:
If you canβt, at a glance, determine what the logical expression is doing, itβs too complex.
As it happens, I think this does 10 attempts:
++ais a prefix increment, which adds 1 toa- The
>=meansacannot be10or more and that is being done after the increment astarts as0- the first attempt happens when itβs
0, the 10th happens when itβs9 - So it does 10 attempts
β¦ probably.
While programming languages allow us shortcuts to do things and several ways to express the same things, clearly a for (i=0; i<10; i++) style expression would be instantly recognisable for what it is. The codey code is almost always better refactored.
It seems like loops are prone to codey code.
Published on Java Code Geeks with permission by Ashley Frieze, partner at our JCG program. See the original article here: Mythematical Codey Code Opinions expressed by Java Code Geeks contributors are their own. |
Thank you!
We will contact you soon.
Ashley FriezeMarch 5th, 2020Last Updated: March 4th, 2020

This site uses Akismet to reduce spam. Learn how your comment data is processed.
Hiβ¦
Iβm Elena gillbert.While programming languages allow us shortcuts to do things and several ways to express the same things, clearly a for (i=0; i<10; i++) style expression would be instantly recognisable for what it is. The codey code is almost always better refactored. It seems like loops are prone to codey code.