PSA: Time Variables

The Blog of Tom Webster

  2015-11-25 16:19:00 PST

This is a public service announcement about naming variables dealing with amounts of time. I’ve had the misfortune of dealing with some code recently that didn’t have properly named variables for different time-sensitive functions. What resulted is some confusion about why certain functions would never fire, even after the elapsed time.

The majority of the time variables in this application were in miliseconds, as is common in most of the code I work with. Unfortunately, miliseconds were not the only measure of time used in variables. There were integer variables that used seconds and even one that used hours. With no call out, comments, or specific names to differentiate them. What was set to 3600000 miliseconds was actually a variable for number of hours. Instead of firing every hour, as planned, because of the inspecific variable name and mixing of time units without comments, that event would fire once every ~411 days.

If you’re going to use variables for time, keep these things in mind:

  1. Only use one unit of time across your project, stick to seconds or miliseconds for everything. Call this out in the comments or readme. If you want to be really nice, you can use #2 as well.

  2. Call out the unit in all variable names. Yes, this can get tedious, but it really helps people looking at your code figure out your intent for the variable. Maybe making everything use seconds as the unit is too big, maybe you need something smaller, but settling for miliseconds across every value is kinda crazy, seeing as you want to use hours in a couple places. Why not socket_timeout_in_miliseconds or auto_backup_time_in_hours?

The only wrong answer is mixing units and leaving them a mystery to the next developer to pick up your code.