Browsing around StackOverflow I came across a question about specifying binary files. One of the answers said that the Java spec for class files was a good example of how to do it.
So I went there to look and found this:
ClassFile {
…
u2 constant_pool_count;
cp_info constant_pool[constant_pool_count-1];
…
}
and the following description:
constant_pool_countThe value of the constant_pool_countitem is equal to the number of entries in theconstant_pooltable plus one. Aconstant_poolindex is considered valid if it is greater than zero and less thanconstant_pool_count, with the exception for constants of typelonganddoublenoted in §4.4.5.constant_pool[]The constant_poolis a table of structures (§4.4) representing various string constants, class and interface names, field names, and other constants that are referred to within theClassFilestructure and its substructures. The format of eachconstant_pooltable entry is indicated by its first "tag" byte. Theconstant_pooltable is indexed from1toconstant_pool_count-1.
and I wondered if this is a good spec what does a horrible one look like?
Granted, this is quite chatty, but when you read it for sense you get more and more confused.
It looks like a C structure, so let's read it like one…
Why is the count one more than the number of elements in the array? The array index starts at 0 when I declare one. Oh yeah: the valid indexes are greater than zero (why omit the zero index?)—except for some long and double stuff, life's too short—and then the valid indexes are from 1 to count-1.
Whoa! where do they go? The declaration a[3] normally allocates three elements (indexes 0, 1 and 2), but here we allocate count-1 and index from 1 to count-1. The last index would be invalid!??!
Aha! We must be basing our arrays from one and not zero!!
…and the
Ugh!
If this is a good spec my name is Edsgar Dijkstra.
