Oct 18, 2013

Assertions

Assertions represent Boolean expressions that a programmer believes to be true at specific points in a program. Assertions were included in Java 1.4, they are often confused as exception handling aids but in essence they help you validate, or better said, evaluate conditions on runtime; they are for debugging not for exception handling. 
Assertion properties commonly fall into one of these three categories:
  • Preconditions that a property holds before a code block executes
  • Postconditions that a property holds after a code block executes
  • Invariants that a property holds before and after a code block executes
 The role of assertions is to identify bugs in a program. Assertions frequently involve writing macros that compile into real-time checks when a debug flag is set.
Note: Assertions are disabled on runtime by default, to enable them you must use the -debug flag 

Programming assertions
Constructors:
assert booleanExpression;
assert booleanExpression : message;

Sample:
assert time>12 : "The value of time must be greater than 12. Time is +"time;

The use of assertion programming can be adopted slowly. Use assertions first around the entry points of functions or methods. Then move on to conditions executed within the code before advancing to manipulations and function returns. As you increase the usage of assertions, the quality of the code will improve.

No comments:

Post a Comment