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 File
s 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?
Why can't you just control the entry point of the
File
object into your program's logic and perform thenull
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 aNullReader
implementationThe 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 aFile
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.
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:
After
And have that method implemented like:
Obviously coded carefully and not in 3 mins. as I did :) :) :)