CodeSOD: Not a WTF
Sometimes, I have to wonder if I'm the dummy. Today I want to take a look at two examples from readers that are pretty close to code I've written, and I'm left wondering: am I the real WTF?
meowcow moocat writes:
This little gem of mathematic wizardry was in a shell script designed to check the existence of a pid file. If pid file was younger than an hour - do nothing. If older than an hour - delete it. The fantastic bit about the script was how the guy worked out seconds in an hour.
The offending code:
MAX_SECONDS = $((60*60*1))
I don't hate this. I understand that the *1 at the end is superfluous, but it also makes the intent a bit more clear. Sure, I could just make it 3600, but then I have to remember that 3600 is the number of seconds in an hour, and I hate that. I'd probably give that 1 a variable name, like LIFETIME_HOURS or something, but I like including the extra operation, for clarity. It's not the most efficient, but how many times is this line actually invoked? I'd rather have something more readable.
Michael on the other hand, found some code that needs to limit file uploads to 20MB. This was the responsible code:
// files must be less than 20MBif (round($uploadedFile->getSize() / 1024 / 1024) > 20) { [ ... throw some error message ]}
Okay, I have some problems here, though I'm not sure I consider them full on WTFs- specifically the round. But the general idea of spamming some 1024s in there doesn't bother me. I'd multiply instead of divide: if ($uploadedFile->getSize() > 20 * 1024 * 1024).
Again, better naming around constants and variables would be good, but I've written code very much like that.
So today's article either doesn't have a real WTF, or I am the real WTF.
[Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!