I've fiddled with my blog template because I decided I wanted more horizontal viewing space, given that it was using less than a third of my 1920 horizontal pixels. If it feels too spread out for you, I added a drag-and-drop handle over to the left to let you resize the main content column. The javascript is pretty primitive. If it breaks, drop me a comment.
>
>
>
>

Tuesday, December 30, 2008

Implementing Optionally Infinite Iterations

Sometimes you need to write a method that takes an argument indicating how many times a certain thing should be done with the option of doing it an unlimited number of times. A straightforward writing might look like this:
    /** Pass in -1 to work forever. */
    public void doStuff(int iterations) {
        int count = 0;
        while (count < iterations || iterations == -1) {
            foo();
            count++;
        }
    }
If that just bugs you because one of the conditions will always be unnecessary to check--it bugs me--then what about this?
    /** Pass in -1 to work forever. */
    public void doStuff(int iterations) {
        final long maxCount = iterations == -1 ? Long.MAX_VALUE : iterations;
        int count = 0;
        while (count++ < maxCount) {
            foo();
        }
    }
Since an int can never be as much as Long.MAX_VALUE, you've got your infinite iterations, and there's only the one condition to check. All it requires is that you know how big the primitive types are in java and understand how two's complement numbers work.

No comments: