Sunday, April 1, 2012

Assertion Summary


Assertion Summary

  • Assertions give you a way to test your assumptions during development and debugging.

  • Assertions are typically enabled during testing but disabled during deployment.

  • You can use assert as a keyword (as of version 1.4) or an identifier, but not both together. To compile older code that uses assert as an identifier (for example, a method name), use the -source 1.3 command-line flag to javac.

  • Assertions are disabled at runtime by default. To enable them, use a command-line flag -ea or -enableassertions.

  • You can selectively disable assertions using the -da or -disableassertions flag.

  • If you enable or disable assertions using the flag without any arguments, you’re enabling or disabling assertions in general. You can combine enabling and disabling switches to have assertions enabled for some classes and/or packages, but not others.
  • You can enable or disable assertions in the system classes with the -esa or -dsa flags.

  • You can enable and disable assertions on a class-by-class basis, using the following syntax:

  • java -ea -da:MyClass TestClass

  • Do not use assertions to validate arguments to public methods.

  • Do not use assert expressions that cause side effects. Assertions aren’t guaranteed to always run, so you don’t want behavior that changes depending on whether assertions are enabled.

  • Do use assertions—even in public methods—to validate that a particular code block will never be reached. You can use assert false; for code that should never be reached, so that an assertion error is thrown immediately if the assert statement is executed.

  • Do not use assert expressions that can cause side effects.




No comments:

Post a Comment