| Author |
inappropriate use of assertions
|
Sekhar Kadiyala
Ranch Hand
Joined: Feb 17, 2004
Posts: 170
|
|
Hi guys, i came accross the following question.
Which fragment is an example of inappropriate use of assertions? A. assert(!(map.contains(x))); map.add(x); B.if (x>0) {} else (assert(x==0);} C.public void aMethod(int x) { assert(x>0);} D.assert(amethod2()); return retval; E.switch(x) { case 1: break; case 2:break; default:assert(x==0);
I thought the answer should be C as we are creating a method just for the purpose of asserting. Am i thinking in the right direction? or any other answers?
|
PMP CSQA SCJP SCWCD SCBCD INS 21 INS 23
|
 |
Adrian Pang
Ranch Hand
Joined: Feb 20, 2004
Posts: 40
|
|
|
I think C, because we shouldn't use assertion to check parameters of a public method, and D, because amethod() is a side-effect and won't be called with asserts disabled.
|
SCJP 1.4, SCWCD 1.4, SCBCD 1.3
|
 |
Charlie Goth
Ranch Hand
Joined: Feb 26, 2004
Posts: 60
|
|
|
D could just be a get method and not do anything else, so just C.
|
SCJP (77%)
|
 |
Bojan Knezovic
Ranch Hand
Joined: Nov 20, 2003
Posts: 90
|
|
I agree with Adrian, think the C is the way to go - assertions should not be used in the public methods, one should rather have all the logics built INSIDE the method because you can never tell who will use your method and with what parameter values. OTOH, I'm not sure about the D, the first part of the assert should be an expression that evaluates to true or false, so if the amethod2() method returns boolean, it's OK, otherwise I'd put it on the list as well. [ March 05, 2004: Message edited by: Bojan Knezovic ]
|
 |
fethi makhlouf
Ranch Hand
Joined: Feb 16, 2004
Posts: 50
|
|
Hello that's your code .. -------------------------------------------------------------------------------- Which fragment is an example of inappropriate use of assertions? A. assert(!(map.contains(x))); map.add(x); B. if (x>0) {} else (assert(x==0);} C. public void aMethod(int x) { assert(x>0);} D. assert(amethod2()); return retval; E. switch(x) { case 1: break; case 2:break; default:assert(x==0); -------------------------------------------------------------------------------- I think neither C nor D is appropriate use of assertions, but is that all? No! A is using a method call to check assertion condition, it's not appropriate use specially if that method will affect any value! it depends on the method code! ain't? Fethi
|
SCJP 1.4
|
 |
Adrian Pang
Ranch Hand
Joined: Feb 20, 2004
Posts: 40
|
|
I think it's ok to use the return value of a method for assertion, as long as the correct operation of the program does not depend on invoking the method. Since it's unlikely that the program in A will depend on .contains being called, I think it's ok. By the same token, as long as the correct operation of the program in D doesn't depend on amethod() being called, it's ok. =) -- Exam in an hr, getting nervous =) Adrian
|
 |
 |
|
|
subject: inappropriate use of assertions
|
|
|