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?
This is my preferred solution:
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.filedoes not existfileis a directoryfileis 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-1Lor throw an exception. The answer to this debate turns on whether the-1Lcases are “normal” or “exceptional”, and that can only be determined with reference to the contexts in which the method is designed to be used,