aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Assertions to validate arguments; Inappropriate to validate PUBLIC arguments Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Assertions to validate arguments; Inappropriate to validate PUBLIC arguments" Watch "Assertions to validate arguments; Inappropriate to validate PUBLIC arguments" New topic
Author

Assertions to validate arguments; Inappropriate to validate PUBLIC arguments

Sandra Bachan
Ranch Hand

Joined: Feb 18, 2010
Posts: 434
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....


Marriage Made in Heaven
http://www.youtube.com/user/RohitWaliaWedsSonia
Ireneusz Kordal
Ranch Hand

Joined: Jun 21, 2008
Posts: 423
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

Joined: Feb 18, 2010
Posts: 434
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Assertions to validate arguments; Inappropriate to validate PUBLIC arguments