create a null PrintWriter

Hi, I don't like to write code like this:

if (verbose) out.println();

where, out is a PrintWriter, coz everytime I should write "if (verbose)".

I want to initialize out according to the value of verbose, like:

public void intializeOut() {

if (verbose) {

out = new PrintWriter(System.out, true);

}

else {

// set out to a null PrintWriter (actually it

// should not be null, otherwise there is

// a NullPointerException.

// however you can still call out.println(),

// though nothing will be printed in anywhere

}

My questions are:

1) Is that possible?

2) Is this way efficient compared with always judge the verbose value?

Thanks very much!

JST

[791 byte] By [JSmallTiger] at [2007-9-26 4:13:23]
# 1

You want to implement the "null object" pattern. Simply create a NullPrintWriter class that extends PrintWriter and override the methods with empty method bodies. This approach will be more efficient when the reference points to a real PrintWriter (because you've removed the check), but will be less efficient when it points to the NullPrintWriter (because calling a polymorphic method is more expensive than checking a simple condition).

schapel at 2007-6-29 13:20:04 > top of Java-index,Archived Forums,Java Programming...