ulfben icon

assert(), require(), expect()

ulfben | PRO | 08/29/19 04:50:15 PM UTC | 0 ⭐ | 1289 👁️ | Never ⏰ | []
Java |

1.6 KB

|

None

|

0 👍

/

0 👎

/*
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.
So I added two new static functions into our Utilities-class - require() and expect(). 
*/
import android.util.Log;
 
public abstract class Utils {
    public static void expect(final boolean condition, final String tag) {
        Utils.expect(condition, tag, "Expectation was broken.");
    }
    public static void expect(final boolean condition, final String tag, final String message) {
        if(!condition) {
            Log.e(tag, message);
        }
    }
    public static void require(final boolean condition) {
        Utils.require(condition, "Assertion failed!");
    }
    public static void require(final boolean condition, final String message) {
        if (!condition) {
            throw new AssertionError(message);
        }
    }
}
 
/*
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. 
 
expects() logs the error but won't crash the app. This is good for documenting non-critical expectations.
 
Ergo: whenever you see an assert() in my Java-articles, replace it with Utils.requires() in your own code. 
*/

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎

    
        
  • Yuizcko icon
    05/18/26 01:02:40 PM UTC
    text |

    0 B

    |

    0 👍

    /

    0 👎

    Best t33n active cpx link daily updates!
     Copy and paste the link in a new browser tab and then hit enter!
     https://crazyporn.xxx/members/157354/?asgtbndr=1&play=true&spon=adworld&zone=400