Java 2 SDK for Solaris Developer's Guide

Design FAQ - Enabling and Disabling Assertions

  1. Why not provide a compiler flag to completely eliminate assertions from object files?

    It is a firm requirement that it be possible to enable assertions in the field, for enhanced serviceability. It would have been possible to also permit developers to eliminate assertions from object files at compile time. However, since assertions can contain side effects (though they should not), such a flag could alter the behavior of a program in significant ways. It is viewed as good thing that there is only one semantics associated with each valid Java program. Also, we want to encourage users to leave asserts in object files so they can be enabled in the field. Finally, the standard Java "conditional compilation idiom" described in JLS 14.19 can be used to achieve this effect for developers who really want it.

  2. Why does setPackageAssertionStatus have package-tree semantics instead of the more obvious package semantics?

    Hierarchical control is useful, as programmers really do use package hierarchies to organize their code. For example, package-tree semantics allow assertions to be enabled or disabled in all of Swing at one time.

  3. Why does setClassAssertionStatus return a boolean instead of throwing an exception if it is invoked when it's too late to set the assertion status (i.e., the named class has already been loaded)?

    No action (other than perhaps a warning message) is necessary or desirable if it's too late to set the assertion status. An exception seems unduly heavyweight.

  4. Why not overload a single method to take the place of setDefaultAssertionStatus and setAssertionStatus?

    Clarity in method naming is for the greater good.

  5. Why is there no RuntimePermission to prevent applets from enabling/disabling assertions?

    While applets have no reason to call any of the ClassLoader methods for modifying assertion status, allowing them to do so seems harmless. At worst, an applet can mount a weak denial-of-service attack by turning on asserts in classes that have yet to be loaded. Moreover, applets can only affect the assert status of classes that are to be loaded by class loaders that the applets can access. There already exists a RuntimePermission to prevent untrusted code from gaining access to class loaders (getClassLoader).

  6. Why not provide a construct to query the assert status of the containing class?

    Such a construct would encourage people to inline complex assertion code, which we view as a bad thing:

               if (assertsEnabled()) {

    Further, it is straightforward to query the assert status atop the current API, if you feel you must:

     boolean assertsEnabled = false;
              assert assertsEnabled = true;  // Intentional side-effect!!!
              // Now assertsEnabled is set to the correct value