VOOZH about

URL: https://www.javacodegeeks.com/2020/03/mythematical-codey-code.html

⇱ Mythematical Codey Code - Java Code Geeks


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.

Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Thank you!

We will contact you soon.

πŸ‘ Photo of Ashley Frieze
Ashley Frieze
March 5th, 2020Last Updated: March 4th, 2020
1 604 1 minute read

Ashley Frieze

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

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

1 Comment
Oldest
Newest Most Voted
6 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.

-1
Reply
Back to top button
Close
wpDiscuz