ultrabowser ultrabowser - 1 year ago 48
Java Question

Java best practice: filename of File as argument constructor

Should I make a constructor take on a

or a
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 {


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

Is there a best way that is obvious?

Answer Source

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

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