views:

89

answers:

3

I have a class that occasionally gets passed null for File objects. During normal operation it uses a Scanner class to parse through the file.

Instead of littering my code with null checks against the File objects, I thought I could replace the Files with nullobjects (Gang of Four style).

However, it looks like File isn't really designed to be extended. Does any one have any pointers on how to do this?

A: 

Why can't you just control the entry point of the File object into your program's logic and perform the null check there?

Another option would be to use something like a separate interface which encapsulates the data: a Reader for example. You could certainly provide a NullReader implementation

oxbow_lakes
A: 

The null object pattern was designed around interfaces, not concrete objects.

To get around this, you can create a new interface which contains the methods you are using from File, and then create a concrete implementation which just delegates to a File held inside. Then, you can create your null implementation, which will stub out the calls.

Of course, this seems like a bit of overkill for removing one null check.

James Van Huis
+2  A: 

You can replace the object that uses the file with a NullObject

For instance, you can use a NullInputStream and pass it to the scanner.

Before:

 public void whatever( File f ) { 

     Scanner scanner = new Scanner( f );

     ...
 }

After

 public void whatever( File f ) { 

      Scanner scanner = new Scanner( getInputStreamFrom( f ) );

      ...
 }

And have that method implemented like:

 private final InputStream getInputStreamFrom( File f ) {

      if( f == null && !f.exists() ) { 
          return NullInputStream.instance;
      }

      return new InputStream( new FileInputStream( f ) );

 }


 class NulllInputStream extends InputStream {

      private final static NullInputStream instance = new NullInputStream();

      private NullInputStream() {
      }

      public int read() { 
          return -1; 
      }
      .... other relevant methods here... 
 }

Obviously coded carefully and not in 3 mins. as I did :) :) :)

OscarRyz
There's even an implementation of this in Apache Commons: http://commons.apache.org/io/apidocs/org/apache/commons/io/input/NullInputStream.html
Ryan
File.exists is most useless.
Tom Hawtin - tackline