To assert or not to assert

      Java 2004-6-18 20:54
To assert or not to assert

Don't use assertions to validate parameters of public functions. These functions should throw NullPointerException, IllegalArgumentException, and other relevant exceptions instead. Since public functions will be used by other programmers, you should make sure that they get the right errors if they mess up.

Use assertions to check preconditions and postconditions on parameters of protected and private access methods.

Don't use assertions to check for software user errors. If you expect the user of your web-based online sales system to enter a 10-digit credit card number and she enters only 9 digits, don't use an assert. Instead, throw IllegalArgumentException. If you use assert, as soon as someone turns off assertions on your servlet container, the checking logic in your system would go away.

Use assertions to check parameters and variables for conditions that shouldn't happen.

Use assertions to check for invalid code branches.

Don't use an assertion to do any work. Assertions are developer-level errors and shouldn't be used to repair state in the program or perform complex logging. Also, don't forget that if a user runs the program without assertions, the code will be gone. If that code was critical to the functioning of the program, you could be in deep trouble.

Don't bother internationalizing assertion error messages. Again, since assertions are developer-level issues, internationalizing them would be a waste of time.

Use assertions to check post conditions.
标签集:TAGS:
回复Comments() 点击Count()

回复Comments

{commentauthor}
{commentauthor}
{commenttime}
{commentnum}
{commentcontent}
作者:
{commentrecontent}
}