This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Java in General and the fly likes why not assertion for public methods ?? 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 » Java » Java in General
Bookmark "why not assertion for public methods ??" Watch "why not assertion for public methods ??" New topic

why not assertion for public methods ??

Geet Chaudhary

Joined: Feb 15, 2010
Posts: 11
I have a doubt .. why can't we use assertion for public methods ???
I have read somewhere "An assert is inappropriate in public methods because the method guarantees that it will always enforce the argument checks. A public method must check its arguments whether or not assertions are enabled. Further, the assert construct does not throw an exception of the specified type. It can throw only an AssertionError".

So, wont it applicable for private method too ??
I didnt understand the above statement clearly ..
Stephan van Hulst

Joined: Sep 20, 2010
Posts: 4642

I agree with you. Personally I think assertions are pretty useless, but a lot here would disagree with me.

The point is, it's perfectly fine for you to add assertions in a public method, but you should not rely on them, and you should do actual precondition checking with proper exceptions.

The reason they are used only in private methods, is because you don't have to do precondition checking in private methods. Why? Because you wrote the code by yourself, and you may assume that you always adhere to the contract of your private methods. Assertions are used as a kind of backup check, just in case.

The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.
I agree. Here's the link:
subject: why not assertion for public methods ??
It's not a secret anymore!