assert(), require(), expect()

ulfben Aug 29th, 2019 83 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. I habitually put assert()-statements in my code to check for programmer errors. When an assert() triggers it crashes the application immediately so the programmer error can be fixed. Problem is: assert() doesn't actually exist in the Android runtime (ART)! You can try it yourself - put assert(false) in your Game constructor and run it - nothing happens! Not in debug mode, not on the emulator nor on the physical device.
  3. So I added two new static functions into our Utilities-class - require() and expect().
  4. */
  5. import android.util.Log;
  7. public abstract class Utils {
  8.     public static void expect(final boolean condition, final String tag) {
  9.         Utils.expect(condition, tag, "Expectation was broken.");
  10.     }
  11.     public static void expect(final boolean condition, final String tag, final String message) {
  12.         if(!condition) {
  13.             Log.e(tag, message);
  14.         }
  15.     }
  16.     public static void require(final boolean condition) {
  17.         Utils.require(condition, "Assertion failed!");
  18.     }
  19.     public static void require(final boolean condition, final String message) {
  20.         if (!condition) {
  21.             throw new AssertionError(message);
  22.         }
  23.     }
  24. }
  26. /*
  27. requires() will throw an AssertionError and thus be functionally equivalent to the original assert(). Your application will crash, and the debugger will give you a stack trace to show where the fault was.
  29. expects() logs the error but won't crash the app. This is good for documenting non-critical expectations.
  31. Ergo: whenever you see an assert() in my Java-articles, replace it with Utils.requires() in your own code.
  32. */
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand