Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controlling Java Assertions - Best Practices

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.

like image 264
mtical Avatar asked Nov 03 '22 15:11

mtical


1 Answers

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.

like image 101
meriton Avatar answered Nov 14 '22 23:11

meriton