gauntlet : Java Glossary


A gauntlet is a series of conditions guarding an action. There is usually only one fail action (possibly empty) and one success action (possibly empty) for the series of tests as a whole.

Early Return Style Gauntlet

Writing gauntlets the obvious way in Java soon wraps you N layers deep in nested ifs. One of the easiet ways to write gauntlets is to make them a separate procedure that returns either success or fail. You use the early return feature to avoid the deep nesting. The above code is an artificial example since File.delete is defined to return true if and only if the file denoted by this abstract pathname exists and is a directory; false otherwise. In other words, it does most of the checks itself and so they are not necessary.

Java purists dislike using the early return, even in a small method like the one above. I like this style because the conditions are independent and uniform. You can shuffle the order easily and add new conditions without having the adjust the existing code.

Another common type of early return gauntlet has a void return. If any test fails it quietly returns without doing anything. Another type just returns a boolean without executing the goal action, leaving that up to caller.

McCarthy Style Gauntlet

If your gauntlet is composed purely of conditions, you can use && or || to join them in a single if.

One problem with the technique above is things can get a little complicated with precedence and all the possible combinations of !, || and &&. The other problem is you have to break the pattern any time a condition needs a little precalculation.

Nested If Inline Style Gauntlet

Java has no nested methods. Therefore all the information your gauntlet method needs must either be passed as parameters or available via instance and static variables and methods. Sometimes the volume of information you need to pass via parameters is so high, it makes writing a separate gauntlet method not worth the effort and it is cleaner to make do with an inline gauntlet implemented as a deeply nested if like this:

If find the nested if style above the hardest to maintain. When it comes time to add another condition or reorder the conditions it turns into a confusing sea of { and }. The other problem is the gauntlet in not clearly delimited as a logical unit. It flows seamlessly into the logic before and after.

This page is posted
on the web at:

Optional Replicator mirror
on local hard disk J:

Canadian Mind Products
Please the feedback from other visitors, or your own feedback about the site.
Contact Roedy. Please feel free to link to this page without explicit permission.

Your face IP:[]
You are visitor number