I would like less-computational-intensive assertions to remain on at all times and disable higher-computational-intensive assertions. A practical use case could be when we move the code to production (according to the Pragmatic Programmer, this is the suggested way to handle assertions).
What is the best way to go about controlling assertions? (Note, I have already enabled assertions in the VM variables using "-ea").
A simple example:
/**
*
* @precondition sizeOfList >= 2
*/
private ArrayList<Integer> createSortedList(int sizeOfList){
ArrayList<Integer> results = new ArrayList<Integer>();
for(int i = 0; i<sizeOfList; i++){
<algorithm to add sorted numbers to array>
}
if(<some_flag>)
assert results.get(0) < results.get(1) : "Results are not sorted.";
assert results.size() == sizeOfList : "Results-list size does not equal requested size.";
return results;
}
Is it best to use System Properties to control the variable? If that's the case, can System Properties be set for an entire project and not just a particular class (in Eclipse)?
Is it a better idea to use a constant variable defined in a "Constants" class?
Are there other ways I'm not thinking of?
Thanks in advance.
The defining feature of the assert statement is that it can be turned off, so I would only use it for the assertions that should not always run. For the assertions that always run, I'd do something like:
if (results.size() != sizeOfList)
throw new AssertionError("Results-list size does not equal requested size.");
Then, you can enable / disable the expensive assertions through the -ea
JVM option.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With