Core Java

Mythematical Codey Code

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:

  • ++a is a prefix increment, which adds 1 to a
  • The >= means a cannot be 10 or more and that is being done after the increment
  • a starts as 0
  • the first attempt happens when it’s 0, the 10th happens when it’s 9
  • 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.

Ashley Frieze

Software developer, stand-up comedian, musician, writer, jolly big cheer-monkey, skeptical thinker, Doctor Who fan, lover of fine sounds
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Elena gillbert
4 years ago

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.

Back to top button