Here is a question I'm trying to answer:
Which of the following use assertions appropriately?
public class Hunt { public static void main(String... args) { int y = 10; assert y > 5; // #1 new Hunt().netant(y); } public void netant(int x) { assert x > 0; // #2 anteater(x); } private void anteater(int x) { assert x > 0; // #3 } }Choose: 2
Options:
- #1
- #2
- #3
- The program has runtime errors although assertions are used correctly
Correct Answer: 1 & 3
Explanation: It is not advisable to use assertions to assert arguments of public methods
Source:http://www.certpal.com
The answer states "It is not advisable to use assertions to assert arguments of public methods". But in the above code even though assert statement is used to assert arguments of main() method it is chosen as the right answer!
Is it advisable to use assert statement in main() method?
Assertions are a defence mechanism for coding errors. Entering an invalid argument in to a public method is a user error, even if it's an API a programmer is using.
Users should never see an assert, tests should.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With