6

I am studing for 1Z0-851 Oracla Java SE 1.6 Certification and I saw this question:

Question from test

I marked the first alternative as the correct one and failed! "All of the assert statements are used appropriately" and the answer says that the first one assert(x > 0); is incorrect.. the question is why?

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
thiagoh
  • 7,098
  • 8
  • 51
  • 77

4 Answers4

4

The correct answer is this

Appropriate and inappropriate use of assertions

You can place an assertion at any location that you don't expect to be reached normally. Assertions can be used to validate the parameters passed to a private method. However, assertions should not be used to validate parameters passed to public methods because a public method must check its arguments regardless of whether assertions are enabled or not. However, you can test postconditions with assertions in both public and non-public methods. Also, assertions should not change the state of a program in any manner.

Src: http://www.freejavaguide.com/java-scjp-part1.pdf

  • +1 Nice, didnt know that. Although personally I only ever use assertions in unit tests..! – cowls Feb 26 '13 at 08:42
3

Line 12 is redundant.

if you remove it, the assertion on line 15 will cover the case where x <= 0

To be honest its a strangely worded question but that is all I can see. I am not sure what is meant by appropriately

cowls
  • 24,013
  • 8
  • 48
  • 78
1

If you read just the first assert statement -- which should be interpreted as a "precondition" because of its position --, it implies that the function should work properly with any positive int value, which is not true. Therefore, that assertion is misleading.

Bruno Reis
  • 37,201
  • 11
  • 119
  • 156
  • The function doesn't work for any values of x. Either it's a negative number and fails the first, or it `assert false`s. – asteri Feb 25 '13 at 17:54
0

Starting by go2, it is easy to understand the assert.
The method does nothing, it just asserts your expectation, that x < 0.

The go method, on the other hand, has a switch.
It is good practice to assert false on the default clause, if you absolutely do not expect your program to fall under this clause, ie, under normal circumstances, one of the cases has to be correct.

The only case on the switch expects x to be exactly 2.
So, to sum up, you don't expect x to be greater than 0, as the first assertion says, you expect x to be 2 and nothing else. Thus, the assertion is not used appropriately.

However, as Jeff noted, the case has no break, which means the default will always be executed, leading, in every scenario, to assert false.

Conclusion: The go method should always result in an error, making assert false properly used, while assert x > 0 isn't correct at all.

Community
  • 1
  • 1
afsantos
  • 5,178
  • 4
  • 30
  • 54