nullobject for File in Java

2019-08-03 19:46发布

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?

3条回答
够拽才男人
2楼-- · 2019-08-03 20:01

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

查看更多
祖国的老花朵
3楼-- · 2019-08-03 20:09

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.

查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-08-03 20:12

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 :) :) :)

查看更多
登录 后发表回答