Is that possible, at compile time, to disable guava's Preconditions like we disable Java 1.4's assert keyword?

StackOverflow https://stackoverflow.com/questions/14976330

Question

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.

Was it helpful?

Solution

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...)

OTHER TIPS

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:

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top