Friday, April 16, 2010

CodeSOD: Check Digit Check

CodeSOD: Check Digit Check: "

Seen any absurdly bad code lately? Send it on in!



Anne K has worked in the direct mail industry for almost twenty years, and has seen a bazillion ways to put names and addresses onto paper. One thing that's common across all mailing houses is that, in order to get discounts from the postal service, a postal barcode must be printed on every piece of mail. The barcode is made up of the ZIP code, the ZIP+4 code, and a couple more digits indicating (often) the house number. There's also a check digit on the bar code, which is calculated by adding up all the digits of the barcode, modding the result by 10, and then subtracting from 10. So, if all the digits of the barcode add up to 39, (10 - (9 mod 10)) leaves a result of 1.


It couldn't be simpler, right? It takes a teeny little loop and a mod. At least, that's what Anne thought. When she was doing developer training at a certain mailhouse, she just happened to be looking into the program that printed a simple name and address block on the piece. Curious as to why it was thousands of lines of code, she dove in and saw this.




counter=0;
if (zipcode >= 34200 AND zipcode <= 34299){
zzipcode = zipcode - 34200
counter = counter + 3 + 4 + 2;
}

if (zipcode >= 34600 AND zipcode <= 34799){
zzipcode = zipcode - 34600
if (zzipcode > 99){
counter = counter + 1
}
counter = counter + 3 + 4 + 6;
}

... snip ...

if (zzipcode < 10){
counter = counter + zzipcode;
}
if (zzipcode = 10) counter = counter + 1
if (zzipcode = 20) counter = counter + 2
if (zzipcode = 30) counter = counter + 3
if (zzipcode = 40) counter = counter + 4
... snip ...
if (zzipcode = 98) counter = counter + 17
if (zzipcode = 99) counter = counter + 18


Naturally, this is just a small subsection of the code (with proper indentation added). The original programmer apparently didn't realize there were math or, at the very least, string manipulation functions.


As for the most wondrous thing about this program? The coder took special care to find out exactly what ZIP code ranges aren't used by the postal service, so as to avoid unnecessary coding for those ranges.



"

No comments: