Roedy said:
An assert on program structure needs to be on only once.
I am not so sure about turning asserts off. Why?
That is their purpose.
The idea is that once you've proven the invariants, there's no need to keep
proving them except when the code changes. The code doesn't change in
production, by definition, it changes in development.
1. a clever compiler optimises them out or makes them low overhead.
Evidence?
2. If things blow up at a client site, you want all the hints you can
get.
That's what exceptions are for. And you can turn assertions on at the
production site, at will, class by class, when you need those hints.
The nature of invariants is that they're, well, invariant. Unlike exceptional
conditions, they don't change from run to run. Once you lock them down, turn
off the assertions. If you goofed, that's on your shoulders; then you have to
turn them back on (perhaps partially) and correct your mistake before you turn
them back off again.
It's a common mistake to think assertions are exceptions. They aren't.
Part of the reason for that mistake is that people don't analyze algorithms in
terms of invariants enough. When you look at an assertion in the code, it
often states the "obvious", as in:
public void setLittleRabbit( Foo foo )
{
if ( foo == null )
{
throw new IllegalArgumentException( new NullPointerException(
"foo == null" ));
}
this.littleRabbit = foo;
assert this.littleRabbit != null;
}
This in turn allows the set invariant postcondition to be a get.. invariant
precondition:
public Foo getLittleRabbit()
{
assert this.littleRabbit != null;
return this.littleRabbit;
}
Now, should someone subclass or alter this class and fracture the invariant,
the asserts will raise the salute. Since they're turned on in development and
all, you know.