Utility method - Pass a File or String?

James P. picture James P. · May 9, 2010 · Viewed 7.7k times · Source

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?

Answer

Stephen C picture Stephen C · May 9, 2010

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,