Why
1) you can test postconditions with assertions in both public and non public methods
but, you are advised to
2) not use assertions to check the parameters of a public method(preconditions)?
I understand that 2) is caused by : - convention: the method guarantees that it will always enforce the argument checks(e.g. with checked exceptions) so it must check its arguments whether or not the assertions are enabled. - the assert construct does not throw an exception of the specified type. It can throw only an AssertionError, which is not quite user friendly
But I don't understand why 1) is available for public methods as well ?
Thanks.
The above questioned rephrased :) A contract is made of two parts :
- requirements upon the caller made by the class
- promises made by the class to the caller
Why Sun advises you to not use assertions as preconditions for public methods because the assertions could be disabled and then you are not checking the requirements imposed on the caller, but allows you to use assertions to test postconditions for public methods(test the return value to see you are returning a correct result) is still an enigma for me.
Put in other words, you must be very careful when enforcing requirements, but you can close an eye when verifying the promises.
Is there a technical reason for this metaphorically called "lack of ethics" that you demostrate when you enforce your client to respect the requirements, but you are not so harsh with yourself in respecting the promises ? :)