Best Loop Idiom for special casing the last element

后端 未结 18 974
梦毁少年i
梦毁少年i 2020-12-23 09:25

I run into this case a lot of times when doing simple text processing and print statements where I am looping over a collection and I want to special case the last element (

18条回答
  •  遥遥无期
    2020-12-23 10:03

    Generally, my favourite is the multi-level exit. Change

    for ( s1; exit-condition; s2 ) {
        doForAll();
        if ( !modified-exit-condition ) 
            doForAllButLast();
    }
    

    to

    for ( s1;; s2 ) {
        doForAll();
    if ( modified-exit-condition ) break;
        doForAllButLast();
    }
    

    It eliminates any duplicate code or redundant checks.

    Your example:

    for (int i = 0;; i++) {
        itemOutput.append(items[i]);
    if ( i == items.length - 1) break;
        itemOutput.append(", ");
    }
    

    It works for some things better than others. I'm not a huge fan of this for this specific example.

    Of course, it gets really tricky for scenarios where the exit condition depends on what happens in doForAll() and not just s2. Using an Iterator is such a case.

    Here's a paper from the prof that shamelessly promoted it to his students :-). Read section 5 for exactly what you're talking about.

提交回复
热议问题