assert

Tags:

Do not use assertions to check the parameters of a public method. An assert is inappropriate because the method guarantees that it will always enforce the argument checks. It must check its arguments whether or not assertions are enabled. Further, the assert construct does not throw an exception of the specified type. It can throw only an AssertionError.

You can, however, use an assertion to test a nonpublic method’s precondition that you believe will be true no matter what a client does with the class. For example, an assertion is appropriate in the following “helper method” that is invoked by the previous method:


   /**
    * Sets the refresh interval (which must correspond to a legal frame rate).
    *
    * @param  interval refresh interval in milliseconds.
    */
    private void setRefreshInterval(int interval) {
        // Confirm adherence to precondition in nonpublic method
        assert interval > 0 && interval <= 1000/MAX_REFRESH_RATE : interval;

        ... // Set the refresh interval
    } 

Note, the above assertion will fail if MAX_REFRESH_RATE is greater than 1000 and the client selects a refresh rate greater than 1000. This would, in fact, indicate a bug in the library!

source: http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *