What is the use case for null(Input/Output)Stream API in Java?

Sometimes you want to have a parameter of InputStream type, but also to be able to choose not to feed your code with any data. In tests it’s probably easier to mock it but in production you may choose to bind null input instead of scattering your code with ifs and flags.

compare:

class ComposableReprinter {
    void reprint(InputStream is) throws IOException {
        System.out.println(is.read());
    }

    void bla() {
        reprint(InputStream.nullInputStream());
    }
}

with this:

class ControllableReprinter {
    void reprint(InputStream is, boolean for_real) throws IOException {
        if (for_real) {
            System.out.println(is.read());
        }
    }
    void bla() {
        reprint(new BufferedInputStream(), false);
    }
}

or this:

class NullableReprinter {
    void reprint(InputStream is) throws IOException {
        if (is != null) {
            System.out.println(is.read());
        }
    }
    void bla() {
        reprint(null);
    }
}

It makes more sense with output IMHO. Input is probably more for consistency.

This approach is called Null Object: https://en.wikipedia.org/wiki/Null_object_pattern

Leave a Comment