Meaningless Drivel is fun!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Assertions Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Assertions" Watch "Assertions" New topic


John Campbell
Ranch Hand

Joined: Mar 11, 2005
Posts: 53
It is generally considered incorrect to use asserts to check the values passed in as parameters to a public method.

Why is this restriction to public methods only?
Marc Marechal

Joined: Apr 15, 2005
Posts: 17
See the SUN tutorial : Programming With Assertions :

And Effective Java Programming Language Guide, rule 23.

Programming With Assertions

Do not use assertions for argument checking in public methods.

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.

Do not use assertions to do any work that your application requires for correct operation.

Because assertions may be disabled, programs must not assume that the boolean expression contained in an assertion will be evaluated.

Effective Java Programming Language Guide, rule 23

For an unexported method, you as the package author control the circumstances under which the method is called, so you can and should ensure that only valid parameter values are ever passed in. Therefore nonpublic methods should generally check their parameters using assertions rather than normal checks. If you are using a release of the platform that supports assertions (1.4 or later), you should use the assert construct; otherwise you should use a makeshift assertion mechanism.
John Campbell
Ranch Hand

Joined: Mar 11, 2005
Posts: 53
Cheers Marc
Don Redd
Ranch Hand

Joined: Jan 05, 2012
Posts: 82

Joanne Neal

Joined: Aug 05, 2005
Posts: 3742
Don Redd wrote:What does "MAKE SHIFT ASSERTION MECHANISM "meant by?

It means assertion functionality that you implement yourself. Assertions didn't exist in Java before 1.4 so if you wanted to use them you had to work out a way to do something similar yourself.

Don Redd
Ranch Hand

Joined: Jan 05, 2012
Posts: 82

thanks Neal..
I agree. Here's the link:
subject: Assertions
It's not a secret anymore!