File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
JavaRanch » Java Forums » Java » Java in General
Bookmark "why not assertion for public methods ??" Watch "why not assertion for public methods ??" New topic
Author

why not assertion for public methods ??

Geet Chaudhary
Greenhorn

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
Bartender

Joined: Sep 20, 2010
Posts: 3649
    
  17

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: why not assertion for public methods ??