CodeSOD: Magic Math
LK was browsing a local job site for a new position. The site was flaky, which lead LK to look into the code, and it looks like if anything, this job site should be hiring a new web developer.
function startSWBanner(){ browserType = "new"; timenow = new Date(); secs = timenow.getTime () / 1000; modnum = 2 * 10; range = secs % modnum; n = Math.floor(range / 10); urlArray = new Array(2); banArray = new Array(2); altArray = new Array(2); popupArray = new Array(2); urlArray[0] = '/cgi-bin/banner_track.cgi?banner_id=2627'; banArray[0] = '/rot_ban/v2lbanner.gif'; urlArray[1] = '/cgi-bin/banner_track.cgi?banner_id=4245'; banArray[1] = '/rot_ban/ir35_banner.gif'; if (browserType == "new") { document.swbanner.src = banArray[n]; startThread = setTimeout("rotateSWBanner()", 10000); }}
For starters, we have a nice big pile of global variables. We do a bunch of odd datetime operations, to populate the variable n. We have to give a special shoutout to modnum, which is set to 20, but um, as 2 * 10, because... we don't want to use any magic numbers, I guess?
n, by the time we're done, is the number of seconds, mod 20, divided by 10.
Speaking of unused values, altArray and popupArray are also never used in the code.
After all that, if browserType == "new" (which it definitely does, since we set it equal to "new" up above), we start a timeout to rotateSWBanner().
function rotateSWBanner(){ if (browserType == "new") { if (n < (2 - 1)) { n++; } else { n = 0; } imageSource = banArray[n]; thread = setTimeout("rotateSWBanner()", 10000); window.document.swbanner.src = imageSource; }}
Once again, we play with n, and implement the most awkward modulus operation. Once again, we're doing arithmetic instead of using magic numbers, because magic math is clearly a better option? But the core of the if is to make sure n rotates through the entire range of items in banArray, which again, we could just do a mod to accomplish that.
In any case, "magic numbers" are now supplanted by "magic math" as the new anti-pattern you should absolutely never use.
[Advertisement] Utilize BuildMaster to release your software with confidence, at the pace your business demands. Download today!