1

I used to insert java1.4's assertion construct in my codes and find it really practical because it allows me to enable the inserted assertions in debug- time and disable them at compile-time.

My question is: whether it is possible to do the same thing to the modern Preconditions.checkArgument(..) etc in Guava's library?
This is important to know. We may have plenty of guava's precondition check in the codes, but most of them are for debugging purpose and may affect performance when the number of such preconditions quickly becomes large.

Thank you for your idea.

zell
  • 9,830
  • 10
  • 62
  • 115

3 Answers3

8

No, there isn't. If you really want to take off your seatbelts when you're driving at high speed, use assert instead.

In my experience, most preconditons are really cheap - and very unlikely to have a significant performance impact in real life. (Whereas the impact of unexpected bad data getting into your system and not being detected until it's messed everything else up can be huge...)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Moreover, the JIT can quite often determine that passing a precondition makes some subsequent check prescribed by the language specification redundant, like in `checkNotNull(a); checkArgument(i < a.length);` ... `int x = a[i];`, so the precondition may be completely free. – maaartinus Feb 20 '13 at 21:36
  • Actually, the answer (that I accept with reservation) does not seem to be convincing. The time overhead needs to be measured and statistically analyzed. To add these preconditions is like JVM performs array bounds checks orinserting comparison instructions before accessing an array element, or null pointer check etc. It is known that safety checking mechanisms in JVM do cause heavy runtime overhead. – zell Feb 24 '13 at 06:50
  • @zell: How heavy is heavy though? I accept that it's worth measuring - but I take the attitude that I won't micro-optimize (which includes with preconditions) without evidence. – Jon Skeet Feb 24 '13 at 08:07
0

You can use valid4j with hamcrest-matchers instead (found on Maven Central as org.valid4j:valid4j). Although I don't recommend it, valid4j is possible to switch off.

With system property: -Dorg.valid4j.AssertiveProvider=disabled

Or using a service loader, add a file /META-INF/services/org.valid4j.AssertiveProvider with a line org.valid4j.impl.AssertiveDisabledProvider

Links:

keyoxy
  • 4,423
  • 2
  • 21
  • 18
0

Take a look at https://github.com/cowwoc/requirements.java/ (I'm the author). It achieves exactly what you're asking for (the code gets optimized-away by the JIT) if assertions are disabled:

assertThat(name, value).isGreaterThan(5);

I provide specific performance numbers at the bottom of the document.

Gili
  • 86,244
  • 97
  • 390
  • 689