Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Utility method - Pass a File or String? [closed]

Here's an example of a utility method:

public static Long getFileSize(String fileString) {

    File file = new File(fileString);

    if (file == null || !file.isFile())
        return null;

    return file.length();
}

Is it a good practise to pass a String rather than a File to a method like this? In general what reasoning should be applied when making utility methods of this style?

like image 708
James P. Avatar asked May 09 '10 00:05

James P.


2 Answers

This is my preferred solution:

public static Long getFileSize(String path) {
    return getFileSize(new File(path));
}

public static Long getFileSize(File file) {
    return (!file.isFile()) ? -1L : file.length();
}

Note that it is returning -1L rather than 0L, to allow the caller to distinguish between an empty file, and a "file" whose length cannot be determined for some reason. The file.length() will return zero in some cases where you don't have a zero length file; e.g.

  • when the file does not exist
  • when the file is a directory
  • when the file is a special file (e.g. device file, pipe, etc) and the OS cannot determine its length.

The file.isFile() call deals with these cases. However, it is debatable whether the method(s) should return -1L or throw an exception. The answer to this debate turns on whether the -1L cases are "normal" or "exceptional", and that can only be determined with reference to the contexts in which the method is designed to be used,

like image 185
Stephen C Avatar answered Sep 21 '22 06:09

Stephen C


I'd go with a File. It feels a little OOP correct to me: more typesafe (Strings are so 'general' in Java...) and semantically expressive: if you are dealing with files, well then pass a File object.

Recall that in Java a File object represents not really a file in itself (its content) but rather its path: "An abstract representation of file and directory pathnames" (it can even be the path of a non-existent file) and that's almost exactly what you need here.

This can only be a limitation in a few cases: if the "file" is actually some kind of pseudo-file or resource, for example inside a jar file. An alternative I have found useful is a URI, which (conceptually) includes a File as a special case, but also other resources.

And if you decide to stick with the two alternatives (String or File), I emphatically don't recommend to name the methods the same. Method overloading can be a pain, use it only when it gives you a tangible benefit.

like image 22
leonbloy Avatar answered Sep 22 '22 06:09

leonbloy