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: 412 · Permalink · RSS
Categorized in: Java · Tagged with: ,
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Leave a Reply


  • Highest Rated

  • My PicasaPhotos

    IMG_0521.JPG

    1557e2d1543651c0562c84c3.jpg

    0845191.jpg

  • RSS My del.icio.us

  • My RSS