Question 10 in chapter 6 asks:
10. Which of the following are true of the code? (Choose all that apply.)
4: private int addPlusOne(int a, int b) {
5: boolean assert = false;
6: assert a++ > 0;
7: assert b > 0;
8: return a + b;
9: }
A. Line 5 does not compile.
B. Lines 6 and 7 do not compile because they are missing the String message.
C. Lines 6 and 7 do not compile because they are missing parentheses.
D. Line 6 is an appropriate use of an assertion.
E. Line 7 is an appropriate use of an assertion.
In the answers is stated that E is correct because checking with assert an argument passed from elsewhere in the program is a good use of assertions.
But in the book is explicitly stated that, when checking method parameters, we should not use asserts, but we should throw IllegalArgumentException instead (and I agree with that).
Why is there this discrepancy? Maybe it is because for the exam we should answer "Yes, it is appropriate", but in real life we should answer "No, throwing IllegalArgumentException is appropriate instead" ?
Luigi Rubino
OCP Java SE8 Programmer, OCE-JPAD JPA Developer, SCBCD (1.3) , SCWCD (1.4), OCA DBA 10g
https://it.linkedin.com/in/luigirubino