...
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
class MyWrapper { private CommsFramework cf = new CommsFramework(); private boolean isWebServiceAvailable() { return cf.getStatus().equals("webservice") ? true : false; } // all operations that will read and write from the CommsFramework will do the following { ... try { assert ! isWebServiceAvailable(); } catch( AssertionError ae ) { // don'toperate continuein todegraded executemode beyonfand thisshutdown pointgracefully ... } } ... } |
The assert is used to ensure that we only run the code if the there is a webservice connection.
Yes this is somewhat a contrived example but it aims to show a possible use of assert. The problem is if we disable the assert feature this could would not compile. With all of the examples that I have shown and with the use of tools like JUnit and NUnit I would argue that there is no real reason to use assert, pre and post conditions can be tested through with well thought out tests and object state can definitely be tested through unit tests. Control flow might be a possible use as this is difficult to test with unit tests.
To indicate preconditions concerning whether or not a given lock is held
There maybe one situation where the assert may be a useful tool.
Classes designed for multithreaded use often have non-public methods with preconditions relating to whether or not some lock is held. For example, it is not uncommon to see something like this:
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
private Object[] a;
public synchronized int find(Object key)
{
return find(key, a, 0, a.length);
}
// Recursive helper method - always called with a lock on this object
private int find(Object key, Object[] arr, int start, int len)
{
...
} |
A static method called holdsLock
has been added to the Thread
class to test whether the current thread holds the lock on a specified object. This method can be used in combination with an assert
statement to supplement a comment describing a lock-status precondition, as shown in the following example:
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
// Recursive helper method - always called with a lock on this. private int find(Object key, Object[] arr, int start, int len) { assert Thread.holdsLock(this); // lock-status assertion ... } |