Readonly asserts and more

bearophile bearophileHUGS at lycos.com
Tue Mar 2 04:56:28 PST 2010


In Java there are few uncommon situations where it's useful to put side effects inside asserts.

This Java code manipulates an array, and then wants to assert something about this computation. To perform such tests it needs the old array, that has to be copied. But in release mode the programmer doesn't want to perform such extra array copy, so the array copy too is inside an assert:


void foo(final int[] array) {
    // Inner class that saves state and performs final consistency check
    class DataCopy {
        private int[] arrayCopy;
        DataCopy() { arrayCopy = (int[]) array.clone(); }
        boolean isConsistent() { return Arrays.equals(array, arrayCopy); }
    }

    DataCopy copy = null;

    // Always succeeds; has side effect of saving a copy of array
    assert ((copy = new DataCopy()) != null);

    ... // Manipulate array

    // Ensure array has same ints in same order as before manipulation.
    assert copy.isConsistent();
} 


In D code I prefer to solve this problem with a debug{/*array copy*/}, and keep my asserts side-effects free.

Bye,
bearophile



More information about the Digitalmars-d mailing list