• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Assertions to validate arguments; Inappropriate to validate PUBLIC arguments

 
Sandra Bachan
Ranch Hand
Posts: 434
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

In Sierra/Bates, Chapter 5, it says, “Do not use assertions to validate arguments to a public method.” What is the logic behind this. In other words, where can I find code examples where someone uses assertions to validate arguments to a public method, and then the program goes berserk?

I do understand that it is not ILLEGAL for assertions to validate public arguments....

 
Ireneusz Kordal
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Proper and improper uses of assertions is discussed in the Sun's Java Tutorial here:
http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html

Argument checking is typically part of the published specifications (or contract) of a method, and these specifications must be obeyed whether assertions are enabled or disabled. Another problem with using assertions for argument checking is that erroneous arguments should result in an appropriate runtime exception (such as IllegalArgumentException, IndexOutOfBoundsException, or NullPointerException). An assertion failure will not throw an appropriate exception.



Sandra Bachan wrote:Hello,
I do understand that it is not ILLEGAL for assertions to validate public arguments....

This is not illegal (Java does not prevent you from doing this), but it is considered as a bad programming practice.
Anyway, Sus says in the tutorial:
- "Do not use assertions for argument checking in public methods"
- "Do not use assertions to do any work that your application requires for correct operation."
and you may get a question regarding these rules on the exam.
 
Sandra Bachan
Ranch Hand
Posts: 434
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So in other words, using assertions on public arguments has the potential to mask an exceptions the program may have, because an assertion will simply point out that some value is not what it is supposed to be. Now it makes sense, assertion is a private debugging tool for the developer, whereas exception may be shown to the user, i.e if they enter a number instead of a character.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic