On Mon, 4 Aug 2008, marlow.andrew@googlemail.com wrote:
So do people actually find the java assert mechanism useful? I am
relatively new to java and have not seen it used in any projects I
have been on yet. But I do see lots of advice telling newcomers to use
it and how good it is. Does anyone here prefer to always have the
checking on?
I haven't ever used it.
I think the way to think of java assertions is as tiny unit tests which
are embedded in the application code. If you had a class like:
public class OldMoney {
private int pounds ; // must be >= 0
private int shillings ; // must be >=0, <20
private int pence ; // must be >=0, <12
public int getPriceInPence() {
return (((pounds * 20) + shillings) * 12) + pence ;
}
}
You might write a unit test that looked like:
public void testMoneyComponentCounts() {
OldMoney cash = somehowGetSomeMoney() ;
assertGreaterThanZero(cash.getPounds()) ;
assertInBetweenInclusive(0, cash.getShillings(), 19) ;
assertInBetweenInclusive(0, cash.getPence(), 11) ;
}
With assertions, you could write:
public int getPriceInPence() {
assert pounds >= 0 ;
assert (shillings >= 0) && (shillings < 20) ;
assert (pence >= 0) && (pence < 12) ;
return (((pounds * 20) + shillings) * 12) + pence ;
}
Which would do much the same thing, but would run every time you called
that method, if you had assertions switched on.
Then you will need some type of AOP.
If the values tested are exposed, then it should be easy.
framework.