assert and IllegalArgumentExceptions

J

jan V

I have zillions of methods which perform very simple "garbage in?" checks
and which throw IllegalArgumentExceptions if method parameters have illegal
values.

Apart from the "if it ain't broke, don't fix it" rule, what do you think
about me combing through my codebase to morf these simple if (..) throw new
IllegalArgumentExceptions(..) into assert statements?

Am I right in thinking that my simple ifs are logically equivalent to
asserts?

Would writing a tool to automate the upgrading of such tests to true asserts
be useful?
 
T

Thomas Hawtin

jan said:
I have zillions of methods which perform very simple "garbage in?" checks
and which throw IllegalArgumentExceptions if method parameters have illegal
values.

Apart from the "if it ain't broke, don't fix it" rule, what do you think
about me combing through my codebase to morf these simple if (..) throw new
IllegalArgumentExceptions(..) into assert statements?

Bad idea. Live with the slightly longer syntax. You may want to move the
checking to purpose built methods.
Am I right in thinking that my simple ifs are logically equivalent to
asserts?

No. Firstly the exception type for assert is a type of Error not a
RuntimeException. But much more importantly asserts are usually switched
off. After a car is taken off the production line and smoke tested, they
don't take out the seatbelts.

Keep asserts to checking internal consistency. They can reasonably used
for checking arguments to private methods (still internal to the (outer)
class), but for testing purposes private methods aren't such a good idea
in the first place.

Asserts should be quite rare.

Tom Hawtin
 
C

Chris Uppal

jan said:
Apart from the "if it ain't broke, don't fix it" rule, what do you think
about me combing through my codebase to morf these simple if (..) throw
new IllegalArgumentExceptions(..) into assert statements?

Not a good idea IMO. Asserts are a tool for documentation and for helping with
debugging (during development /ONLY/).

An assert should be present in delivered code only if it means the following:
"I am certain that <such and such> will be true"

If you are in any doubt about that -- if you think there is a chance that the
test could fail at runtime -- then a "proper" exception is called for. If, on
the other hand, you /are/ certain (or as much as one can legitimately be), then
what's the point of the test in the first place ? Yoy would get exactly the
same "value" from a comment to the same effect. And that's how assertions
should be seen: as a sort of comment.

-- chris
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top