The interesting but useful mock assertion in Java
在某开源项目里, 发现它使用了一种很有意思的 assertion 机制. 这是一种仿 assertion 的方式来实现对输入参数或特定表达式的判断.
伪代码如下:
public final class Assert {
private Assert() {}
public static void notNull(Object o) {
notNull("Null object is used", o);
}
public static void notNull(String description, Object o) {
if(o == null) {
throw new AssertionException(description);
}
}
...... // other assertion methods
}
AssertionException 继承自 RuntimeException, 因此是可以不捕获的.
在某方法里可以如此使用这个 Assert :
public void someMethod(String arg1 ...) {
Assert.notNull(arg1);
...
}
好处是:
1. 类似 Java 已有的 Assertion 机制, 使用起来非常直观.
2. 减少了大量对参数进行 if-else 等的判断, 代码看起来更加整洁, 易懂.
3. 对类似错误可以进行统一处理, 对错误信息进行统一描述.
By javafuns on July 30, 2009 at 10:55 ·
Views: 272 · Permalink
Categorized in: Java · Tagged with: Java, Open Source
Categorized in: Java · Tagged with: Java, Open Source


(