Reputation: 744
I know that passing a an Object is not a good practise. But in this case it seems the best solution to me.
public void doSomething(final Object obj) {
// some code
...
if (obj instanceof InputStream) {
document = PDDocument.load((InputStream) obj);
} else if (obj instanceof File) {
document = PDDocument.load((File) obj);
} else {
throw new IllegalArgumentException("Argument must be an instance of " + InputStream.class.getName() + " or " + " " + File.class.getName() + ".");
// more code
...
}
}
An alternative solution would have more duplicated code (all the line before and after PDDocument.load(obj);
)
public void doSomething(final InputStream obj) {
// some code
...
document = PDDocument.load(obj);
// more code
...
}
}
public void doSomething(final File obj) {
// some code
...
document = PDDocument.load(obj);
// more code
...
}
}
Due to the duplicated code I prefer the first solution.
Do you know any better solution to solve this problem?
Upvotes: 1
Views: 759
Reputation: 140544
Pass in the result of
PDDocument.load(specificallyTypedVariable)
as a parameter to the method.
This assumes that // some code
isn't doing some kind of setup for the load
call. If that's the case, you could pass in a Function<? super T, PDDocument>
along with the T
you're going to load it from:
public <T> void doSomething(final T obj, Function<? super T, PDDocument> loader) {
// some code
PDDocument document = loader.apply(obj);
// other code.
}
and invoke like:
doSomething(someFile, PDDocument::load);
doSomething(someInputStream, PDDocument::load);
Upvotes: 6
Reputation: 121840
Since PDDocument
can load from an InputStream
and you can obtain an InputStream
from a File
anyway, I'd suggest:
public void doSomething(final InputStream in)
{
// some code
document = PDDocument.load(in);
// more code
}
public void doSomething(final File file)
{
try (
final InputStream in = new FileInputStream(file);
) {
doSomething(in);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
Of course, handle errors accordingly!
Also, I don't understand why you don't return the document
and put that processing in a method returning void
?
Upvotes: 1
Reputation: 44854
Move
// some code
...
document = PDDocument.load(obj);
// more code
to a separate private
method which can only be called by the two above methods
Upvotes: 0