我有这个代码来验证java.io.File
参数,该参数不应该是null
,应该是可访问的,应该是文件而不是目录等
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)", ...
}
看起来像是我可能在某个地方"捏"的东西的样板。特别是因为这些不是我需要的所有检查,还有更多(例如,文件是一个文本文件,并且有正确的编码,…)。对我来说,有一种比这更简单的方法来做这件事似乎是合理的。也许是要通过Builder构造并传递给verifyFileSpecs静态帮助程序的FileSpecs对象?
问题:我是做错了还是有代码可以重用
有效期后常见问题解答:
显示我之前做了一些研究:我查看了Java 6 SDK,这是我获得不同方法的地方,查看了JDK 7和Files.isReadable,查看了Apache Commons IO。。。
这表明这个问题是独一无二的:我特别问是否有我可以重用的代码,我不是在问"我如何检查路径是否对应于文件而不是目录?",所有这些都已经在SO 上得到了答案
为什么这对其他人有用:团队不喜欢提交代码审查、签入和版本控制、潜在维护(单元测试等)的样板代码。因此,在我看来,从信誉良好的来源借用代码会非常有帮助。
是的,我认为上面的代码不是DRY (Don't Repeat Yourself)
。
考虑使用Apache Commons中的Validate。
public static Banana fromConfigurationFile(File configurationFile) {
Validate.notNull(configurationFile, String.format(EXCEPTION_PATH_REFERENCE_IS_NULL, configurationFile));
Validate.isTrue(configurationFile.exists(), String.format(EXCEPTION_PATH_DOES_NOT_EXIST, configurationFile.getAbsolutePath()));
Validate.isTrue(configurationFile.isFile()), String.format(EXCEPTION_PATH_IS_NOT_A_FILE, configurationFile.getAbsolutePath()));
// and more validation...
}