Safer Assert

I'm currently working on a project using the J2SE™ 5.0 platform. This is the first large project I've done since 1.3. One of the new(ish) features that I use often is assertions. In particular, I find myself using assert false quite a lot, as an indication that even reaching the given point in the code is a problem. In testing, though, I've noticed that if assertions are disabled, which is the default state, bad things happen because of my reliance on assert false. Because the assertions are ignored, the VM doesn't break out at my assert false points, and it goes on to do bad and often confusing things.

I began to wonder if I wasn't perhaps misusing the assertion facility. After a quick search, I found Programming With Assertions. In that document, the author validates my use of assert false, but suggests a safer alternative. Instead of assert false : "message";, the author recommends throw new AssertionError("message");. The effect is the same, except for two caveats. First, even when assertions are disabled, the later will still cause an error to be thrown. Second, in cases where a return statement is expected in the branch, the former is a syntax error while the later is valid.

Armed with this new bit of knowledge, I will be replacing the occurances of assert false in the project source base as I run across them.

Comments:

Post a Comment:
Comments are closed for this entry.
About

templedf

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today