Writing code that ends cleanly without breaks


Super detailed diagram!

You'd think transitioning back to university studies after working would mean I'd be learning more about so called "correct" programming techniques, but I've actually found the opposite is true! Apparently I'm also incapable of writing catchy titles for programming posts.

It's hard to describe, but in high school programming classes I learned its important to bring programming logic that may have strayed off in different directions back to a single point so a method can cleanly exit. In this way, each block has a clearly defined beginning and end.

This can be demonstrated using a loop. In this completely pointless Java example we're traversing a linked list of <Strings> looking for an awesome anime character. To preempt any comments, yes I could have used a for each loop, but that's not the point I'm trying to make.

while (linkList.hasNext()) {
  if (linkList.next().equals("Her Senjougharaness")) {

In the above case we have one entry point, but we're breaking out of the loop instead of allowing it to cleanly finish (in fact in this case it never will finish!). This works, but a more elegant solution is to modify the condition of the loop itself:/p>

boolean found = false;
while (!found && linkList.hasNext()) {
  if (linkList.next().equals("Her Senjougharaness")) {
    found = true;

In this case, once we've found what we're looking for the loop isn't merely broken out of with a break statement, but is allowed to cleanly finish and gracefully return control to the parent because the condition of the loop has been changed and it terminates itself.

Funnily enough I've been told by people marking my assignments I've been creating unnecessary extra work for myself demanding my loops and methods be structured like this, and they're probably right. Nevertheless I've been wired to not accept any other way; unclean exits just look ugly as sin from a design standpoint to me, and I know it's not the "correct" thing to do. I think!

Author bio and support


Ruben Schade is a technical writer and infrastructure architect in Sydney, Australia who refers to himself in the third person. Hi!

The site is powered by Hugo, FreeBSD, and OpenZFS on OrionVM, everyone’s favourite bespoke cloud infrastructure provider.

If you found this post helpful or entertaining, you can shout me a coffee or send a comment. Thanks ☺️.