I have this code to validate a java.io.Fileparameter which should not be null, should be accessible, should be a file and not a directory, etc.:
private static final String EXCEPTION_FILE_CAN_NOT_BE_READ =
"The file %s does not seem to readable.";
private static final String EXCEPTION_PATH_DOES_NOT_EXIST =
"The path %s does not seem to exist.";
private static final String EXCEPTION_PATH_IS_NOT_A_FILE =
"The path %s does not seem to correspond to a file.";
private static final String EXCEPTION_PATH_REFERENCE_IS_NULL =
"The supplied java.io.File path reference can not be null.";
public static Banana fromConfigurationFile(
File configurationFile) {
if (configurationFile == null) {
String nullPointerExceptionMessage =
String.format(EXCEPTION_PATH_REFERENCE_IS_NULL, configurationFile);
throw new NullPointerException();
}
if (!configurationFile.exists()) {
String illegalArgumentExceptionMessage =
String.format(EXCEPTION_PATH_DOES_NOT_EXIST,
configurationFile.getAbsolutePath());
throw new IllegalArgumentException(illegalArgumentExceptionMessage);
}
if (!configurationFile.isFile()) {
String illegalArgumentExceptionMessage =
String.format(EXCEPTION_PATH_IS_NOT_A_FILE,
configurationFile.getAbsolutePath());
throw new IllegalArgumentException(illegalArgumentExceptionMessage);
}
if (!configurationFile.canRead()) {
String illegalArgumentExceptionMessage =
String.format(EXCEPTION_FILE_CAN_NOT_BE_READ,
configurationFile.getAbsolutePath());
throw new IllegalArgumentException(illegalArgumentExceptionMessage);
}
// ... more tests, like "isEncoding(X)", "isBanana(ripe)", ...
}
Looks like a lot of boilerplate for something I could be “pinching” from somewhere. Especially because these are not all the checks that I need, there is more (e.g. the file is a text file and has the right encoding, …). It seems reasonable to me that there would be a simpler way to do it than this. Perhaps a FileSpecs object to construct through a Builder and to pass to a verifyFileSpecs static helper?
Question: am I doing it wrong or is there code I could reuse?
Answer to the FAQ for post validity:
Shows I made some research beforehand: I looked at the Java 6 SDK, that’s where I got the different methods from, looked at JDK 7 and Files.isReadable, looked at Apache Commons IO, …
Shows that this question is unique: I am specifically asking if there is code that I can reuse, I am not asking “how do I check if a path corresponds to a file and not a directory?”, all of which has already an answer on SO
Why this could be useful to others: teams don’t like boilerplate code like that submitted for code review, checked-in and versioned, potentially maintained (unit tests, etc.) So, borrowing the code from a reputable source would be very helpful, in my opinion.
Yes, I would say above code is not
DRY (Don't Repeat Yourself).Consider using Validate from Apache Commons.