java - When to use a String with filename or File as argument to constructor? -
when should use file
, when should use string
filename constructor? constructed method should contain contents of file. can choose:
public graphmodel(file file) throws ioexception { this(); readfromfile(file); }
versus
public graphmodel(string filename) throws ioexception { this(); readfromfile(new file(filename)); }
is 1 preferred on other?
some people think matter of taste / personal preference ... or doesn't matter. argue matter.
lets assume api's implementation require file
internally. then, there 3 alternative approaches:
// #1 public graphmodel(file file) throws ioexception {...} // #2 public graphmodel(string file) throws ioexception {...} // #3 public graphmodel(file file) throws ioexception {...} public graphmodel(string file) throws ioexception { this(new file(file)); }
now compare these apis in various contexts:
if adopt approach #1, , caller has filename
string
must constructfile
. potentially results in duplicative code1.if adopt approach #2, , caller has filename
file
must usefile.tostring()
argument constructor. potentially duplicative , inefficient2.if adopt approach #3, api works in either case.
so conclusion is:
if trying provide general api use in contexts you don't know form caller have filename, approach #3 best, , approach #2 better approach #1.
if api not general; i.e. designing specific context, either approach #1 or #2 ok ... if fit intended usage patterns. however, might3 want design application don't keep on creating
file
objects same filenames.
1 - if constructor called in lots of places, mean new file(...)
call @ each place.
2 - caller must convert file
string
, have constructor create new file
string
.
3 - if aspect of application demonstrably performance critical.
Comments
Post a Comment