Braincheck is a very simple library that you can used to check invariants in code. It is designed that these invariant
checks can be compiled out in production environments either by the JIT or the GWT compiler. Braincheck also super-sources
Objects.requireNonNull(...) to call javaemul.internal.InternalPreconditions.checkNotNull(...) so that these guards
can be stripped by configuring the compile-time property jre.checks.checkLevel to DISABLED.
The simplest way to use Braincheck is to;
-
Review the javadocs.
-
Add the BrainCheck dependencies into the build system. i.e.
<dependency>
<groupId>org.realityforge.braincheck</groupId>
<artifactId>braincheck</artifactId>
<version>1.32.0</version>
</dependency>-
If the application is a GWT application, then inherit from
org.realityforge.braincheck.BrainCheckin your .gwt.xml for a production build or inheritorg.realityforge.braincheck.BrainCheckDevin a development build. You can also explicitly set the configuration properties to control which parts of the application are optimized away during builds. See the configuration properties section below. -
Add invariant checks to your code to verify various conditions.
import static org.realityforge.braincheck.Guards.*;
class MyClass
{
public void myMethod(int i)
{
// Raise an exception if condition (first parameter) is not true
apiInvariant( () -> i > 0, () -> "You are using the api incorrectly!" );
// Raise an exception if condition (first parameter) is not true
invariant( () -> 1 == 1, () -> "Maths has broken down!" );
// Raise an exception if invariant checks enabled
fail( () -> "You have reached a failing scenario in the application" );
}
}- You can also modify the invariant configuration in tests by setting system property
braincheck.environmenttodevelopmentand interacting with theBrainCheckTestUtilclass. i.e.
import org.realityforge.braincheck.BrainCheckTestUtil;
class MyTest
{
@Test
public void myTest()
{
BrainCheckTestUtil.setCheckApiInvariants( true );
//...
}
}The following configuration properties can be used to configure BrainCheck. These are mainly used to optimize the size of applications that statically compile code (i.e. GWT) when we want to minimize code size.
braincheck.verbose_error_messageswhich can be set totrueorfalseand iftrue, then invariant exception messages will use the supplied message, otherwise no message will be passed to exception.braincheck.check_invariantswhich can be set totrueorfalseand iffalse, calls toGuards.invariant()andGuards.fail()are ignored.braincheck.check_api_invariantswhich can be set totrueorfalseand iffalseor ifbraincheck.check_invariantsis false then calls toGuards.apiInvariant()are ignored.braincheck.environmentwhich can be set todevelopmentorproductionand defaults toproduction. Ifproductionthen the default values forbraincheck.verbose_error_messages,braincheck.check_invariantsandbraincheck.check_api_invariantswill befalseotherwise they will default to betrue.