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 ..
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.