2

Working with Chromium codebase I got used to macros like CHECK(condition);, DCHECK(contidtion) and NOTREACHED;. They introduce assertions (usually preconditions) to the code and allow to terminate program with some info in a log, an in debug build DCHECK and NOTREACHED would also stop debugger to investigate the case. First one is active only in release mode and latter two only in debug - when "unactive" they would be replaced by an empty macro and not cause any overhead.

Is there some library in Java that allows such thing? I know that I could create some static method/object and depending on configuration swap configuration but I cannot see the way to avoid creating overhead. Besides, I wouldn't want to reinvent the wheel.

Mateusz Kubuszok
  • 24,995
  • 4
  • 42
  • 64

2 Answers2

3

You can use the assert keyword:

public void yourMethod(String arg) {
    assert arg != null : "arg may not be null";
    // ...
}

which is equivalent to

public void yourMethod(String arg) {
    if (arg == null) throw new AssertionError("arg may not be null");
    // ...
}

Asserts are disabled unless the -ea switch is given when starting the JVM and will have close to 0 overhead when disabled.

The equivalent to NOTREACHED would be assert false;

Related: What does the "assert" keyword do?

Community
  • 1
  • 1
aioobe
  • 413,195
  • 112
  • 811
  • 826
  • [Programming With Assertions](http://docs.oracle.com/javase/8/docs/technotes/guides/language/assert.html#usage-control) discusses how to use this, including for pre-conditions, post-conditions, and control flow invariants. – Patricia Shanahan Dec 10 '14 at 18:29
  • So I need to manually handle it in my `UncauchtExceptionHandler` to log error and terminate, and configure debugger to stop on `AssertionException`? I guess it cannot be done prettier... – Mateusz Kubuszok Dec 10 '14 at 18:37
  • Debuggers often stop automatically on uncaught exceptions. – aioobe Dec 10 '14 at 19:41
0

I authored a library that helps writing preconditions, postconditions with an emphasis on readability. For example:

// Input
List<Integer> actual = Arrays.asList(2, 3, 4, 6);
List<Integer> expected = Arrays.asList(1, 3, 5);
requireThat(actual, "actual").containsAll(expected);

// Output
java.lang.IllegalArgumentException: actual must contain all elements in: [1, 3, 5]
Actual : [2, 4, 6]
Missing: [1, 5]
Gili
  • 86,244
  • 97
  • 390
  • 689