java boilerplate

Thursday, December 01, 2005

Quicker way of handling empty for loops.

Oftentimes you need to do something special if a for loop will not ever run; that is, the loop condition is false even before we ever iterate into the for loop. We propose a new keyword, 'empty', which can be added onto a for loop. This code will be called if the for loop's loop condition is false right away.

old code:
     int length = someObject.size();
if ( length == 0 ) {
throw new EmptyCollectionException();
for ( int i = 0 ; i < length ; i++ ) {
// ... whatever

new code:
     for ( int i = 0 ; i < someObject.size() ; i++ ) {
// ... whatever
} empty {
throw new EmptyCollectionException();

BONUS: Add a pythonesque 'else' statement as well, which is called when the for loop exits normally (but not if the for loop ends abruptly, by an in-for return or throws statement, a break statement, or a continue jumping to an outer label. I don't think 'else' is the proper term for it, though.

BACKWARD COMPATIBILITY PROBLEMS: 'empty' is not currently a reserved keyword. An existing reserved keyword, such as 'else' can be used for this, but 'else' is a really bad idea. Python supports 'else' on a for loop but its meaning is completely different.


  • Why not use an Iterator?

    By Blogger Sanj, at 3:08 PM  

  • Same issue. It's no problem when you have an actual Iterator object, but when using java 1.5's foreach operator, you don't have one either. I intend the empty operator to also work on a foreach type for ie:

    for ( String item : someMap.keySet() ) {
    } empty {
    //something else

    By Blogger Reinier Zwitserloot, at 4:46 PM  

  • A better idea from a backwards compatibility perspective is to use the 'case' reserved keyword for this:

    for ( something ) {
    } case empty {
    //something when the for loop ran 0 times
    } case normal {
    //for when the for loop ends normally
    } //etc

    Probably still hard to do right given normal compiler design, but gives a way out to let 'empty' NOT be reserved keyword.

    By Blogger Reinier Zwitserloot, at 12:11 AM  

Post a Comment

<< Home