You can use assertion any where syntactically. But, assertion is used in testing purposes, so, if you used it in public methods, then it can be used by outsiders.
|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
Joined: Sep 23, 2010
Sorry Abimaran..Let me modify the question. As per K&B, It is NOT APPROPRIATE to use assertions on public methods &APPROPRIATE to use on private methods. What about methods with protected or default access specifiers ?
Harikrishna Gorrepati wrote:Sorry Abimaran..Let me modify the question. As per K&B, It is NOT APPROPRIATE to use assertions on public methods &APPROPRIATE to use on private methods. What about methods with protected or default access specifiers ?
Do you mean to it appropriately? Or syntactically?
Joined: Sep 23, 2010
I am referring "appropriately". syntactically, we can use anywhere(public, private, protected, default).
A public method might be called from code that you don't control (or from code you have never seen). Because public methods are part of your interface to the outside world, you're supposed to guarantee that any constraints on the arguments will be enforced by the method itself. But since assertions aren't guaranteed to actually run (they're typically disabled in a deployed application), the enforcement won't happen if assertions aren't enabled. You don't want publicly accessible code that works only conditionally, depending on whether assertions are enabled. If you need to validate public method arguments, you'll probably use exceptions to throw, say, an IllegalArgumentException if the values passed to the public method are invalid.
So, only within the private method is the appropriate, because You don't want publicly accessible code that works only conditionally, depending on whether assertions are enabled. Others are accessible from outside.
I disagree. You can stick assertions wherever you want.
The point the book makes though, is that you shouldn't rely on them. If you want your code to fail fast and reliably, you need to use exceptions.
Assertions simply make more sense in private methods than in public, default and protected methods, because since you're the only one who has access to the method, you may assume you call the method correctly.
Personally, I rarely find assertions useful. I can imagine they are very helpful in big classes written by multiple programmers, but if I write code by myself and I can take the time to insert the assertions, I can also take the time to make sure my code works correctly.
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.