What is the use of assertion?

Questions by mikerich135   answers by mikerich135

Showing Answers 1 - 3 of 3 Answers

dear_srik

  • Oct 27th, 2007
 

Assertions are kind of mechanisms in java from 1.4 onwards, where assert is a keyword. By using assertions you can validate your assumptions. Assertions should be only used to validate certain assumptions. Assertions should:

1. Be used to assertain the formal parameters of a private methods against the assumptions, they should never be used to check the formal parameters of public methods.

2. Should not produce any side effects, and the behaviour of the application should not be dependent on the assertions, as they may be enabled or disabled when required.

3. even in public methods, they should be used to flag execution of blocks which should never be executed.(eg: default case in a switch, where all the possible values are listed)

Assertion comes in two flavours, first it takes a boolean value, just like a if statement, if the condition fails, AssertionError is raised which should not be handled insided the code, and in second form it takes an optional string parameter (or anything which can be transformed to string) which is printed on failure of the assertion condition.

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions