Skip to main content

Dont Be for-blind

·2 mins

Looking through some code the other day got me thinking seriously about how neglected the do-while loop is, most of us never use it, neither do we have a solid understanding of the inner workings of it, or even when to use it. So today I’m going to go through one use case where you can change your while/for-loops for a nicer version using do-while instead.

Correcting a blindness #

As a Java developer, I have gotten used to doing for-loops, I have mostly even stopped using while-loops. With the introduction of lambda-powered loop constructions, I mostly end up with a version of a for-loop. Today however I saw a stupid mistake in my code and I could not fathom that I just wrote code without even thinking.

How many of you have done something like this?

boolean isCondition = false;
for (SomeObject o : someList) {
  if (o.someProperty < someNumber) {
    isCondition = true;
    break;
  }
}

Have you tried something like this lately?

boolean isCondition = false;
int c = 0;
do {
    isCondition = someList.get(c).someProperty < someNumber;
    c++;
} while (!isCondition && c < someList.size());

Of course someone will point out that you can just do:

boolean isCondition = someList
                        .stream
                        .anyMatch(o -> o.someProperty < someNumber);

I’ll be first in line admitting that lambda is great, but methods such as anyMatch can evaluate more objects than required before exiting, which may not be ideal.

Conclusion #

Sometime we get caught up in the way we do things, but it is important to always question our own view on coding, making sure we approach each problem with at least fresh eyes if not new eyes.

So, for problems that require you to loop over collections, stopping when some term becomes true, remember that a do-while is a viable option instead of going for a for-loop with a break.