ultrabowser ultrabowser - 5 months ago 8
Java Question

Java best practice: filename of File as argument constructor

Should I make a constructor take on a

File
or a
String
with a filename when I want to read the content the new file is supposed to contain from a file?

public GraphModel(File file) throws IOException {
this();
readFromFile(file);
}


versus

public GraphModel(String filename) throws IOException {
this();
readFromFile(new File(filename));
}


Is there a best way that is obvious?

Answer

Imho it's not important. I've often overloaded the constructor and let the constructor with the String parameter call the one with the File parameter to allow for both. Which won't work of course if you want to call the parameterless constructor as well. Otherwise it's like

public final class GraphFile {

    private final File file;

    GraphFile(String fileName) {
        this(new File(fileName));
    }

    GraphFile(File file) {
        this.file=file;
    }

    public GraphModel read() throws IOException {
        return whatEverReadsYourGraphModel(file);
    }
}
Comments