Alex Rivera | Logout

Is it good practice to use assert in Java?

Asked 2010-12-27T09:06:46.220
35

I know that the keyword assert exists in java. However I don't remember seeing code that uses it. Probably I am using exceptions and logging in places where I could have used it. Is it a good practice to use the assert keyword in java?

EDIT: I know that assertions in general is a good practice. my question is, to be more accurate, if in java the BKM of assertion is using the assert keyword rather than using exception, logging and other techniques.

Edit
Report

1 Answer

1

in my algortihms lectures, my lecturer always maintained the usefulness of assertions. theyre mostly used for test and debugging purposes, which my be why u do see code using it. but yes, theyre highly recomended. they can be disabled if you're worried abt performance. normally i use System.out.println or breakpoints to test, but assertions are one way too. here's what i mean:

For example, to prove that sort+reverse is equivalent to sort in reverse order:
Method 1: sort(int[] arr, int len)
// pre: len is the length of the array arr
// post: arr is sorted in ascending order
Method 2: reverse(int[] arr)
// post: the order of elements in arr is
// reversed (e.g. [9 5 10] -> [10 5 9])
Assertion 1: the length of arr is len
sort(arr,len);
Assertion 2: arr is sorted in ascending order
reverse(arr);
Assertion 3: the order of arr is reversed
answered 2010-12-27T09:18:26.963

Your Answer